From ccfd44423f492cab860f513413c0979acf713fb8 Mon Sep 17 00:00:00 2001 From: brian hung Date: Tue, 20 Apr 2021 02:07:29 -0700 Subject: [PATCH 1/2] dist --- .gitignore | 3 +- dist/src/lib.d.ts | 50 + dist/src/plugins/cursor-plugin.d.ts | 8 + dist/src/plugins/keys.d.ts | 19 + dist/src/plugins/sync-plugin.d.ts | 74 + dist/src/plugins/undo-plugin.d.ts | 7 + dist/src/y-prosemirror.d.ts | 5 + dist/test.cjs | 11111 +++++++++++ dist/test.cjs.map | 1 + dist/test.js | 25582 ++++++++++++++++++++++++++ dist/test.js.map | 1 + dist/y-prosemirror.cjs | 1381 ++ dist/y-prosemirror.cjs.map | 1 + 13 files changed, 38241 insertions(+), 2 deletions(-) create mode 100644 dist/src/lib.d.ts create mode 100644 dist/src/plugins/cursor-plugin.d.ts create mode 100644 dist/src/plugins/keys.d.ts create mode 100644 dist/src/plugins/sync-plugin.d.ts create mode 100644 dist/src/plugins/undo-plugin.d.ts create mode 100644 dist/src/y-prosemirror.d.ts create mode 100644 dist/test.cjs create mode 100644 dist/test.cjs.map create mode 100644 dist/test.js create mode 100644 dist/test.js.map create mode 100644 dist/y-prosemirror.cjs create mode 100644 dist/y-prosemirror.cjs.map diff --git a/.gitignore b/.gitignore index 76add87..b512c09 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1 @@ -node_modules -dist \ No newline at end of file +node_modules \ No newline at end of file diff --git a/dist/src/lib.d.ts b/dist/src/lib.d.ts new file mode 100644 index 0000000..174cb64 --- /dev/null +++ b/dist/src/lib.d.ts @@ -0,0 +1,50 @@ +/** + * Utility method to convert a Prosemirror Doc Node into a Y.Doc. + * + * This can be used when importing existing content to Y.Doc for the first time, + * note that this should not be used to rehydrate a Y.Doc from a database once + * collaboration has begun as all history will be lost + * + * @param {Node} doc + * @param {string} xmlFragment + * @return {Y.Doc} + */ +export function prosemirrorToYDoc(doc: Node, xmlFragment?: string): any; +/** + * Utility method to convert Prosemirror compatible JSON into a Y.Doc. + * + * This can be used when importing existing content to Y.Doc for the first time, + * note that this should not be used to rehydrate a Y.Doc from a database once + * collaboration has begun as all history will be lost + * + * @param {Schema} schema + * @param {any} state + * @param {string} xmlFragment + * @return {Y.Doc} + */ +export function prosemirrorJSONToYDoc(schema: Schema, state: any, xmlFragment?: string): any; +/** + * Utility method to convert a Y.Doc to a Prosemirror Doc node. + * + * @param {Schema} schema + * @param {Y.Doc} ydoc + * @return {Node} + */ +export function yDocToProsemirror(schema: Schema, ydoc: any): Node; +/** + * Utility method to convert a Y.Doc to Prosemirror compatible JSON. + * + * @param {Y.Doc} ydoc + * @param {string} xmlFragment + * @return {Record} + */ +export function yDocToProsemirrorJSON(ydoc: any, xmlFragment?: string): Record; +export function setMeta(view: any, key: any, value: any): void; +export function absolutePositionToRelativePosition(pos: number, type: any, mapping: Map | Node[]>): any; +export function relativePositionToAbsolutePosition(y: any, documentType: any, relPos: any, mapping: Map | Node[]>): null | number; +/** + * Either a node if type is YXmlElement or an Array of text nodes if YXmlText + */ +export type ProsemirrorMapping = Map | Node[]>; +import { Node } from "prosemirror-model"; +import { Schema } from "prosemirror-model"; diff --git a/dist/src/plugins/cursor-plugin.d.ts b/dist/src/plugins/cursor-plugin.d.ts new file mode 100644 index 0000000..3c487b1 --- /dev/null +++ b/dist/src/plugins/cursor-plugin.d.ts @@ -0,0 +1,8 @@ +export function defaultCursorBuilder(user: any): HTMLSpanElement; +export function createDecorations(state: any, awareness: Awareness, createCursor: any): any; +export function yCursorPlugin(awareness: Awareness, { cursorBuilder, getSelection }?: { + cursorBuilder: (arg0: any) => HTMLElement; + getSelection: (arg0: any) => any; + cursorStateField: string; +}, cursorStateField?: string): any; +import { Awareness } from "y-protocols/awareness"; diff --git a/dist/src/plugins/keys.d.ts b/dist/src/plugins/keys.d.ts new file mode 100644 index 0000000..4d9d438 --- /dev/null +++ b/dist/src/plugins/keys.d.ts @@ -0,0 +1,19 @@ +/** + * The unique prosemirror plugin key for syncPlugin + * + * @public + */ +export const ySyncPluginKey: PluginKey; +/** + * The unique prosemirror plugin key for undoPlugin + * + * @public + */ +export const yUndoPluginKey: PluginKey; +/** + * The unique prosemirror plugin key for cursorPlugin + * + * @public + */ +export const yCursorPluginKey: PluginKey; +import { PluginKey } from "prosemirror-state"; diff --git a/dist/src/plugins/sync-plugin.d.ts b/dist/src/plugins/sync-plugin.d.ts new file mode 100644 index 0000000..6a5261c --- /dev/null +++ b/dist/src/plugins/sync-plugin.d.ts @@ -0,0 +1,74 @@ +export function isVisible(item: any, snapshot?: any): boolean; +export function ySyncPlugin(yXmlFragment: any, { colors, colorMapping, permanentUserData }?: YSyncOpts): any; +export function getRelativeSelection(pmbinding: any, state: any): { + anchor: any; + head: any; +}; +/** + * Binding for prosemirror. + * + * @protected + */ +export class ProsemirrorBinding { + /** + * @param {Y.XmlFragment} yXmlFragment The bind source + * @param {any} prosemirrorView The target binding + */ + constructor(yXmlFragment: any, prosemirrorView: any); + type: any; + prosemirrorView: any; + mux: any; + /** + * @type {ProsemirrorMapping} + */ + mapping: Map | PMNode[]>; + _observeFunction: any; + /** + * @type {Y.Doc} + */ + doc: any; + /** + * current selection as relative positions in the Yjs model + */ + beforeTransactionSelection: { + anchor: any; + head: any; + }; + beforeAllTransactions: () => void; + afterAllTransactions: () => void; + _domSelectionInView: boolean; + _isLocalCursorInView(): boolean; + _isDomSelectionInView(): boolean; + renderSnapshot(snapshot: any, prevSnapshot: any): void; + unrenderSnapshot(): void; + _forceRerender(): void; + /** + * @param {Y.Snapshot} snapshot + * @param {Y.Snapshot} prevSnapshot + * @param {Object} pluginState + */ + _renderSnapshot(snapshot: any, prevSnapshot: any, pluginState: any): void; + /** + * @param {Array} events + * @param {Y.Transaction} transaction + */ + _typeChanged(events: Array, transaction: any): void; + _prosemirrorChanged(doc: any): void; + destroy(): void; +} +export function updateYFragment(y: any, yDomFragment: any, pNode: any, mapping: Map | PMNode[]>): void; +/** + * Either a node if type is YXmlElement or an Array of text nodes if YXmlText + */ +export type ProsemirrorMapping = Map | PMNode[]>; +export type ColorDef = { + light: string; + dark: string; +}; +export type YSyncOpts = { + colors?: Array; + colorMapping?: Map; + permanentUserData?: any | null; +}; +export type NormalizedPNodeContent = (PMNode | PMNode[])[]; +import { Node as PMNode } from "prosemirror-model"; diff --git a/dist/src/plugins/undo-plugin.d.ts b/dist/src/plugins/undo-plugin.d.ts new file mode 100644 index 0000000..f05f781 --- /dev/null +++ b/dist/src/plugins/undo-plugin.d.ts @@ -0,0 +1,7 @@ +export function undo(state: any): boolean; +export function redo(state: any): boolean; +export function yUndoPlugin({ protectedNodes, trackedOrigins }?: { + protectedNodes?: Set; + trackedOrigins?: any[]; +}): Plugin; +import { Plugin } from "prosemirror-state"; diff --git a/dist/src/y-prosemirror.d.ts b/dist/src/y-prosemirror.d.ts new file mode 100644 index 0000000..708dbe7 --- /dev/null +++ b/dist/src/y-prosemirror.d.ts @@ -0,0 +1,5 @@ +export * from "./plugins/cursor-plugin.js"; +export * from "./plugins/undo-plugin.js"; +export * from "./plugins/keys.js"; +export { ySyncPlugin, isVisible, getRelativeSelection, ProsemirrorBinding } from "./plugins/sync-plugin.js"; +export { absolutePositionToRelativePosition, relativePositionToAbsolutePosition, setMeta, prosemirrorJSONToYDoc, yDocToProsemirrorJSON, yDocToProsemirror, prosemirrorToYDoc } from "./lib.js"; diff --git a/dist/test.cjs b/dist/test.cjs new file mode 100644 index 0000000..4925cae --- /dev/null +++ b/dist/test.cjs @@ -0,0 +1,11111 @@ +'use strict'; + +var fs = require('fs'); +var path = require('path'); +var jsdom = require('jsdom'); +var t = require('lib0/dist/testing.cjs'); +var prng = require('lib0/dist/prng.cjs'); +var math = require('lib0/dist/math.cjs'); +var observable_js = require('lib0/dist/observable.cjs'); +var array = require('lib0/dist/array.cjs'); +var map = require('lib0/dist/map.cjs'); +var encoding = require('lib0/dist/encoding.cjs'); +var decoding = require('lib0/dist/decoding.cjs'); +var random = require('lib0/dist/random.cjs'); +var buffer = require('lib0/dist/buffer.cjs'); +var error = require('lib0/dist/error.cjs'); +var binary = require('lib0/dist/binary.cjs'); +var f = require('lib0/dist/function.cjs'); +var set = require('lib0/dist/set.cjs'); +var logging = require('lib0/dist/logging.cjs'); +var time = require('lib0/dist/time.cjs'); +var iterator = require('lib0/dist/iterator.cjs'); +var object = require('lib0/dist/object.cjs'); +var prosemirrorView = require('prosemirror-view'); +var prosemirrorState = require('prosemirror-state'); +var mutex_js = require('lib0/dist/mutex.cjs'); +var prosemirrorModel = require('prosemirror-model'); +var diff_js = require('lib0/dist/diff.cjs'); +var environment_js = require('lib0/dist/environment.cjs'); +var dom_js = require('lib0/dist/dom.cjs'); +require('lib0/dist/eventloop.cjs'); +var basicSchema = require('prosemirror-schema-basic'); +var prosemirrorTransform = require('prosemirror-transform'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs); +var path__default = /*#__PURE__*/_interopDefaultLegacy(path); +var jsdom__default = /*#__PURE__*/_interopDefaultLegacy(jsdom); + +/** + * This is an abstract interface that all Connectors should implement to keep them interchangeable. + * + * @note This interface is experimental and it is not advised to actually inherit this class. + * It just serves as typing information. + * + * @extends {Observable} + */ +class AbstractConnector extends observable_js.Observable { + /** + * @param {Doc} ydoc + * @param {any} awareness + */ + constructor (ydoc, awareness) { + super(); + this.doc = ydoc; + this.awareness = awareness; + } +} + +class DeleteItem { + /** + * @param {number} clock + * @param {number} len + */ + constructor (clock, len) { + /** + * @type {number} + */ + this.clock = clock; + /** + * @type {number} + */ + this.len = len; + } +} + +/** + * We no longer maintain a DeleteStore. DeleteSet is a temporary object that is created when needed. + * - When created in a transaction, it must only be accessed after sorting, and merging + * - This DeleteSet is send to other clients + * - We do not create a DeleteSet when we send a sync message. The DeleteSet message is created directly from StructStore + * - We read a DeleteSet as part of a sync/update message. In this case the DeleteSet is already sorted and merged. + */ +class DeleteSet { + constructor () { + /** + * @type {Map>} + */ + this.clients = new Map(); + } +} + +/** + * Iterate over all structs that the DeleteSet gc's. + * + * @param {Transaction} transaction + * @param {DeleteSet} ds + * @param {function(GC|Item):void} f + * + * @function + */ +const iterateDeletedStructs = (transaction, ds, f) => + ds.clients.forEach((deletes, clientid) => { + const structs = /** @type {Array} */ (transaction.doc.store.clients.get(clientid)); + for (let i = 0; i < deletes.length; i++) { + const del = deletes[i]; + iterateStructs(transaction, structs, del.clock, del.len, f); + } + }); + +/** + * @param {Array} dis + * @param {number} clock + * @return {number|null} + * + * @private + * @function + */ +const findIndexDS = (dis, clock) => { + let left = 0; + let right = dis.length - 1; + while (left <= right) { + const midindex = math.floor((left + right) / 2); + const mid = dis[midindex]; + const midclock = mid.clock; + if (midclock <= clock) { + if (clock < midclock + mid.len) { + return midindex + } + left = midindex + 1; + } else { + right = midindex - 1; + } + } + return null +}; + +/** + * @param {DeleteSet} ds + * @param {ID} id + * @return {boolean} + * + * @private + * @function + */ +const isDeleted = (ds, id) => { + const dis = ds.clients.get(id.client); + return dis !== undefined && findIndexDS(dis, id.clock) !== null +}; + +/** + * @param {DeleteSet} ds + * + * @private + * @function + */ +const sortAndMergeDeleteSet = ds => { + ds.clients.forEach(dels => { + dels.sort((a, b) => a.clock - b.clock); + // merge items without filtering or splicing the array + // i is the current pointer + // j refers to the current insert position for the pointed item + // try to merge dels[i] into dels[j-1] or set dels[j]=dels[i] + let i, j; + for (i = 1, j = 1; i < dels.length; i++) { + const left = dels[j - 1]; + const right = dels[i]; + if (left.clock + left.len === right.clock) { + left.len += right.len; + } else { + if (j < i) { + dels[j] = right; + } + j++; + } + } + dels.length = j; + }); +}; + +/** + * @param {Array} dss + * @return {DeleteSet} A fresh DeleteSet + */ +const mergeDeleteSets = dss => { + const merged = new DeleteSet(); + for (let dssI = 0; dssI < dss.length; dssI++) { + dss[dssI].clients.forEach((delsLeft, client) => { + if (!merged.clients.has(client)) { + // Write all missing keys from current ds and all following. + // If merged already contains `client` current ds has already been added. + /** + * @type {Array} + */ + const dels = delsLeft.slice(); + for (let i = dssI + 1; i < dss.length; i++) { + array.appendTo(dels, dss[i].clients.get(client) || []); + } + merged.clients.set(client, dels); + } + }); + } + sortAndMergeDeleteSet(merged); + return merged +}; + +/** + * @param {DeleteSet} ds + * @param {number} client + * @param {number} clock + * @param {number} length + * + * @private + * @function + */ +const addToDeleteSet = (ds, client, clock, length) => { + map.setIfUndefined(ds.clients, client, () => []).push(new DeleteItem(clock, length)); +}; + +const createDeleteSet = () => new DeleteSet(); + +/** + * @param {StructStore} ss + * @return {DeleteSet} Merged and sorted DeleteSet + * + * @private + * @function + */ +const createDeleteSetFromStructStore = ss => { + const ds = createDeleteSet(); + ss.clients.forEach((structs, client) => { + /** + * @type {Array} + */ + const dsitems = []; + for (let i = 0; i < structs.length; i++) { + const struct = structs[i]; + if (struct.deleted) { + const clock = struct.id.clock; + let len = struct.length; + if (i + 1 < structs.length) { + for (let next = structs[i + 1]; i + 1 < structs.length && next.id.clock === clock + len && next.deleted; next = structs[++i + 1]) { + len += next.length; + } + } + dsitems.push(new DeleteItem(clock, len)); + } + } + if (dsitems.length > 0) { + ds.clients.set(client, dsitems); + } + }); + return ds +}; + +/** + * @param {AbstractDSEncoder} encoder + * @param {DeleteSet} ds + * + * @private + * @function + */ +const writeDeleteSet = (encoder, ds) => { + encoding.writeVarUint(encoder.restEncoder, ds.clients.size); + ds.clients.forEach((dsitems, client) => { + encoder.resetDsCurVal(); + encoding.writeVarUint(encoder.restEncoder, client); + const len = dsitems.length; + encoding.writeVarUint(encoder.restEncoder, len); + for (let i = 0; i < len; i++) { + const item = dsitems[i]; + encoder.writeDsClock(item.clock); + encoder.writeDsLen(item.len); + } + }); +}; + +/** + * @param {AbstractDSDecoder} decoder + * @return {DeleteSet} + * + * @private + * @function + */ +const readDeleteSet = decoder => { + const ds = new DeleteSet(); + const numClients = decoding.readVarUint(decoder.restDecoder); + for (let i = 0; i < numClients; i++) { + decoder.resetDsCurVal(); + const client = decoding.readVarUint(decoder.restDecoder); + const numberOfDeletes = decoding.readVarUint(decoder.restDecoder); + if (numberOfDeletes > 0) { + const dsField = map.setIfUndefined(ds.clients, client, () => []); + for (let i = 0; i < numberOfDeletes; i++) { + dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen())); + } + } + } + return ds +}; + +/** + * @todo YDecoder also contains references to String and other Decoders. Would make sense to exchange YDecoder.toUint8Array for YDecoder.DsToUint8Array().. + */ + +/** + * @param {AbstractDSDecoder} decoder + * @param {Transaction} transaction + * @param {StructStore} store + * + * @private + * @function + */ +const readAndApplyDeleteSet = (decoder, transaction, store) => { + const unappliedDS = new DeleteSet(); + const numClients = decoding.readVarUint(decoder.restDecoder); + for (let i = 0; i < numClients; i++) { + decoder.resetDsCurVal(); + const client = decoding.readVarUint(decoder.restDecoder); + const numberOfDeletes = decoding.readVarUint(decoder.restDecoder); + const structs = store.clients.get(client) || []; + const state = getState(store, client); + for (let i = 0; i < numberOfDeletes; i++) { + const clock = decoder.readDsClock(); + const clockEnd = clock + decoder.readDsLen(); + if (clock < state) { + if (state < clockEnd) { + addToDeleteSet(unappliedDS, client, state, clockEnd - state); + } + let index = findIndexSS(structs, clock); + /** + * We can ignore the case of GC and Delete structs, because we are going to skip them + * @type {Item} + */ + // @ts-ignore + let struct = structs[index]; + // split the first item if necessary + if (!struct.deleted && struct.id.clock < clock) { + structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); + index++; // increase we now want to use the next struct + } + while (index < structs.length) { + // @ts-ignore + struct = structs[index++]; + if (struct.id.clock < clockEnd) { + if (!struct.deleted) { + if (clockEnd < struct.id.clock + struct.length) { + structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock)); + } + struct.delete(transaction); + } + } else { + break + } + } + } else { + addToDeleteSet(unappliedDS, client, clock, clockEnd - clock); + } + } + } + if (unappliedDS.clients.size > 0) { + // TODO: no need for encoding+decoding ds anymore + const unappliedDSEncoder = new DSEncoderV2(); + writeDeleteSet(unappliedDSEncoder, unappliedDS); + store.pendingDeleteReaders.push(new DSDecoderV2(decoding.createDecoder((unappliedDSEncoder.toUint8Array())))); + } +}; + +/** + * @module Y + */ + +const generateNewClientId = random.uint32; + +/** + * @typedef {Object} DocOpts + * @property {boolean} [DocOpts.gc=true] Disable garbage collection (default: gc=true) + * @property {function(Item):boolean} [DocOpts.gcFilter] Will be called before an Item is garbage collected. Return false to keep the Item. + * @property {string} [DocOpts.guid] Define a globally unique identifier for this document + * @property {any} [DocOpts.meta] Any kind of meta information you want to associate with this document. If this is a subdocument, remote peers will store the meta information as well. + * @property {boolean} [DocOpts.autoLoad] If a subdocument, automatically load document. If this is a subdocument, remote peers will load the document as well automatically. + */ + +/** + * A Yjs instance handles the state of shared data. + * @extends Observable + */ +class Doc extends observable_js.Observable { + /** + * @param {DocOpts} [opts] configuration + */ + constructor ({ guid = random.uuidv4(), gc = true, gcFilter = () => true, meta = null, autoLoad = false } = {}) { + super(); + this.gc = gc; + this.gcFilter = gcFilter; + this.clientID = generateNewClientId(); + this.guid = guid; + /** + * @type {Map>} + */ + this.share = new Map(); + this.store = new StructStore(); + /** + * @type {Transaction | null} + */ + this._transaction = null; + /** + * @type {Array} + */ + this._transactionCleanups = []; + /** + * @type {Set} + */ + this.subdocs = new Set(); + /** + * If this document is a subdocument - a document integrated into another document - then _item is defined. + * @type {Item?} + */ + this._item = null; + this.shouldLoad = autoLoad; + this.autoLoad = autoLoad; + this.meta = meta; + } + + /** + * Notify the parent document that you request to load data into this subdocument (if it is a subdocument). + * + * `load()` might be used in the future to request any provider to load the most current data. + * + * It is safe to call `load()` multiple times. + */ + load () { + const item = this._item; + if (item !== null && !this.shouldLoad) { + transact(/** @type {any} */ (item.parent).doc, transaction => { + transaction.subdocsLoaded.add(this); + }, null, true); + } + this.shouldLoad = true; + } + + getSubdocs () { + return this.subdocs + } + + getSubdocGuids () { + return new Set(Array.from(this.subdocs).map(doc => doc.guid)) + } + + /** + * Changes that happen inside of a transaction are bundled. This means that + * the observer fires _after_ the transaction is finished and that all changes + * that happened inside of the transaction are sent as one message to the + * other peers. + * + * @param {function(Transaction):void} f The function that should be executed as a transaction + * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin + * + * @public + */ + transact (f, origin = null) { + transact(this, f, origin); + } + + /** + * Define a shared data type. + * + * Multiple calls of `y.get(name, TypeConstructor)` yield the same result + * and do not overwrite each other. I.e. + * `y.define(name, Y.Array) === y.define(name, Y.Array)` + * + * After this method is called, the type is also available on `y.share.get(name)`. + * + * *Best Practices:* + * Define all types right after the Yjs instance is created and store them in a separate object. + * Also use the typed methods `getText(name)`, `getArray(name)`, .. + * + * @example + * const y = new Y(..) + * const appState = { + * document: y.getText('document') + * comments: y.getArray('comments') + * } + * + * @param {string} name + * @param {Function} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ... + * @return {AbstractType} The created type. Constructed with TypeConstructor + * + * @public + */ + get (name, TypeConstructor = AbstractType) { + const type = map.setIfUndefined(this.share, name, () => { + // @ts-ignore + const t = new TypeConstructor(); + t._integrate(this, null); + return t + }); + const Constr = type.constructor; + if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) { + if (Constr === AbstractType) { + // @ts-ignore + const t = new TypeConstructor(); + t._map = type._map; + type._map.forEach(/** @param {Item?} n */ n => { + for (; n !== null; n = n.left) { + // @ts-ignore + n.parent = t; + } + }); + t._start = type._start; + for (let n = t._start; n !== null; n = n.right) { + n.parent = t; + } + t._length = type._length; + this.share.set(name, t); + t._integrate(this, null); + return t + } else { + throw new Error(`Type with the name ${name} has already been defined with a different constructor`) + } + } + return type + } + + /** + * @template T + * @param {string} [name] + * @return {YArray} + * + * @public + */ + getArray (name = '') { + // @ts-ignore + return this.get(name, YArray) + } + + /** + * @param {string} [name] + * @return {YText} + * + * @public + */ + getText (name = '') { + // @ts-ignore + return this.get(name, YText) + } + + /** + * @param {string} [name] + * @return {YMap} + * + * @public + */ + getMap (name = '') { + // @ts-ignore + return this.get(name, YMap) + } + + /** + * @param {string} [name] + * @return {YXmlFragment} + * + * @public + */ + getXmlFragment (name = '') { + // @ts-ignore + return this.get(name, YXmlFragment) + } + + /** + * Converts the entire document into a js object, recursively traversing each yjs type + * + * @return {Object} + */ + toJSON () { + /** + * @type {Object} + */ + const doc = {}; + + this.share.forEach((value, key) => { + doc[key] = value.toJSON(); + }); + + return doc + } + + /** + * Emit `destroy` event and unregister all event handlers. + */ + destroy () { + array.from(this.subdocs).forEach(subdoc => subdoc.destroy()); + const item = this._item; + if (item !== null) { + this._item = null; + const content = /** @type {ContentDoc} */ (item.content); + if (item.deleted) { + // @ts-ignore + content.doc = null; + } else { + content.doc = new Doc({ guid: this.guid, ...content.opts }); + content.doc._item = item; + } + transact(/** @type {any} */ (item).parent.doc, transaction => { + if (!item.deleted) { + transaction.subdocsAdded.add(content.doc); + } + transaction.subdocsRemoved.add(this); + }, null, true); + } + this.emit('destroyed', [true]); + super.destroy(); + } + + /** + * @param {string} eventName + * @param {function(...any):any} f + */ + on (eventName, f) { + super.on(eventName, f); + } + + /** + * @param {string} eventName + * @param {function} f + */ + off (eventName, f) { + super.off(eventName, f); + } +} + +class AbstractDSDecoder { + /** + * @param {decoding.Decoder} decoder + */ + constructor (decoder) { + this.restDecoder = decoder; + error.methodUnimplemented(); + } + + resetDsCurVal () { } + + /** + * @return {number} + */ + readDsClock () { + error.methodUnimplemented(); + } + + /** + * @return {number} + */ + readDsLen () { + error.methodUnimplemented(); + } +} + +class AbstractUpdateDecoder extends AbstractDSDecoder { + /** + * @return {ID} + */ + readLeftID () { + error.methodUnimplemented(); + } + + /** + * @return {ID} + */ + readRightID () { + error.methodUnimplemented(); + } + + /** + * Read the next client id. + * Use this in favor of readID whenever possible to reduce the number of objects created. + * + * @return {number} + */ + readClient () { + error.methodUnimplemented(); + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readInfo () { + error.methodUnimplemented(); + } + + /** + * @return {string} + */ + readString () { + error.methodUnimplemented(); + } + + /** + * @return {boolean} isKey + */ + readParentInfo () { + error.methodUnimplemented(); + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readTypeRef () { + error.methodUnimplemented(); + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @return {number} len + */ + readLen () { + error.methodUnimplemented(); + } + + /** + * @return {any} + */ + readAny () { + error.methodUnimplemented(); + } + + /** + * @return {Uint8Array} + */ + readBuf () { + error.methodUnimplemented(); + } + + /** + * Legacy implementation uses JSON parse. We use any-decoding in v2. + * + * @return {any} + */ + readJSON () { + error.methodUnimplemented(); + } + + /** + * @return {string} + */ + readKey () { + error.methodUnimplemented(); + } +} + +class DSDecoderV1 { + /** + * @param {decoding.Decoder} decoder + */ + constructor (decoder) { + this.restDecoder = decoder; + } + + resetDsCurVal () { + // nop + } + + /** + * @return {number} + */ + readDsClock () { + return decoding.readVarUint(this.restDecoder) + } + + /** + * @return {number} + */ + readDsLen () { + return decoding.readVarUint(this.restDecoder) + } +} + +class UpdateDecoderV1 extends DSDecoderV1 { + /** + * @return {ID} + */ + readLeftID () { + return createID(decoding.readVarUint(this.restDecoder), decoding.readVarUint(this.restDecoder)) + } + + /** + * @return {ID} + */ + readRightID () { + return createID(decoding.readVarUint(this.restDecoder), decoding.readVarUint(this.restDecoder)) + } + + /** + * Read the next client id. + * Use this in favor of readID whenever possible to reduce the number of objects created. + */ + readClient () { + return decoding.readVarUint(this.restDecoder) + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readInfo () { + return decoding.readUint8(this.restDecoder) + } + + /** + * @return {string} + */ + readString () { + return decoding.readVarString(this.restDecoder) + } + + /** + * @return {boolean} isKey + */ + readParentInfo () { + return decoding.readVarUint(this.restDecoder) === 1 + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readTypeRef () { + return decoding.readVarUint(this.restDecoder) + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @return {number} len + */ + readLen () { + return decoding.readVarUint(this.restDecoder) + } + + /** + * @return {any} + */ + readAny () { + return decoding.readAny(this.restDecoder) + } + + /** + * @return {Uint8Array} + */ + readBuf () { + return buffer.copyUint8Array(decoding.readVarUint8Array(this.restDecoder)) + } + + /** + * Legacy implementation uses JSON parse. We use any-decoding in v2. + * + * @return {any} + */ + readJSON () { + return JSON.parse(decoding.readVarString(this.restDecoder)) + } + + /** + * @return {string} + */ + readKey () { + return decoding.readVarString(this.restDecoder) + } +} + +class DSDecoderV2 { + /** + * @param {decoding.Decoder} decoder + */ + constructor (decoder) { + this.dsCurrVal = 0; + this.restDecoder = decoder; + } + + resetDsCurVal () { + this.dsCurrVal = 0; + } + + readDsClock () { + this.dsCurrVal += decoding.readVarUint(this.restDecoder); + return this.dsCurrVal + } + + readDsLen () { + const diff = decoding.readVarUint(this.restDecoder) + 1; + this.dsCurrVal += diff; + return diff + } +} + +class UpdateDecoderV2 extends DSDecoderV2 { + /** + * @param {decoding.Decoder} decoder + */ + constructor (decoder) { + super(decoder); + /** + * List of cached keys. If the keys[id] does not exist, we read a new key + * from stringEncoder and push it to keys. + * + * @type {Array} + */ + this.keys = []; + decoding.readUint8(decoder); // read feature flag - currently unused + this.keyClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder)); + this.clientDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder)); + this.leftClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder)); + this.rightClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder)); + this.infoDecoder = new decoding.RleDecoder(decoding.readVarUint8Array(decoder), decoding.readUint8); + this.stringDecoder = new decoding.StringDecoder(decoding.readVarUint8Array(decoder)); + this.parentInfoDecoder = new decoding.RleDecoder(decoding.readVarUint8Array(decoder), decoding.readUint8); + this.typeRefDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder)); + this.lenDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder)); + } + + /** + * @return {ID} + */ + readLeftID () { + return new ID(this.clientDecoder.read(), this.leftClockDecoder.read()) + } + + /** + * @return {ID} + */ + readRightID () { + return new ID(this.clientDecoder.read(), this.rightClockDecoder.read()) + } + + /** + * Read the next client id. + * Use this in favor of readID whenever possible to reduce the number of objects created. + */ + readClient () { + return this.clientDecoder.read() + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readInfo () { + return /** @type {number} */ (this.infoDecoder.read()) + } + + /** + * @return {string} + */ + readString () { + return this.stringDecoder.read() + } + + /** + * @return {boolean} + */ + readParentInfo () { + return this.parentInfoDecoder.read() === 1 + } + + /** + * @return {number} An unsigned 8-bit integer + */ + readTypeRef () { + return this.typeRefDecoder.read() + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @return {number} + */ + readLen () { + return this.lenDecoder.read() + } + + /** + * @return {any} + */ + readAny () { + return decoding.readAny(this.restDecoder) + } + + /** + * @return {Uint8Array} + */ + readBuf () { + return decoding.readVarUint8Array(this.restDecoder) + } + + /** + * This is mainly here for legacy purposes. + * + * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder. + * + * @return {any} + */ + readJSON () { + return decoding.readAny(this.restDecoder) + } + + /** + * @return {string} + */ + readKey () { + const keyClock = this.keyClockDecoder.read(); + if (keyClock < this.keys.length) { + return this.keys[keyClock] + } else { + const key = this.stringDecoder.read(); + this.keys.push(key); + return key + } + } +} + +class AbstractDSEncoder { + constructor () { + this.restEncoder = encoding.createEncoder(); + } + + /** + * @return {Uint8Array} + */ + toUint8Array () { + error.methodUnimplemented(); + } + + /** + * Resets the ds value to 0. + * The v2 encoder uses this information to reset the initial diff value. + */ + resetDsCurVal () { } + + /** + * @param {number} clock + */ + writeDsClock (clock) { } + + /** + * @param {number} len + */ + writeDsLen (len) { } +} + +class AbstractUpdateEncoder extends AbstractDSEncoder { + /** + * @return {Uint8Array} + */ + toUint8Array () { + error.methodUnimplemented(); + } + + /** + * @param {ID} id + */ + writeLeftID (id) { } + + /** + * @param {ID} id + */ + writeRightID (id) { } + + /** + * Use writeClient and writeClock instead of writeID if possible. + * @param {number} client + */ + writeClient (client) { } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeInfo (info) { } + + /** + * @param {string} s + */ + writeString (s) { } + + /** + * @param {boolean} isYKey + */ + writeParentInfo (isYKey) { } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeTypeRef (info) { } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @param {number} len + */ + writeLen (len) { } + + /** + * @param {any} any + */ + writeAny (any) { } + + /** + * @param {Uint8Array} buf + */ + writeBuf (buf) { } + + /** + * @param {any} embed + */ + writeJSON (embed) { } + + /** + * @param {string} key + */ + writeKey (key) { } +} + +class DSEncoderV1 { + constructor () { + this.restEncoder = new encoding.Encoder(); + } + + toUint8Array () { + return encoding.toUint8Array(this.restEncoder) + } + + resetDsCurVal () { + // nop + } + + /** + * @param {number} clock + */ + writeDsClock (clock) { + encoding.writeVarUint(this.restEncoder, clock); + } + + /** + * @param {number} len + */ + writeDsLen (len) { + encoding.writeVarUint(this.restEncoder, len); + } +} + +class UpdateEncoderV1 extends DSEncoderV1 { + /** + * @param {ID} id + */ + writeLeftID (id) { + encoding.writeVarUint(this.restEncoder, id.client); + encoding.writeVarUint(this.restEncoder, id.clock); + } + + /** + * @param {ID} id + */ + writeRightID (id) { + encoding.writeVarUint(this.restEncoder, id.client); + encoding.writeVarUint(this.restEncoder, id.clock); + } + + /** + * Use writeClient and writeClock instead of writeID if possible. + * @param {number} client + */ + writeClient (client) { + encoding.writeVarUint(this.restEncoder, client); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeInfo (info) { + encoding.writeUint8(this.restEncoder, info); + } + + /** + * @param {string} s + */ + writeString (s) { + encoding.writeVarString(this.restEncoder, s); + } + + /** + * @param {boolean} isYKey + */ + writeParentInfo (isYKey) { + encoding.writeVarUint(this.restEncoder, isYKey ? 1 : 0); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeTypeRef (info) { + encoding.writeVarUint(this.restEncoder, info); + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @param {number} len + */ + writeLen (len) { + encoding.writeVarUint(this.restEncoder, len); + } + + /** + * @param {any} any + */ + writeAny (any) { + encoding.writeAny(this.restEncoder, any); + } + + /** + * @param {Uint8Array} buf + */ + writeBuf (buf) { + encoding.writeVarUint8Array(this.restEncoder, buf); + } + + /** + * @param {any} embed + */ + writeJSON (embed) { + encoding.writeVarString(this.restEncoder, JSON.stringify(embed)); + } + + /** + * @param {string} key + */ + writeKey (key) { + encoding.writeVarString(this.restEncoder, key); + } +} + +class DSEncoderV2 { + constructor () { + this.restEncoder = new encoding.Encoder(); // encodes all the rest / non-optimized + this.dsCurrVal = 0; + } + + toUint8Array () { + return encoding.toUint8Array(this.restEncoder) + } + + resetDsCurVal () { + this.dsCurrVal = 0; + } + + /** + * @param {number} clock + */ + writeDsClock (clock) { + const diff = clock - this.dsCurrVal; + this.dsCurrVal = clock; + encoding.writeVarUint(this.restEncoder, diff); + } + + /** + * @param {number} len + */ + writeDsLen (len) { + if (len === 0) { + error.unexpectedCase(); + } + encoding.writeVarUint(this.restEncoder, len - 1); + this.dsCurrVal += len; + } +} + +class UpdateEncoderV2 extends DSEncoderV2 { + constructor () { + super(); + /** + * @type {Map} + */ + this.keyMap = new Map(); + /** + * Refers to the next uniqe key-identifier to me used. + * See writeKey method for more information. + * + * @type {number} + */ + this.keyClock = 0; + this.keyClockEncoder = new encoding.IntDiffOptRleEncoder(); + this.clientEncoder = new encoding.UintOptRleEncoder(); + this.leftClockEncoder = new encoding.IntDiffOptRleEncoder(); + this.rightClockEncoder = new encoding.IntDiffOptRleEncoder(); + this.infoEncoder = new encoding.RleEncoder(encoding.writeUint8); + this.stringEncoder = new encoding.StringEncoder(); + this.parentInfoEncoder = new encoding.RleEncoder(encoding.writeUint8); + this.typeRefEncoder = new encoding.UintOptRleEncoder(); + this.lenEncoder = new encoding.UintOptRleEncoder(); + } + + toUint8Array () { + const encoder = encoding.createEncoder(); + encoding.writeUint8(encoder, 0); // this is a feature flag that we might use in the future + encoding.writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array()); + encoding.writeVarUint8Array(encoder, this.clientEncoder.toUint8Array()); + encoding.writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array()); + encoding.writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array()); + encoding.writeVarUint8Array(encoder, encoding.toUint8Array(this.infoEncoder)); + encoding.writeVarUint8Array(encoder, this.stringEncoder.toUint8Array()); + encoding.writeVarUint8Array(encoder, encoding.toUint8Array(this.parentInfoEncoder)); + encoding.writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array()); + encoding.writeVarUint8Array(encoder, this.lenEncoder.toUint8Array()); + // @note The rest encoder is appended! (note the missing var) + encoding.writeUint8Array(encoder, encoding.toUint8Array(this.restEncoder)); + return encoding.toUint8Array(encoder) + } + + /** + * @param {ID} id + */ + writeLeftID (id) { + this.clientEncoder.write(id.client); + this.leftClockEncoder.write(id.clock); + } + + /** + * @param {ID} id + */ + writeRightID (id) { + this.clientEncoder.write(id.client); + this.rightClockEncoder.write(id.clock); + } + + /** + * @param {number} client + */ + writeClient (client) { + this.clientEncoder.write(client); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeInfo (info) { + this.infoEncoder.write(info); + } + + /** + * @param {string} s + */ + writeString (s) { + this.stringEncoder.write(s); + } + + /** + * @param {boolean} isYKey + */ + writeParentInfo (isYKey) { + this.parentInfoEncoder.write(isYKey ? 1 : 0); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeTypeRef (info) { + this.typeRefEncoder.write(info); + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @param {number} len + */ + writeLen (len) { + this.lenEncoder.write(len); + } + + /** + * @param {any} any + */ + writeAny (any) { + encoding.writeAny(this.restEncoder, any); + } + + /** + * @param {Uint8Array} buf + */ + writeBuf (buf) { + encoding.writeVarUint8Array(this.restEncoder, buf); + } + + /** + * This is mainly here for legacy purposes. + * + * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder. + * + * @param {any} embed + */ + writeJSON (embed) { + encoding.writeAny(this.restEncoder, embed); + } + + /** + * Property keys are often reused. For example, in y-prosemirror the key `bold` might + * occur very often. For a 3d application, the key `position` might occur very often. + * + * We cache these keys in a Map and refer to them via a unique number. + * + * @param {string} key + */ + writeKey (key) { + const clock = this.keyMap.get(key); + if (clock === undefined) { + this.keyClockEncoder.write(this.keyClock++); + this.stringEncoder.write(key); + } else { + this.keyClockEncoder.write(this.keyClock++); + } + } +} + +let DefaultDSEncoder = DSEncoderV1; +let DefaultDSDecoder = DSDecoderV1; +let DefaultUpdateEncoder = UpdateEncoderV1; +let DefaultUpdateDecoder = UpdateDecoderV1; + +const useV1Encoding = () => { + DefaultDSEncoder = DSEncoderV1; + DefaultDSDecoder = DSDecoderV1; + DefaultUpdateEncoder = UpdateEncoderV1; + DefaultUpdateDecoder = UpdateDecoderV1; +}; + +const useV2Encoding = () => { + DefaultDSEncoder = DSEncoderV2; + DefaultDSDecoder = DSDecoderV2; + DefaultUpdateEncoder = UpdateEncoderV2; + DefaultUpdateDecoder = UpdateDecoderV2; +}; + +/** + * @param {AbstractUpdateEncoder} encoder + * @param {Array} structs All structs by `client` + * @param {number} client + * @param {number} clock write structs starting with `ID(client,clock)` + * + * @function + */ +const writeStructs = (encoder, structs, client, clock) => { + // write first id + const startNewStructs = findIndexSS(structs, clock); + // write # encoded structs + encoding.writeVarUint(encoder.restEncoder, structs.length - startNewStructs); + encoder.writeClient(client); + encoding.writeVarUint(encoder.restEncoder, clock); + const firstStruct = structs[startNewStructs]; + // write first struct with an offset + firstStruct.write(encoder, clock - firstStruct.id.clock); + for (let i = startNewStructs + 1; i < structs.length; i++) { + structs[i].write(encoder, 0); + } +}; + +/** + * @param {AbstractUpdateEncoder} encoder + * @param {StructStore} store + * @param {Map} _sm + * + * @private + * @function + */ +const writeClientsStructs = (encoder, store, _sm) => { + // we filter all valid _sm entries into sm + const sm = new Map(); + _sm.forEach((clock, client) => { + // only write if new structs are available + if (getState(store, client) > clock) { + sm.set(client, clock); + } + }); + getStateVector(store).forEach((clock, client) => { + if (!_sm.has(client)) { + sm.set(client, 0); + } + }); + // write # states that were updated + encoding.writeVarUint(encoder.restEncoder, sm.size); + // Write items with higher client ids first + // This heavily improves the conflict algorithm. + Array.from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => { + // @ts-ignore + writeStructs(encoder, store.clients.get(client), client, clock); + }); +}; + +/** + * @param {AbstractUpdateDecoder} decoder The decoder object to read data from. + * @param {Map>} clientRefs + * @param {Doc} doc + * @return {Map>} + * + * @private + * @function + */ +const readClientsStructRefs = (decoder, clientRefs, doc) => { + const numOfStateUpdates = decoding.readVarUint(decoder.restDecoder); + for (let i = 0; i < numOfStateUpdates; i++) { + const numberOfStructs = decoding.readVarUint(decoder.restDecoder); + /** + * @type {Array} + */ + const refs = new Array(numberOfStructs); + const client = decoder.readClient(); + let clock = decoding.readVarUint(decoder.restDecoder); + // const start = performance.now() + clientRefs.set(client, refs); + for (let i = 0; i < numberOfStructs; i++) { + const info = decoder.readInfo(); + if ((binary.BITS5 & info) !== 0) { + /** + * The optimized implementation doesn't use any variables because inlining variables is faster. + * Below a non-optimized version is shown that implements the basic algorithm with + * a few comments + */ + const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0; + // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y` + // and we read the next string as parentYKey. + // It indicates how we store/retrieve parent from `y.share` + // @type {string|null} + const struct = new Item( + createID(client, clock), + null, // leftd + (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null, // origin + null, // right + (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null, // right origin + cantCopyParentInfo ? (decoder.readParentInfo() ? doc.get(decoder.readString()) : decoder.readLeftID()) : null, // parent + cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub + readItemContent(decoder, info) // item content + ); + /* A non-optimized implementation of the above algorithm: + + // The item that was originally to the left of this item. + const origin = (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null + // The item that was originally to the right of this item. + const rightOrigin = (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null + const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0 + const hasParentYKey = cantCopyParentInfo ? decoder.readParentInfo() : false + // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y` + // and we read the next string as parentYKey. + // It indicates how we store/retrieve parent from `y.share` + // @type {string|null} + const parentYKey = cantCopyParentInfo && hasParentYKey ? decoder.readString() : null + + const struct = new Item( + createID(client, clock), + null, // leftd + origin, // origin + null, // right + rightOrigin, // right origin + cantCopyParentInfo && !hasParentYKey ? decoder.readLeftID() : (parentYKey !== null ? doc.get(parentYKey) : null), // parent + cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub + readItemContent(decoder, info) // item content + ) + */ + refs[i] = struct; + clock += struct.length; + } else { + const len = decoder.readLen(); + refs[i] = new GC(createID(client, clock), len); + clock += len; + } + } + // console.log('time to read: ', performance.now() - start) // @todo remove + } + return clientRefs +}; + +/** + * Resume computing structs generated by struct readers. + * + * While there is something to do, we integrate structs in this order + * 1. top element on stack, if stack is not empty + * 2. next element from current struct reader (if empty, use next struct reader) + * + * If struct causally depends on another struct (ref.missing), we put next reader of + * `ref.id.client` on top of stack. + * + * At some point we find a struct that has no causal dependencies, + * then we start emptying the stack. + * + * It is not possible to have circles: i.e. struct1 (from client1) depends on struct2 (from client2) + * depends on struct3 (from client1). Therefore the max stack size is eqaul to `structReaders.length`. + * + * This method is implemented in a way so that we can resume computation if this update + * causally depends on another update. + * + * @param {Transaction} transaction + * @param {StructStore} store + * + * @private + * @function + */ +const resumeStructIntegration = (transaction, store) => { + const stack = store.pendingStack; // @todo don't forget to append stackhead at the end + const clientsStructRefs = store.pendingClientsStructRefs; + // sort them so that we take the higher id first, in case of conflicts the lower id will probably not conflict with the id from the higher user. + const clientsStructRefsIds = Array.from(clientsStructRefs.keys()).sort((a, b) => a - b); + if (clientsStructRefsIds.length === 0) { + return + } + const getNextStructTarget = () => { + let nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1])); + while (nextStructsTarget.refs.length === nextStructsTarget.i) { + clientsStructRefsIds.pop(); + if (clientsStructRefsIds.length > 0) { + nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1])); + } else { + store.pendingClientsStructRefs.clear(); + return null + } + } + return nextStructsTarget + }; + let curStructsTarget = getNextStructTarget(); + if (curStructsTarget === null && stack.length === 0) { + return + } + /** + * @type {GC|Item} + */ + let stackHead = stack.length > 0 + ? /** @type {GC|Item} */ (stack.pop()) + : /** @type {any} */ (curStructsTarget).refs[/** @type {any} */ (curStructsTarget).i++]; + // caching the state because it is used very often + const state = new Map(); + // iterate over all struct readers until we are done + while (true) { + const localClock = map.setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client)); + const offset = stackHead.id.clock < localClock ? localClock - stackHead.id.clock : 0; + if (stackHead.id.clock + offset !== localClock) { + // A previous message from this client is missing + // check if there is a pending structRef with a smaller clock and switch them + /** + * @type {{ refs: Array, i: number }} + */ + const structRefs = clientsStructRefs.get(stackHead.id.client) || { refs: [], i: 0 }; + if (structRefs.refs.length !== structRefs.i) { + const r = structRefs.refs[structRefs.i]; + if (r.id.clock < stackHead.id.clock) { + // put ref with smaller clock on stack instead and continue + structRefs.refs[structRefs.i] = stackHead; + stackHead = r; + // sort the set because this approach might bring the list out of order + structRefs.refs = structRefs.refs.slice(structRefs.i).sort((r1, r2) => r1.id.clock - r2.id.clock); + structRefs.i = 0; + continue + } + } + // wait until missing struct is available + stack.push(stackHead); + return + } + const missing = stackHead.getMissing(transaction, store); + if (missing === null) { + if (offset === 0 || offset < stackHead.length) { + stackHead.integrate(transaction, offset); + state.set(stackHead.id.client, stackHead.id.clock + stackHead.length); + } + // iterate to next stackHead + if (stack.length > 0) { + stackHead = /** @type {GC|Item} */ (stack.pop()); + } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) { + stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++]); + } else { + curStructsTarget = getNextStructTarget(); + if (curStructsTarget === null) { + // we are done! + break + } else { + stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++]); + } + } + } else { + // get the struct reader that has the missing struct + /** + * @type {{ refs: Array, i: number }} + */ + const structRefs = clientsStructRefs.get(missing) || { refs: [], i: 0 }; + if (structRefs.refs.length === structRefs.i) { + // This update message causally depends on another update message. + stack.push(stackHead); + return + } + stack.push(stackHead); + stackHead = structRefs.refs[structRefs.i++]; + } + } + store.pendingClientsStructRefs.clear(); +}; + +/** + * @param {Transaction} transaction + * @param {StructStore} store + * + * @private + * @function + */ +const tryResumePendingDeleteReaders = (transaction, store) => { + const pendingReaders = store.pendingDeleteReaders; + store.pendingDeleteReaders = []; + for (let i = 0; i < pendingReaders.length; i++) { + readAndApplyDeleteSet(pendingReaders[i], transaction, store); + } +}; + +/** + * @param {AbstractUpdateEncoder} encoder + * @param {Transaction} transaction + * + * @private + * @function + */ +const writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState); + +/** + * @param {StructStore} store + * @param {Map>} clientsStructsRefs + * + * @private + * @function + */ +const mergeReadStructsIntoPendingReads = (store, clientsStructsRefs) => { + const pendingClientsStructRefs = store.pendingClientsStructRefs; + clientsStructsRefs.forEach((structRefs, client) => { + const pendingStructRefs = pendingClientsStructRefs.get(client); + if (pendingStructRefs === undefined) { + pendingClientsStructRefs.set(client, { refs: structRefs, i: 0 }); + } else { + // merge into existing structRefs + const merged = pendingStructRefs.i > 0 ? pendingStructRefs.refs.slice(pendingStructRefs.i) : pendingStructRefs.refs; + for (let i = 0; i < structRefs.length; i++) { + merged.push(structRefs[i]); + } + pendingStructRefs.i = 0; + pendingStructRefs.refs = merged.sort((r1, r2) => r1.id.clock - r2.id.clock); + } + }); +}; + +/** + * @param {Map,i:number}>} pendingClientsStructRefs + */ +const cleanupPendingStructs = pendingClientsStructRefs => { + // cleanup pendingClientsStructs if not fully finished + pendingClientsStructRefs.forEach((refs, client) => { + if (refs.i === refs.refs.length) { + pendingClientsStructRefs.delete(client); + } else { + refs.refs.splice(0, refs.i); + refs.i = 0; + } + }); +}; + +/** + * Read the next Item in a Decoder and fill this Item with the read data. + * + * This is called when data is received from a remote peer. + * + * @param {AbstractUpdateDecoder} decoder The decoder object to read data from. + * @param {Transaction} transaction + * @param {StructStore} store + * + * @private + * @function + */ +const readStructs = (decoder, transaction, store) => { + const clientsStructRefs = new Map(); + // let start = performance.now() + readClientsStructRefs(decoder, clientsStructRefs, transaction.doc); + // console.log('time to read structs: ', performance.now() - start) // @todo remove + // start = performance.now() + mergeReadStructsIntoPendingReads(store, clientsStructRefs); + // console.log('time to merge: ', performance.now() - start) // @todo remove + // start = performance.now() + resumeStructIntegration(transaction, store); + // console.log('time to integrate: ', performance.now() - start) // @todo remove + // start = performance.now() + cleanupPendingStructs(store.pendingClientsStructRefs); + // console.log('time to cleanup: ', performance.now() - start) // @todo remove + // start = performance.now() + tryResumePendingDeleteReaders(transaction, store); + // console.log('time to resume delete readers: ', performance.now() - start) // @todo remove + // start = performance.now() +}; + +/** + * Read and apply a document update. + * + * This function has the same effect as `applyUpdate` but accepts an decoder. + * + * @param {decoding.Decoder} decoder + * @param {Doc} ydoc + * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))` + * @param {AbstractUpdateDecoder} [structDecoder] + * + * @function + */ +const readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) => + transact(ydoc, transaction => { + readStructs(structDecoder, transaction, ydoc.store); + readAndApplyDeleteSet(structDecoder, transaction, ydoc.store); + }, transactionOrigin, false); + +/** + * Read and apply a document update. + * + * This function has the same effect as `applyUpdate` but accepts an decoder. + * + * @param {decoding.Decoder} decoder + * @param {Doc} ydoc + * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))` + * + * @function + */ +const readUpdate = (decoder, ydoc, transactionOrigin) => readUpdateV2(decoder, ydoc, transactionOrigin, new DefaultUpdateDecoder(decoder)); + +/** + * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`. + * + * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder. + * + * @param {Doc} ydoc + * @param {Uint8Array} update + * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))` + * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder] + * + * @function + */ +const applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => { + const decoder = decoding.createDecoder(update); + readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder)); +}; + +/** + * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`. + * + * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder. + * + * @param {Doc} ydoc + * @param {Uint8Array} update + * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))` + * + * @function + */ +const applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, DefaultUpdateDecoder); + +/** + * Write all the document as a single update message. If you specify the state of the remote client (`targetStateVector`) it will + * only write the operations that are missing. + * + * @param {AbstractUpdateEncoder} encoder + * @param {Doc} doc + * @param {Map} [targetStateVector] The state of the target that receives the update. Leave empty to write all known structs + * + * @function + */ +const writeStateAsUpdate = (encoder, doc, targetStateVector = new Map()) => { + writeClientsStructs(encoder, doc.store, targetStateVector); + writeDeleteSet(encoder, createDeleteSetFromStructStore(doc.store)); +}; + +/** + * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will + * only write the operations that are missing. + * + * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder + * + * @param {Doc} doc + * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs + * @param {AbstractUpdateEncoder} [encoder] + * @return {Uint8Array} + * + * @function + */ +const encodeStateAsUpdateV2 = (doc, encodedTargetStateVector, encoder = new UpdateEncoderV2()) => { + const targetStateVector = encodedTargetStateVector == null ? new Map() : decodeStateVector(encodedTargetStateVector); + writeStateAsUpdate(encoder, doc, targetStateVector); + return encoder.toUint8Array() +}; + +/** + * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will + * only write the operations that are missing. + * + * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder + * + * @param {Doc} doc + * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs + * @return {Uint8Array} + * + * @function + */ +const encodeStateAsUpdate = (doc, encodedTargetStateVector) => encodeStateAsUpdateV2(doc, encodedTargetStateVector, new DefaultUpdateEncoder()); + +/** + * Read state vector from Decoder and return as Map + * + * @param {AbstractDSDecoder} decoder + * @return {Map} Maps `client` to the number next expected `clock` from that client. + * + * @function + */ +const readStateVector = decoder => { + const ss = new Map(); + const ssLength = decoding.readVarUint(decoder.restDecoder); + for (let i = 0; i < ssLength; i++) { + const client = decoding.readVarUint(decoder.restDecoder); + const clock = decoding.readVarUint(decoder.restDecoder); + ss.set(client, clock); + } + return ss +}; + +/** + * Read decodedState and return State as Map. + * + * @param {Uint8Array} decodedState + * @return {Map} Maps `client` to the number next expected `clock` from that client. + * + * @function + */ +const decodeStateVectorV2 = decodedState => readStateVector(new DSDecoderV2(decoding.createDecoder(decodedState))); + +/** + * Read decodedState and return State as Map. + * + * @param {Uint8Array} decodedState + * @return {Map} Maps `client` to the number next expected `clock` from that client. + * + * @function + */ +const decodeStateVector = decodedState => readStateVector(new DefaultDSDecoder(decoding.createDecoder(decodedState))); + +/** + * @param {AbstractDSEncoder} encoder + * @param {Map} sv + * @function + */ +const writeStateVector = (encoder, sv) => { + encoding.writeVarUint(encoder.restEncoder, sv.size); + sv.forEach((clock, client) => { + encoding.writeVarUint(encoder.restEncoder, client); // @todo use a special client decoder that is based on mapping + encoding.writeVarUint(encoder.restEncoder, clock); + }); + return encoder +}; + +/** + * @param {AbstractDSEncoder} encoder + * @param {Doc} doc + * + * @function + */ +const writeDocumentStateVector = (encoder, doc) => writeStateVector(encoder, getStateVector(doc.store)); + +/** + * Encode State as Uint8Array. + * + * @param {Doc} doc + * @param {AbstractDSEncoder} [encoder] + * @return {Uint8Array} + * + * @function + */ +const encodeStateVectorV2 = (doc, encoder = new DSEncoderV2()) => { + writeDocumentStateVector(encoder, doc); + return encoder.toUint8Array() +}; + +/** + * Encode State as Uint8Array. + * + * @param {Doc} doc + * @return {Uint8Array} + * + * @function + */ +const encodeStateVector = doc => encodeStateVectorV2(doc, new DefaultDSEncoder()); + +/** + * General event handler implementation. + * + * @template ARG0, ARG1 + * + * @private + */ +class EventHandler { + constructor () { + /** + * @type {Array} + */ + this.l = []; + } +} + +/** + * @template ARG0,ARG1 + * @returns {EventHandler} + * + * @private + * @function + */ +const createEventHandler = () => new EventHandler(); + +/** + * Adds an event listener that is called when + * {@link EventHandler#callEventListeners} is called. + * + * @template ARG0,ARG1 + * @param {EventHandler} eventHandler + * @param {function(ARG0,ARG1):void} f The event handler. + * + * @private + * @function + */ +const addEventHandlerListener = (eventHandler, f) => + eventHandler.l.push(f); + +/** + * Removes an event listener. + * + * @template ARG0,ARG1 + * @param {EventHandler} eventHandler + * @param {function(ARG0,ARG1):void} f The event handler that was added with + * {@link EventHandler#addEventListener} + * + * @private + * @function + */ +const removeEventHandlerListener = (eventHandler, f) => { + const l = eventHandler.l; + const len = l.length; + eventHandler.l = l.filter(g => f !== g); + if (len === eventHandler.l.length) { + console.error('[yjs] Tried to remove event handler that doesn\'t exist.'); + } +}; + +/** + * Removes all event listeners. + * @template ARG0,ARG1 + * @param {EventHandler} eventHandler + * + * @private + * @function + */ +const removeAllEventHandlerListeners = eventHandler => { + eventHandler.l.length = 0; +}; + +/** + * Call all event listeners that were added via + * {@link EventHandler#addEventListener}. + * + * @template ARG0,ARG1 + * @param {EventHandler} eventHandler + * @param {ARG0} arg0 + * @param {ARG1} arg1 + * + * @private + * @function + */ +const callEventHandlerListeners = (eventHandler, arg0, arg1) => + f.callAll(eventHandler.l, [arg0, arg1]); + +class ID { + /** + * @param {number} client client id + * @param {number} clock unique per client id, continuous number + */ + constructor (client, clock) { + /** + * Client id + * @type {number} + */ + this.client = client; + /** + * unique per client id, continuous number + * @type {number} + */ + this.clock = clock; + } +} + +/** + * @param {ID | null} a + * @param {ID | null} b + * @return {boolean} + * + * @function + */ +const compareIDs = (a, b) => a === b || (a !== null && b !== null && a.client === b.client && a.clock === b.clock); + +/** + * @param {number} client + * @param {number} clock + * + * @private + * @function + */ +const createID = (client, clock) => new ID(client, clock); + +/** + * @param {encoding.Encoder} encoder + * @param {ID} id + * + * @private + * @function + */ +const writeID = (encoder, id) => { + encoding.writeVarUint(encoder, id.client); + encoding.writeVarUint(encoder, id.clock); +}; + +/** + * Read ID. + * * If first varUint read is 0xFFFFFF a RootID is returned. + * * Otherwise an ID is returned + * + * @param {decoding.Decoder} decoder + * @return {ID} + * + * @private + * @function + */ +const readID = decoder => + createID(decoding.readVarUint(decoder), decoding.readVarUint(decoder)); + +/** + * The top types are mapped from y.share.get(keyname) => type. + * `type` does not store any information about the `keyname`. + * This function finds the correct `keyname` for `type` and throws otherwise. + * + * @param {AbstractType} type + * @return {string} + * + * @private + * @function + */ +const findRootTypeKey = type => { + // @ts-ignore _y must be defined, otherwise unexpected case + for (const [key, value] of type.doc.share.entries()) { + if (value === type) { + return key + } + } + throw error.unexpectedCase() +}; + +/** + * Check if `parent` is a parent of `child`. + * + * @param {AbstractType} parent + * @param {Item|null} child + * @return {Boolean} Whether `parent` is a parent of `child`. + * + * @private + * @function + */ +const isParentOf = (parent, child) => { + while (child !== null) { + if (child.parent === parent) { + return true + } + child = /** @type {AbstractType} */ (child.parent)._item; + } + return false +}; + +/** + * Convenient helper to log type information. + * + * Do not use in productive systems as the output can be immense! + * + * @param {AbstractType} type + */ +const logType = type => { + const res = []; + let n = type._start; + while (n) { + res.push(n); + n = n.right; + } + console.log('Children: ', res); + console.log('Children content: ', res.filter(m => !m.deleted).map(m => m.content)); +}; + +class PermanentUserData { + /** + * @param {Doc} doc + * @param {YMap} [storeType] + */ + constructor (doc, storeType = doc.getMap('users')) { + /** + * @type {Map} + */ + const dss = new Map(); + this.yusers = storeType; + this.doc = doc; + /** + * Maps from clientid to userDescription + * + * @type {Map} + */ + this.clients = new Map(); + this.dss = dss; + /** + * @param {YMap} user + * @param {string} userDescription + */ + const initUser = (user, userDescription) => { + /** + * @type {YArray} + */ + const ds = user.get('ds'); + const ids = user.get('ids'); + const addClientId = /** @param {number} clientid */ clientid => this.clients.set(clientid, userDescription); + ds.observe(/** @param {YArrayEvent} event */ event => { + event.changes.added.forEach(item => { + item.content.getContent().forEach(encodedDs => { + if (encodedDs instanceof Uint8Array) { + this.dss.set(userDescription, mergeDeleteSets([this.dss.get(userDescription) || createDeleteSet(), readDeleteSet(new DSDecoderV1(decoding.createDecoder(encodedDs)))])); + } + }); + }); + }); + this.dss.set(userDescription, mergeDeleteSets(ds.map(encodedDs => readDeleteSet(new DSDecoderV1(decoding.createDecoder(encodedDs)))))); + ids.observe(/** @param {YArrayEvent} event */ event => + event.changes.added.forEach(item => item.content.getContent().forEach(addClientId)) + ); + ids.forEach(addClientId); + }; + // observe users + storeType.observe(event => { + event.keysChanged.forEach(userDescription => + initUser(storeType.get(userDescription), userDescription) + ); + }); + // add intial data + storeType.forEach(initUser); + } + + /** + * @param {Doc} doc + * @param {number} clientid + * @param {string} userDescription + * @param {Object} [conf] + * @param {function(Transaction, DeleteSet):boolean} [conf.filter] + */ + setUserMapping (doc, clientid, userDescription, { filter = () => true } = {}) { + const users = this.yusers; + let user = users.get(userDescription); + if (!user) { + user = new YMap(); + user.set('ids', new YArray()); + user.set('ds', new YArray()); + users.set(userDescription, user); + } + user.get('ids').push([clientid]); + users.observe(event => { + setTimeout(() => { + const userOverwrite = users.get(userDescription); + if (userOverwrite !== user) { + // user was overwritten, port all data over to the next user object + // @todo Experiment with Y.Sets here + user = userOverwrite; + // @todo iterate over old type + this.clients.forEach((_userDescription, clientid) => { + if (userDescription === _userDescription) { + user.get('ids').push([clientid]); + } + }); + const encoder = new DSEncoderV1(); + const ds = this.dss.get(userDescription); + if (ds) { + writeDeleteSet(encoder, ds); + user.get('ds').push([encoder.toUint8Array()]); + } + } + }, 0); + }); + doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => { + setTimeout(() => { + const yds = user.get('ds'); + const ds = transaction.deleteSet; + if (transaction.local && ds.clients.size > 0 && filter(transaction, ds)) { + const encoder = new DSEncoderV1(); + writeDeleteSet(encoder, ds); + yds.push([encoder.toUint8Array()]); + } + }); + }); + } + + /** + * @param {number} clientid + * @return {any} + */ + getUserByClientId (clientid) { + return this.clients.get(clientid) || null + } + + /** + * @param {ID} id + * @return {string | null} + */ + getUserByDeletedId (id) { + for (const [userDescription, ds] of this.dss.entries()) { + if (isDeleted(ds, id)) { + return userDescription + } + } + return null + } +} + +/** + * A relative position is based on the Yjs model and is not affected by document changes. + * E.g. If you place a relative position before a certain character, it will always point to this character. + * If you place a relative position at the end of a type, it will always point to the end of the type. + * + * A numeric position is often unsuited for user selections, because it does not change when content is inserted + * before or after. + * + * ```Insert(0, 'x')('a|bc') = 'xa|bc'``` Where | is the relative position. + * + * One of the properties must be defined. + * + * @example + * // Current cursor position is at position 10 + * const relativePosition = createRelativePositionFromIndex(yText, 10) + * // modify yText + * yText.insert(0, 'abc') + * yText.delete(3, 10) + * // Compute the cursor position + * const absolutePosition = createAbsolutePositionFromRelativePosition(y, relativePosition) + * absolutePosition.type === yText // => true + * console.log('cursor location is ' + absolutePosition.index) // => cursor location is 3 + * + */ +class RelativePosition { + /** + * @param {ID|null} type + * @param {string|null} tname + * @param {ID|null} item + */ + constructor (type, tname, item) { + /** + * @type {ID|null} + */ + this.type = type; + /** + * @type {string|null} + */ + this.tname = tname; + /** + * @type {ID | null} + */ + this.item = item; + } +} + +/** + * @param {any} json + * @return {RelativePosition} + * + * @function + */ +const createRelativePositionFromJSON = json => new RelativePosition(json.type == null ? null : createID(json.type.client, json.type.clock), json.tname || null, json.item == null ? null : createID(json.item.client, json.item.clock)); + +class AbsolutePosition { + /** + * @param {AbstractType} type + * @param {number} index + */ + constructor (type, index) { + /** + * @type {AbstractType} + */ + this.type = type; + /** + * @type {number} + */ + this.index = index; + } +} + +/** + * @param {AbstractType} type + * @param {number} index + * + * @function + */ +const createAbsolutePosition = (type, index) => new AbsolutePosition(type, index); + +/** + * @param {AbstractType} type + * @param {ID|null} item + * + * @function + */ +const createRelativePosition = (type, item) => { + let typeid = null; + let tname = null; + if (type._item === null) { + tname = findRootTypeKey(type); + } else { + typeid = createID(type._item.id.client, type._item.id.clock); + } + return new RelativePosition(typeid, tname, item) +}; + +/** + * Create a relativePosition based on a absolute position. + * + * @param {AbstractType} type The base type (e.g. YText or YArray). + * @param {number} index The absolute position. + * @return {RelativePosition} + * + * @function + */ +const createRelativePositionFromTypeIndex = (type, index) => { + let t = type._start; + while (t !== null) { + if (!t.deleted && t.countable) { + if (t.length > index) { + // case 1: found position somewhere in the linked list + return createRelativePosition(type, createID(t.id.client, t.id.clock + index)) + } + index -= t.length; + } + t = t.right; + } + return createRelativePosition(type, null) +}; + +/** + * @param {encoding.Encoder} encoder + * @param {RelativePosition} rpos + * + * @function + */ +const writeRelativePosition = (encoder, rpos) => { + const { type, tname, item } = rpos; + if (item !== null) { + encoding.writeVarUint(encoder, 0); + writeID(encoder, item); + } else if (tname !== null) { + // case 2: found position at the end of the list and type is stored in y.share + encoding.writeUint8(encoder, 1); + encoding.writeVarString(encoder, tname); + } else if (type !== null) { + // case 3: found position at the end of the list and type is attached to an item + encoding.writeUint8(encoder, 2); + writeID(encoder, type); + } else { + throw error.unexpectedCase() + } + return encoder +}; + +/** + * @param {RelativePosition} rpos + * @return {Uint8Array} + */ +const encodeRelativePosition = rpos => { + const encoder = encoding.createEncoder(); + writeRelativePosition(encoder, rpos); + return encoding.toUint8Array(encoder) +}; + +/** + * @param {decoding.Decoder} decoder + * @return {RelativePosition|null} + * + * @function + */ +const readRelativePosition = decoder => { + let type = null; + let tname = null; + let itemID = null; + switch (decoding.readVarUint(decoder)) { + case 0: + // case 1: found position somewhere in the linked list + itemID = readID(decoder); + break + case 1: + // case 2: found position at the end of the list and type is stored in y.share + tname = decoding.readVarString(decoder); + break + case 2: { + // case 3: found position at the end of the list and type is attached to an item + type = readID(decoder); + } + } + return new RelativePosition(type, tname, itemID) +}; + +/** + * @param {Uint8Array} uint8Array + * @return {RelativePosition|null} + */ +const decodeRelativePosition = uint8Array => readRelativePosition(decoding.createDecoder(uint8Array)); + +/** + * @param {RelativePosition} rpos + * @param {Doc} doc + * @return {AbsolutePosition|null} + * + * @function + */ +const createAbsolutePositionFromRelativePosition = (rpos, doc) => { + const store = doc.store; + const rightID = rpos.item; + const typeID = rpos.type; + const tname = rpos.tname; + let type = null; + let index = 0; + if (rightID !== null) { + if (getState(store, rightID.client) <= rightID.clock) { + return null + } + const res = followRedone(store, rightID); + const right = res.item; + if (!(right instanceof Item)) { + return null + } + type = /** @type {AbstractType} */ (right.parent); + if (type._item === null || !type._item.deleted) { + index = right.deleted || !right.countable ? 0 : res.diff; + let n = right.left; + while (n !== null) { + if (!n.deleted && n.countable) { + index += n.length; + } + n = n.left; + } + } + } else { + if (tname !== null) { + type = doc.get(tname); + } else if (typeID !== null) { + if (getState(store, typeID.client) <= typeID.clock) { + // type does not exist yet + return null + } + const { item } = followRedone(store, typeID); + if (item instanceof Item && item.content instanceof ContentType) { + type = item.content.type; + } else { + // struct is garbage collected + return null + } + } else { + throw error.unexpectedCase() + } + index = type._length; + } + return createAbsolutePosition(type, index) +}; + +/** + * @param {RelativePosition|null} a + * @param {RelativePosition|null} b + * + * @function + */ +const compareRelativePositions = (a, b) => a === b || ( + a !== null && b !== null && a.tname === b.tname && compareIDs(a.item, b.item) && compareIDs(a.type, b.type) +); + +class Snapshot { + /** + * @param {DeleteSet} ds + * @param {Map} sv state map + */ + constructor (ds, sv) { + /** + * @type {DeleteSet} + */ + this.ds = ds; + /** + * State Map + * @type {Map} + */ + this.sv = sv; + } +} + +/** + * @param {Snapshot} snap1 + * @param {Snapshot} snap2 + * @return {boolean} + */ +const equalSnapshots = (snap1, snap2) => { + const ds1 = snap1.ds.clients; + const ds2 = snap2.ds.clients; + const sv1 = snap1.sv; + const sv2 = snap2.sv; + if (sv1.size !== sv2.size || ds1.size !== ds2.size) { + return false + } + for (const [key, value] of sv1.entries()) { + if (sv2.get(key) !== value) { + return false + } + } + for (const [client, dsitems1] of ds1.entries()) { + const dsitems2 = ds2.get(client) || []; + if (dsitems1.length !== dsitems2.length) { + return false + } + for (let i = 0; i < dsitems1.length; i++) { + const dsitem1 = dsitems1[i]; + const dsitem2 = dsitems2[i]; + if (dsitem1.clock !== dsitem2.clock || dsitem1.len !== dsitem2.len) { + return false + } + } + } + return true +}; + +/** + * @param {Snapshot} snapshot + * @param {AbstractDSEncoder} [encoder] + * @return {Uint8Array} + */ +const encodeSnapshotV2 = (snapshot, encoder = new DSEncoderV2()) => { + writeDeleteSet(encoder, snapshot.ds); + writeStateVector(encoder, snapshot.sv); + return encoder.toUint8Array() +}; + +/** + * @param {Snapshot} snapshot + * @return {Uint8Array} + */ +const encodeSnapshot = snapshot => encodeSnapshotV2(snapshot, new DefaultDSEncoder()); + +/** + * @param {Uint8Array} buf + * @param {AbstractDSDecoder} [decoder] + * @return {Snapshot} + */ +const decodeSnapshotV2 = (buf, decoder = new DSDecoderV2(decoding.createDecoder(buf))) => { + return new Snapshot(readDeleteSet(decoder), readStateVector(decoder)) +}; + +/** + * @param {Uint8Array} buf + * @return {Snapshot} + */ +const decodeSnapshot = buf => decodeSnapshotV2(buf, new DSDecoderV1(decoding.createDecoder(buf))); + +/** + * @param {DeleteSet} ds + * @param {Map} sm + * @return {Snapshot} + */ +const createSnapshot = (ds, sm) => new Snapshot(ds, sm); + +const emptySnapshot = createSnapshot(createDeleteSet(), new Map()); + +/** + * @param {Doc} doc + * @return {Snapshot} + */ +const snapshot = doc => createSnapshot(createDeleteSetFromStructStore(doc.store), getStateVector(doc.store)); + +/** + * @param {Item} item + * @param {Snapshot|undefined} snapshot + * + * @protected + * @function + */ +const isVisible = (item, snapshot) => snapshot === undefined ? !item.deleted : ( + snapshot.sv.has(item.id.client) && (snapshot.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot.ds, item.id) +); + +/** + * @param {Transaction} transaction + * @param {Snapshot} snapshot + */ +const splitSnapshotAffectedStructs = (transaction, snapshot) => { + const meta = map.setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, set.create); + const store = transaction.doc.store; + // check if we already split for this snapshot + if (!meta.has(snapshot)) { + snapshot.sv.forEach((clock, client) => { + if (clock < getState(store, client)) { + getItemCleanStart(transaction, createID(client, clock)); + } + }); + iterateDeletedStructs(transaction, snapshot.ds, item => {}); + meta.add(snapshot); + } +}; + +/** + * @param {Doc} originDoc + * @param {Snapshot} snapshot + * @param {Doc} [newDoc] Optionally, you may define the Yjs document that receives the data from originDoc + * @return {Doc} + */ +const createDocFromSnapshot = (originDoc, snapshot, newDoc = new Doc()) => { + if (originDoc.gc) { + // we should not try to restore a GC-ed document, because some of the restored items might have their content deleted + throw new Error('originDoc must not be garbage collected') + } + const { sv, ds } = snapshot; + + const encoder = new UpdateEncoderV2(); + originDoc.transact(transaction => { + let size = 0; + sv.forEach(clock => { + if (clock > 0) { + size++; + } + }); + encoding.writeVarUint(encoder.restEncoder, size); + // splitting the structs before writing them to the encoder + for (const [client, clock] of sv) { + if (clock === 0) { + continue + } + if (clock < getState(originDoc.store, client)) { + getItemCleanStart(transaction, createID(client, clock)); + } + const structs = originDoc.store.clients.get(client) || []; + const lastStructIndex = findIndexSS(structs, clock - 1); + // write # encoded structs + encoding.writeVarUint(encoder.restEncoder, lastStructIndex + 1); + encoder.writeClient(client); + // first clock written is 0 + encoding.writeVarUint(encoder.restEncoder, 0); + for (let i = 0; i <= lastStructIndex; i++) { + structs[i].write(encoder, 0); + } + } + writeDeleteSet(encoder, ds); + }); + + applyUpdateV2(newDoc, encoder.toUint8Array(), 'snapshot'); + return newDoc +}; + +class StructStore { + constructor () { + /** + * @type {Map>} + */ + this.clients = new Map(); + /** + * Store incompleted struct reads here + * `i` denotes to the next read operation + * We could shift the array of refs instead, but shift is incredible + * slow in Chrome for arrays with more than 100k elements + * @see tryResumePendingStructRefs + * @type {Map}>} + */ + this.pendingClientsStructRefs = new Map(); + /** + * Stack of pending structs waiting for struct dependencies + * Maximum length of stack is structReaders.size + * @type {Array} + */ + this.pendingStack = []; + /** + * @type {Array} + */ + this.pendingDeleteReaders = []; + } +} + +/** + * Return the states as a Map. + * Note that clock refers to the next expected clock id. + * + * @param {StructStore} store + * @return {Map} + * + * @public + * @function + */ +const getStateVector = store => { + const sm = new Map(); + store.clients.forEach((structs, client) => { + const struct = structs[structs.length - 1]; + sm.set(client, struct.id.clock + struct.length); + }); + return sm +}; + +/** + * @param {StructStore} store + * @param {number} client + * @return {number} + * + * @public + * @function + */ +const getState = (store, client) => { + const structs = store.clients.get(client); + if (structs === undefined) { + return 0 + } + const lastStruct = structs[structs.length - 1]; + return lastStruct.id.clock + lastStruct.length +}; + +/** + * @param {StructStore} store + * + * @private + * @function + */ +const integretyCheck = store => { + store.clients.forEach(structs => { + for (let i = 1; i < structs.length; i++) { + const l = structs[i - 1]; + const r = structs[i]; + if (l.id.clock + l.length !== r.id.clock) { + throw new Error('StructStore failed integrety check') + } + } + }); +}; + +/** + * @param {StructStore} store + * @param {GC|Item} struct + * + * @private + * @function + */ +const addStruct = (store, struct) => { + let structs = store.clients.get(struct.id.client); + if (structs === undefined) { + structs = []; + store.clients.set(struct.id.client, structs); + } else { + const lastStruct = structs[structs.length - 1]; + if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) { + throw error.unexpectedCase() + } + } + structs.push(struct); +}; + +/** + * Perform a binary search on a sorted array + * @param {Array} structs + * @param {number} clock + * @return {number} + * + * @private + * @function + */ +const findIndexSS = (structs, clock) => { + let left = 0; + let right = structs.length - 1; + let mid = structs[right]; + let midclock = mid.id.clock; + if (midclock === clock) { + return right + } + // @todo does it even make sense to pivot the search? + // If a good split misses, it might actually increase the time to find the correct item. + // Currently, the only advantage is that search with pivoting might find the item on the first try. + let midindex = math.floor((clock / (midclock + mid.length - 1)) * right); // pivoting the search + while (left <= right) { + mid = structs[midindex]; + midclock = mid.id.clock; + if (midclock <= clock) { + if (clock < midclock + mid.length) { + return midindex + } + left = midindex + 1; + } else { + right = midindex - 1; + } + midindex = math.floor((left + right) / 2); + } + // Always check state before looking for a struct in StructStore + // Therefore the case of not finding a struct is unexpected + throw error.unexpectedCase() +}; + +/** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * + * @param {StructStore} store + * @param {ID} id + * @return {GC|Item} + * + * @private + * @function + */ +const find = (store, id) => { + /** + * @type {Array} + */ + // @ts-ignore + const structs = store.clients.get(id.client); + return structs[findIndexSS(structs, id.clock)] +}; + +/** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * @private + * @function + */ +const getItem = /** @type {function(StructStore,ID):Item} */ (find); + +/** + * @param {Transaction} transaction + * @param {Array} structs + * @param {number} clock + */ +const findIndexCleanStart = (transaction, structs, clock) => { + const index = findIndexSS(structs, clock); + const struct = structs[index]; + if (struct.id.clock < clock && struct instanceof Item) { + structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); + return index + 1 + } + return index +}; + +/** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * + * @param {Transaction} transaction + * @param {ID} id + * @return {Item} + * + * @private + * @function + */ +const getItemCleanStart = (transaction, id) => { + const structs = /** @type {Array} */ (transaction.doc.store.clients.get(id.client)); + return structs[findIndexCleanStart(transaction, structs, id.clock)] +}; + +/** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * + * @param {Transaction} transaction + * @param {StructStore} store + * @param {ID} id + * @return {Item} + * + * @private + * @function + */ +const getItemCleanEnd = (transaction, store, id) => { + /** + * @type {Array} + */ + // @ts-ignore + const structs = store.clients.get(id.client); + const index = findIndexSS(structs, id.clock); + const struct = structs[index]; + if (id.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) { + structs.splice(index + 1, 0, splitItem(transaction, struct, id.clock - struct.id.clock + 1)); + } + return struct +}; + +/** + * Replace `item` with `newitem` in store + * @param {StructStore} store + * @param {GC|Item} struct + * @param {GC|Item} newStruct + * + * @private + * @function + */ +const replaceStruct = (store, struct, newStruct) => { + const structs = /** @type {Array} */ (store.clients.get(struct.id.client)); + structs[findIndexSS(structs, struct.id.clock)] = newStruct; +}; + +/** + * Iterate over a range of structs + * + * @param {Transaction} transaction + * @param {Array} structs + * @param {number} clockStart Inclusive start + * @param {number} len + * @param {function(GC|Item):void} f + * + * @function + */ +const iterateStructs = (transaction, structs, clockStart, len, f) => { + if (len === 0) { + return + } + const clockEnd = clockStart + len; + let index = findIndexCleanStart(transaction, structs, clockStart); + let struct; + do { + struct = structs[index++]; + if (clockEnd < struct.id.clock + struct.length) { + findIndexCleanStart(transaction, structs, clockEnd); + } + f(struct); + } while (index < structs.length && structs[index].id.clock < clockEnd) +}; + +/** + * A transaction is created for every change on the Yjs model. It is possible + * to bundle changes on the Yjs model in a single transaction to + * minimize the number on messages sent and the number of observer calls. + * If possible the user of this library should bundle as many changes as + * possible. Here is an example to illustrate the advantages of bundling: + * + * @example + * const map = y.define('map', YMap) + * // Log content when change is triggered + * map.observe(() => { + * console.log('change triggered') + * }) + * // Each change on the map type triggers a log message: + * map.set('a', 0) // => "change triggered" + * map.set('b', 0) // => "change triggered" + * // When put in a transaction, it will trigger the log after the transaction: + * y.transact(() => { + * map.set('a', 1) + * map.set('b', 1) + * }) // => "change triggered" + * + * @public + */ +class Transaction { + /** + * @param {Doc} doc + * @param {any} origin + * @param {boolean} local + */ + constructor (doc, origin, local) { + /** + * The Yjs instance. + * @type {Doc} + */ + this.doc = doc; + /** + * Describes the set of deleted items by ids + * @type {DeleteSet} + */ + this.deleteSet = new DeleteSet(); + /** + * Holds the state before the transaction started. + * @type {Map} + */ + this.beforeState = getStateVector(doc.store); + /** + * Holds the state after the transaction. + * @type {Map} + */ + this.afterState = new Map(); + /** + * All types that were directly modified (property added or child + * inserted/deleted). New types are not included in this Set. + * Maps from type to parentSubs (`item.parentSub = null` for YArray) + * @type {Map,Set>} + */ + this.changed = new Map(); + /** + * Stores the events for the types that observe also child elements. + * It is mainly used by `observeDeep`. + * @type {Map,Array>} + */ + this.changedParentTypes = new Map(); + /** + * @type {Array} + */ + this._mergeStructs = []; + /** + * @type {any} + */ + this.origin = origin; + /** + * Stores meta information on the transaction + * @type {Map} + */ + this.meta = new Map(); + /** + * Whether this change originates from this doc. + * @type {boolean} + */ + this.local = local; + /** + * @type {Set} + */ + this.subdocsAdded = new Set(); + /** + * @type {Set} + */ + this.subdocsRemoved = new Set(); + /** + * @type {Set} + */ + this.subdocsLoaded = new Set(); + } +} + +/** + * @param {AbstractUpdateEncoder} encoder + * @param {Transaction} transaction + * @return {boolean} Whether data was written. + */ +const writeUpdateMessageFromTransaction = (encoder, transaction) => { + if (transaction.deleteSet.clients.size === 0 && !map.any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) { + return false + } + sortAndMergeDeleteSet(transaction.deleteSet); + writeStructsFromTransaction(encoder, transaction); + writeDeleteSet(encoder, transaction.deleteSet); + return true +}; + +/** + * @param {Transaction} transaction + * + * @private + * @function + */ +const nextID = transaction => { + const y = transaction.doc; + return createID(y.clientID, getState(y.store, y.clientID)) +}; + +/** + * If `type.parent` was added in current transaction, `type` technically + * did not change, it was just added and we should not fire events for `type`. + * + * @param {Transaction} transaction + * @param {AbstractType} type + * @param {string|null} parentSub + */ +const addChangedTypeToTransaction = (transaction, type, parentSub) => { + const item = type._item; + if (item === null || (item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted)) { + map.setIfUndefined(transaction.changed, type, set.create).add(parentSub); + } +}; + +/** + * @param {Array} structs + * @param {number} pos + */ +const tryToMergeWithLeft = (structs, pos) => { + const left = structs[pos - 1]; + const right = structs[pos]; + if (left.deleted === right.deleted && left.constructor === right.constructor) { + if (left.mergeWith(right)) { + structs.splice(pos, 1); + if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType} */ (right.parent)._map.get(right.parentSub) === right) { + /** @type {AbstractType} */ (right.parent)._map.set(right.parentSub, /** @type {Item} */ (left)); + } + } + } +}; + +/** + * @param {DeleteSet} ds + * @param {StructStore} store + * @param {function(Item):boolean} gcFilter + */ +const tryGcDeleteSet = (ds, store, gcFilter) => { + for (const [client, deleteItems] of ds.clients.entries()) { + const structs = /** @type {Array} */ (store.clients.get(client)); + for (let di = deleteItems.length - 1; di >= 0; di--) { + const deleteItem = deleteItems[di]; + const endDeleteItemClock = deleteItem.clock + deleteItem.len; + for ( + let si = findIndexSS(structs, deleteItem.clock), struct = structs[si]; + si < structs.length && struct.id.clock < endDeleteItemClock; + struct = structs[++si] + ) { + const struct = structs[si]; + if (deleteItem.clock + deleteItem.len <= struct.id.clock) { + break + } + if (struct instanceof Item && struct.deleted && !struct.keep && gcFilter(struct)) { + struct.gc(store, false); + } + } + } + } +}; + +/** + * @param {DeleteSet} ds + * @param {StructStore} store + */ +const tryMergeDeleteSet = (ds, store) => { + // try to merge deleted / gc'd items + // merge from right to left for better efficiecy and so we don't miss any merge targets + ds.clients.forEach((deleteItems, client) => { + const structs = /** @type {Array} */ (store.clients.get(client)); + for (let di = deleteItems.length - 1; di >= 0; di--) { + const deleteItem = deleteItems[di]; + // start with merging the item next to the last deleted item + const mostRightIndexToCheck = math.min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1)); + for ( + let si = mostRightIndexToCheck, struct = structs[si]; + si > 0 && struct.id.clock >= deleteItem.clock; + struct = structs[--si] + ) { + tryToMergeWithLeft(structs, si); + } + } + }); +}; + +/** + * @param {DeleteSet} ds + * @param {StructStore} store + * @param {function(Item):boolean} gcFilter + */ +const tryGc = (ds, store, gcFilter) => { + tryGcDeleteSet(ds, store, gcFilter); + tryMergeDeleteSet(ds, store); +}; + +/** + * @param {Array} transactionCleanups + * @param {number} i + */ +const cleanupTransactions = (transactionCleanups, i) => { + if (i < transactionCleanups.length) { + const transaction = transactionCleanups[i]; + const doc = transaction.doc; + const store = doc.store; + const ds = transaction.deleteSet; + const mergeStructs = transaction._mergeStructs; + try { + sortAndMergeDeleteSet(ds); + transaction.afterState = getStateVector(transaction.doc.store); + doc._transaction = null; + doc.emit('beforeObserverCalls', [transaction, doc]); + /** + * An array of event callbacks. + * + * Each callback is called even if the other ones throw errors. + * + * @type {Array} + */ + const fs = []; + // observe events on changed types + transaction.changed.forEach((subs, itemtype) => + fs.push(() => { + if (itemtype._item === null || !itemtype._item.deleted) { + itemtype._callObserver(transaction, subs); + } + }) + ); + fs.push(() => { + // deep observe events + transaction.changedParentTypes.forEach((events, type) => + fs.push(() => { + // We need to think about the possibility that the user transforms the + // Y.Doc in the event. + if (type._item === null || !type._item.deleted) { + events = events + .filter(event => + event.target._item === null || !event.target._item.deleted + ); + events + .forEach(event => { + event.currentTarget = type; + }); + // sort events by path length so that top-level events are fired first. + events + .sort((event1, event2) => event1.path.length - event2.path.length); + // We don't need to check for events.length + // because we know it has at least one element + callEventHandlerListeners(type._dEH, events, transaction); + } + }) + ); + fs.push(() => doc.emit('afterTransaction', [transaction, doc])); + }); + f.callAll(fs, []); + } finally { + // Replace deleted items with ItemDeleted / GC. + // This is where content is actually remove from the Yjs Doc. + if (doc.gc) { + tryGcDeleteSet(ds, store, doc.gcFilter); + } + tryMergeDeleteSet(ds, store); + + // on all affected store.clients props, try to merge + transaction.afterState.forEach((clock, client) => { + const beforeClock = transaction.beforeState.get(client) || 0; + if (beforeClock !== clock) { + const structs = /** @type {Array} */ (store.clients.get(client)); + // we iterate from right to left so we can safely remove entries + const firstChangePos = math.max(findIndexSS(structs, beforeClock), 1); + for (let i = structs.length - 1; i >= firstChangePos; i--) { + tryToMergeWithLeft(structs, i); + } + } + }); + // try to merge mergeStructs + // @todo: it makes more sense to transform mergeStructs to a DS, sort it, and merge from right to left + // but at the moment DS does not handle duplicates + for (let i = 0; i < mergeStructs.length; i++) { + const { client, clock } = mergeStructs[i].id; + const structs = /** @type {Array} */ (store.clients.get(client)); + const replacedStructPos = findIndexSS(structs, clock); + if (replacedStructPos + 1 < structs.length) { + tryToMergeWithLeft(structs, replacedStructPos + 1); + } + if (replacedStructPos > 0) { + tryToMergeWithLeft(structs, replacedStructPos); + } + } + if (!transaction.local && transaction.afterState.get(doc.clientID) !== transaction.beforeState.get(doc.clientID)) { + doc.clientID = generateNewClientId(); + logging.print(logging.ORANGE, logging.BOLD, '[yjs] ', logging.UNBOLD, logging.RED, 'Changed the client-id because another client seems to be using it.'); + } + // @todo Merge all the transactions into one and provide send the data as a single update message + doc.emit('afterTransactionCleanup', [transaction, doc]); + if (doc._observers.has('update')) { + const encoder = new DefaultUpdateEncoder(); + const hasContent = writeUpdateMessageFromTransaction(encoder, transaction); + if (hasContent) { + doc.emit('update', [encoder.toUint8Array(), transaction.origin, doc]); + } + } + if (doc._observers.has('updateV2')) { + const encoder = new UpdateEncoderV2(); + const hasContent = writeUpdateMessageFromTransaction(encoder, transaction); + if (hasContent) { + doc.emit('updateV2', [encoder.toUint8Array(), transaction.origin, doc]); + } + } + transaction.subdocsAdded.forEach(subdoc => doc.subdocs.add(subdoc)); + transaction.subdocsRemoved.forEach(subdoc => doc.subdocs.delete(subdoc)); + + doc.emit('subdocs', [{ loaded: transaction.subdocsLoaded, added: transaction.subdocsAdded, removed: transaction.subdocsRemoved }]); + transaction.subdocsRemoved.forEach(subdoc => subdoc.destroy()); + + if (transactionCleanups.length <= i + 1) { + doc._transactionCleanups = []; + doc.emit('afterAllTransactions', [doc, transactionCleanups]); + } else { + cleanupTransactions(transactionCleanups, i + 1); + } + } + } +}; + +/** + * Implements the functionality of `y.transact(()=>{..})` + * + * @param {Doc} doc + * @param {function(Transaction):void} f + * @param {any} [origin=true] + * + * @function + */ +const transact = (doc, f, origin = null, local = true) => { + const transactionCleanups = doc._transactionCleanups; + let initialCall = false; + if (doc._transaction === null) { + initialCall = true; + doc._transaction = new Transaction(doc, origin, local); + transactionCleanups.push(doc._transaction); + if (transactionCleanups.length === 1) { + doc.emit('beforeAllTransactions', [doc]); + } + doc.emit('beforeTransaction', [doc._transaction, doc]); + } + try { + f(doc._transaction); + } finally { + if (initialCall && transactionCleanups[0] === doc._transaction) { + // The first transaction ended, now process observer calls. + // Observer call may create new transactions for which we need to call the observers and do cleanup. + // We don't want to nest these calls, so we execute these calls one after + // another. + // Also we need to ensure that all cleanups are called, even if the + // observes throw errors. + // This file is full of hacky try {} finally {} blocks to ensure that an + // event can throw errors and also that the cleanup is called. + cleanupTransactions(transactionCleanups, 0); + } + } +}; + +class StackItem { + /** + * @param {DeleteSet} ds + * @param {Map} beforeState + * @param {Map} afterState + */ + constructor (ds, beforeState, afterState) { + this.ds = ds; + this.beforeState = beforeState; + this.afterState = afterState; + /** + * Use this to save and restore metadata like selection range + */ + this.meta = new Map(); + } +} + +/** + * @param {UndoManager} undoManager + * @param {Array} stack + * @param {string} eventType + * @return {StackItem?} + */ +const popStackItem = (undoManager, stack, eventType) => { + /** + * Whether a change happened + * @type {StackItem?} + */ + let result = null; + const doc = undoManager.doc; + const scope = undoManager.scope; + transact(doc, transaction => { + while (stack.length > 0 && result === null) { + const store = doc.store; + const stackItem = /** @type {StackItem} */ (stack.pop()); + /** + * @type {Set} + */ + const itemsToRedo = new Set(); + /** + * @type {Array} + */ + const itemsToDelete = []; + let performedChange = false; + stackItem.afterState.forEach((endClock, client) => { + const startClock = stackItem.beforeState.get(client) || 0; + const len = endClock - startClock; + // @todo iterateStructs should not need the structs parameter + const structs = /** @type {Array} */ (store.clients.get(client)); + if (startClock !== endClock) { + // make sure structs don't overlap with the range of created operations [stackItem.start, stackItem.start + stackItem.end) + // this must be executed before deleted structs are iterated. + getItemCleanStart(transaction, createID(client, startClock)); + if (endClock < getState(doc.store, client)) { + getItemCleanStart(transaction, createID(client, endClock)); + } + iterateStructs(transaction, structs, startClock, len, struct => { + if (struct instanceof Item) { + if (struct.redone !== null) { + let { item, diff } = followRedone(store, struct.id); + if (diff > 0) { + item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff)); + } + if (item.length > len) { + getItemCleanStart(transaction, createID(item.id.client, endClock)); + } + struct = item; + } + if (!struct.deleted && scope.some(type => isParentOf(type, /** @type {Item} */ (struct)))) { + itemsToDelete.push(struct); + } + } + }); + } + }); + iterateDeletedStructs(transaction, stackItem.ds, struct => { + const id = struct.id; + const clock = id.clock; + const client = id.client; + const startClock = stackItem.beforeState.get(client) || 0; + const endClock = stackItem.afterState.get(client) || 0; + if ( + struct instanceof Item && + scope.some(type => isParentOf(type, struct)) && + // Never redo structs in [stackItem.start, stackItem.start + stackItem.end) because they were created and deleted in the same capture interval. + !(clock >= startClock && clock < endClock) + ) { + itemsToRedo.add(struct); + } + }); + itemsToRedo.forEach(struct => { + performedChange = redoItem(transaction, struct, itemsToRedo) !== null || performedChange; + }); + // We want to delete in reverse order so that children are deleted before + // parents, so we have more information available when items are filtered. + for (let i = itemsToDelete.length - 1; i >= 0; i--) { + const item = itemsToDelete[i]; + if (undoManager.deleteFilter(item)) { + item.delete(transaction); + performedChange = true; + } + } + result = stackItem; + if (result != null) { + undoManager.emit('stack-item-popped', [{ stackItem: result, type: eventType }, undoManager]); + } + } + transaction.changed.forEach((subProps, type) => { + // destroy search marker if necessary + if (subProps.has(null) && type._searchMarker) { + type._searchMarker.length = 0; + } + }); + }, undoManager); + return result +}; + +/** + * @typedef {Object} UndoManagerOptions + * @property {number} [UndoManagerOptions.captureTimeout=500] + * @property {function(Item):boolean} [UndoManagerOptions.deleteFilter=()=>true] Sometimes + * it is necessary to filter whan an Undo/Redo operation can delete. If this + * filter returns false, the type/item won't be deleted even it is in the + * undo/redo scope. + * @property {Set} [UndoManagerOptions.trackedOrigins=new Set([null])] + */ + +/** + * Fires 'stack-item-added' event when a stack item was added to either the undo- or + * the redo-stack. You may store additional stack information via the + * metadata property on `event.stackItem.meta` (it is a `Map` of metadata properties). + * Fires 'stack-item-popped' event when a stack item was popped from either the + * undo- or the redo-stack. You may restore the saved stack information from `event.stackItem.meta`. + * + * @extends {Observable<'stack-item-added'|'stack-item-popped'>} + */ +class UndoManager extends observable_js.Observable { + /** + * @param {AbstractType|Array>} typeScope Accepts either a single type, or an array of types + * @param {UndoManagerOptions} options + */ + constructor (typeScope, { captureTimeout = 500, deleteFilter = () => true, trackedOrigins = new Set([null]) } = {}) { + super(); + this.scope = typeScope instanceof Array ? typeScope : [typeScope]; + this.deleteFilter = deleteFilter; + trackedOrigins.add(this); + this.trackedOrigins = trackedOrigins; + /** + * @type {Array} + */ + this.undoStack = []; + /** + * @type {Array} + */ + this.redoStack = []; + /** + * Whether the client is currently undoing (calling UndoManager.undo) + * + * @type {boolean} + */ + this.undoing = false; + this.redoing = false; + this.doc = /** @type {Doc} */ (this.scope[0].doc); + this.lastChange = 0; + this.doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => { + // Only track certain transactions + if (!this.scope.some(type => transaction.changedParentTypes.has(type)) || (!this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor)))) { + return + } + const undoing = this.undoing; + const redoing = this.redoing; + const stack = undoing ? this.redoStack : this.undoStack; + if (undoing) { + this.stopCapturing(); // next undo should not be appended to last stack item + } else if (!redoing) { + // neither undoing nor redoing: delete redoStack + this.redoStack = []; + } + const beforeState = transaction.beforeState; + const afterState = transaction.afterState; + const now = time.getUnixTime(); + if (now - this.lastChange < captureTimeout && stack.length > 0 && !undoing && !redoing) { + // append change to last stack op + const lastOp = stack[stack.length - 1]; + lastOp.ds = mergeDeleteSets([lastOp.ds, transaction.deleteSet]); + lastOp.afterState = afterState; + } else { + // create a new stack op + stack.push(new StackItem(transaction.deleteSet, beforeState, afterState)); + } + if (!undoing && !redoing) { + this.lastChange = now; + } + // make sure that deleted structs are not gc'd + iterateDeletedStructs(transaction, transaction.deleteSet, /** @param {Item|GC} item */ item => { + if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) { + keepItem(item, true); + } + }); + this.emit('stack-item-added', [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? 'redo' : 'undo' }, this]); + }); + } + + clear () { + this.doc.transact(transaction => { + /** + * @param {StackItem} stackItem + */ + const clearItem = stackItem => { + iterateDeletedStructs(transaction, stackItem.ds, item => { + if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) { + keepItem(item, false); + } + }); + }; + this.undoStack.forEach(clearItem); + this.redoStack.forEach(clearItem); + }); + this.undoStack = []; + this.redoStack = []; + } + + /** + * UndoManager merges Undo-StackItem if they are created within time-gap + * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next + * StackItem won't be merged. + * + * + * @example + * // without stopCapturing + * ytext.insert(0, 'a') + * ytext.insert(1, 'b') + * um.undo() + * ytext.toString() // => '' (note that 'ab' was removed) + * // with stopCapturing + * ytext.insert(0, 'a') + * um.stopCapturing() + * ytext.insert(0, 'b') + * um.undo() + * ytext.toString() // => 'a' (note that only 'b' was removed) + * + */ + stopCapturing () { + this.lastChange = 0; + } + + /** + * Undo last changes on type. + * + * @return {StackItem?} Returns StackItem if a change was applied + */ + undo () { + this.undoing = true; + let res; + try { + res = popStackItem(this, this.undoStack, 'undo'); + } finally { + this.undoing = false; + } + return res + } + + /** + * Redo last undo operation. + * + * @return {StackItem?} Returns StackItem if a change was applied + */ + redo () { + this.redoing = true; + let res; + try { + res = popStackItem(this, this.redoStack, 'redo'); + } finally { + this.redoing = false; + } + return res + } +} + +/** + * YEvent describes the changes on a YType. + */ +class YEvent { + /** + * @param {AbstractType} target The changed type. + * @param {Transaction} transaction + */ + constructor (target, transaction) { + /** + * The type on which this event was created on. + * @type {AbstractType} + */ + this.target = target; + /** + * The current target on which the observe callback is called. + * @type {AbstractType} + */ + this.currentTarget = target; + /** + * The transaction that triggered this event. + * @type {Transaction} + */ + this.transaction = transaction; + /** + * @type {Object|null} + */ + this._changes = null; + } + + /** + * Computes the path from `y` to the changed type. + * + * The following property holds: + * @example + * let type = y + * event.path.forEach(dir => { + * type = type.get(dir) + * }) + * type === event.target // => true + */ + get path () { + // @ts-ignore _item is defined because target is integrated + return getPathTo(this.currentTarget, this.target) + } + + /** + * Check if a struct is deleted by this event. + * + * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. + * + * @param {AbstractStruct} struct + * @return {boolean} + */ + deletes (struct) { + return isDeleted(this.transaction.deleteSet, struct.id) + } + + /** + * Check if a struct is added by this event. + * + * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. + * + * @param {AbstractStruct} struct + * @return {boolean} + */ + adds (struct) { + return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0) + } + + /** + * @return {{added:Set,deleted:Set,keys:Map,delta:Array<{insert:Array}|{delete:number}|{retain:number}>}} + */ + get changes () { + let changes = this._changes; + if (changes === null) { + const target = this.target; + const added = set.create(); + const deleted = set.create(); + /** + * @type {Array<{insert:Array}|{delete:number}|{retain:number}>} + */ + const delta = []; + /** + * @type {Map} + */ + const keys = new Map(); + changes = { + added, deleted, delta, keys + }; + const changed = /** @type Set */ (this.transaction.changed.get(target)); + if (changed.has(null)) { + /** + * @type {any} + */ + let lastOp = null; + const packOp = () => { + if (lastOp) { + delta.push(lastOp); + } + }; + for (let item = target._start; item !== null; item = item.right) { + if (item.deleted) { + if (this.deletes(item) && !this.adds(item)) { + if (lastOp === null || lastOp.delete === undefined) { + packOp(); + lastOp = { delete: 0 }; + } + lastOp.delete += item.length; + deleted.add(item); + } // else nop + } else { + if (this.adds(item)) { + if (lastOp === null || lastOp.insert === undefined) { + packOp(); + lastOp = { insert: [] }; + } + lastOp.insert = lastOp.insert.concat(item.content.getContent()); + added.add(item); + } else { + if (lastOp === null || lastOp.retain === undefined) { + packOp(); + lastOp = { retain: 0 }; + } + lastOp.retain += item.length; + } + } + } + if (lastOp !== null && lastOp.retain === undefined) { + packOp(); + } + } + changed.forEach(key => { + if (key !== null) { + const item = /** @type {Item} */ (target._map.get(key)); + /** + * @type {'delete' | 'add' | 'update'} + */ + let action; + let oldValue; + if (this.adds(item)) { + let prev = item.left; + while (prev !== null && this.adds(prev)) { + prev = prev.left; + } + if (this.deletes(item)) { + if (prev !== null && this.deletes(prev)) { + action = 'delete'; + oldValue = array.last(prev.content.getContent()); + } else { + return + } + } else { + if (prev !== null && this.deletes(prev)) { + action = 'update'; + oldValue = array.last(prev.content.getContent()); + } else { + action = 'add'; + oldValue = undefined; + } + } + } else { + if (this.deletes(item)) { + action = 'delete'; + oldValue = array.last(/** @type {Item} */ item.content.getContent()); + } else { + return // nop + } + } + keys.set(key, { action, oldValue }); + } + }); + this._changes = changes; + } + return /** @type {any} */ (changes) + } +} + +/** + * Compute the path from this type to the specified target. + * + * @example + * // `child` should be accessible via `type.get(path[0]).get(path[1])..` + * const path = type.getPathTo(child) + * // assuming `type instanceof YArray` + * console.log(path) // might look like => [2, 'key1'] + * child === type.get(path[0]).get(path[1]) + * + * @param {AbstractType} parent + * @param {AbstractType} child target + * @return {Array} Path to the target + * + * @private + * @function + */ +const getPathTo = (parent, child) => { + const path = []; + while (child._item !== null && child !== parent) { + if (child._item.parentSub !== null) { + // parent is map-ish + path.unshift(child._item.parentSub); + } else { + // parent is array-ish + let i = 0; + let c = /** @type {AbstractType} */ (child._item.parent)._start; + while (c !== child._item && c !== null) { + if (!c.deleted) { + i++; + } + c = c.right; + } + path.unshift(i); + } + child = /** @type {AbstractType} */ (child._item.parent); + } + return path +}; + +const maxSearchMarker = 80; + +/** + * A unique timestamp that identifies each marker. + * + * Time is relative,.. this is more like an ever-increasing clock. + * + * @type {number} + */ +let globalSearchMarkerTimestamp = 0; + +class ArraySearchMarker { + /** + * @param {Item} p + * @param {number} index + */ + constructor (p, index) { + p.marker = true; + this.p = p; + this.index = index; + this.timestamp = globalSearchMarkerTimestamp++; + } +} + +/** + * @param {ArraySearchMarker} marker + */ +const refreshMarkerTimestamp = marker => { marker.timestamp = globalSearchMarkerTimestamp++; }; + +/** + * This is rather complex so this function is the only thing that should overwrite a marker + * + * @param {ArraySearchMarker} marker + * @param {Item} p + * @param {number} index + */ +const overwriteMarker = (marker, p, index) => { + marker.p.marker = false; + marker.p = p; + p.marker = true; + marker.index = index; + marker.timestamp = globalSearchMarkerTimestamp++; +}; + +/** + * @param {Array} searchMarker + * @param {Item} p + * @param {number} index + */ +const markPosition = (searchMarker, p, index) => { + if (searchMarker.length >= maxSearchMarker) { + // override oldest marker (we don't want to create more objects) + const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b); + overwriteMarker(marker, p, index); + return marker + } else { + // create new marker + const pm = new ArraySearchMarker(p, index); + searchMarker.push(pm); + return pm + } +}; + +/** + * Search marker help us to find positions in the associative array faster. + * + * They speed up the process of finding a position without much bookkeeping. + * + * A maximum of `maxSearchMarker` objects are created. + * + * This function always returns a refreshed marker (updated timestamp) + * + * @param {AbstractType} yarray + * @param {number} index + */ +const findMarker = (yarray, index) => { + if (yarray._start === null || index === 0 || yarray._searchMarker === null) { + return null + } + const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => math.abs(index - a.index) < math.abs(index - b.index) ? a : b); + let p = yarray._start; + let pindex = 0; + if (marker !== null) { + p = marker.p; + pindex = marker.index; + refreshMarkerTimestamp(marker); // we used it, we might need to use it again + } + // iterate to right if possible + while (p.right !== null && pindex < index) { + if (!p.deleted && p.countable) { + if (index < pindex + p.length) { + break + } + pindex += p.length; + } + p = p.right; + } + // iterate to left if necessary (might be that pindex > index) + while (p.left !== null && pindex > index) { + p = p.left; + if (!p.deleted && p.countable) { + pindex -= p.length; + } + } + // we want to make sure that p can't be merged with left, because that would screw up everything + // in that cas just return what we have (it is most likely the best marker anyway) + // iterate to left until p can't be merged with left + while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) { + p = p.left; + if (!p.deleted && p.countable) { + pindex -= p.length; + } + } + + // @todo remove! + // assure position + // { + // let start = yarray._start + // let pos = 0 + // while (start !== p) { + // if (!start.deleted && start.countable) { + // pos += start.length + // } + // start = /** @type {Item} */ (start.right) + // } + // if (pos !== pindex) { + // debugger + // throw new Error('Gotcha position fail!') + // } + // } + // if (marker) { + // if (window.lengthes == null) { + // window.lengthes = [] + // window.getLengthes = () => window.lengthes.sort((a, b) => a - b) + // } + // window.lengthes.push(marker.index - pindex) + // console.log('distance', marker.index - pindex, 'len', p && p.parent.length) + // } + if (marker !== null && math.abs(marker.index - pindex) < /** @type {YText|YArray} */ (p.parent).length / maxSearchMarker) { + // adjust existing marker + overwriteMarker(marker, p, pindex); + return marker + } else { + // create new marker + return markPosition(yarray._searchMarker, p, pindex) + } +}; + +/** + * Update markers when a change happened. + * + * This should be called before doing a deletion! + * + * @param {Array} searchMarker + * @param {number} index + * @param {number} len If insertion, len is positive. If deletion, len is negative. + */ +const updateMarkerChanges = (searchMarker, index, len) => { + for (let i = searchMarker.length - 1; i >= 0; i--) { + const m = searchMarker[i]; + if (len > 0) { + /** + * @type {Item|null} + */ + let p = m.p; + p.marker = false; + // Ideally we just want to do a simple position comparison, but this will only work if + // search markers don't point to deleted items for formats. + // Iterate marker to prev undeleted countable position so we know what to do when updating a position + while (p && (p.deleted || !p.countable)) { + p = p.left; + if (p && !p.deleted && p.countable) { + // adjust position. the loop should break now + m.index -= p.length; + } + } + if (p === null || p.marker === true) { + // remove search marker if updated position is null or if position is already marked + searchMarker.splice(i, 1); + continue + } + m.p = p; + p.marker = true; + } + if (index < m.index || (len > 0 && index === m.index)) { // a simple index <= m.index check would actually suffice + m.index = math.max(index, m.index + len); + } + } +}; + +/** + * Accumulate all (list) children of a type and return them as an Array. + * + * @param {AbstractType} t + * @return {Array} + */ +const getTypeChildren = t => { + let s = t._start; + const arr = []; + while (s) { + arr.push(s); + s = s.right; + } + return arr +}; + +/** + * Call event listeners with an event. This will also add an event to all + * parents (for `.observeDeep` handlers). + * + * @template EventType + * @param {AbstractType} type + * @param {Transaction} transaction + * @param {EventType} event + */ +const callTypeObservers = (type, transaction, event) => { + const changedType = type; + const changedParentTypes = transaction.changedParentTypes; + while (true) { + // @ts-ignore + map.setIfUndefined(changedParentTypes, type, () => []).push(event); + if (type._item === null) { + break + } + type = /** @type {AbstractType} */ (type._item.parent); + } + callEventHandlerListeners(changedType._eH, event, transaction); +}; + +/** + * @template EventType + * Abstract Yjs Type class + */ +class AbstractType { + constructor () { + /** + * @type {Item|null} + */ + this._item = null; + /** + * @type {Map} + */ + this._map = new Map(); + /** + * @type {Item|null} + */ + this._start = null; + /** + * @type {Doc|null} + */ + this.doc = null; + this._length = 0; + /** + * Event handlers + * @type {EventHandler} + */ + this._eH = createEventHandler(); + /** + * Deep event handlers + * @type {EventHandler,Transaction>} + */ + this._dEH = createEventHandler(); + /** + * @type {null | Array} + */ + this._searchMarker = null; + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item|null} item + */ + _integrate (y, item) { + this.doc = y; + this._item = item; + } + + /** + * @return {AbstractType} + */ + _copy () { + throw error.methodUnimplemented() + } + + /** + * @param {AbstractUpdateEncoder} encoder + */ + _write (encoder) { } + + /** + * The first non-deleted item + */ + get _first () { + let n = this._start; + while (n !== null && n.deleted) { + n = n.right; + } + return n + } + + /** + * Creates YEvent and calls all type observers. + * Must be implemented by each type. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + if (!transaction.local && this._searchMarker) { + this._searchMarker.length = 0; + } + } + + /** + * Observe all events that are created on this type. + * + * @param {function(EventType, Transaction):void} f Observer function + */ + observe (f) { + addEventHandlerListener(this._eH, f); + } + + /** + * Observe all events that are created by this type and its children. + * + * @param {function(Array,Transaction):void} f Observer function + */ + observeDeep (f) { + addEventHandlerListener(this._dEH, f); + } + + /** + * Unregister an observer function. + * + * @param {function(EventType,Transaction):void} f Observer function + */ + unobserve (f) { + removeEventHandlerListener(this._eH, f); + } + + /** + * Unregister an observer function. + * + * @param {function(Array,Transaction):void} f Observer function + */ + unobserveDeep (f) { + removeEventHandlerListener(this._dEH, f); + } + + /** + * @abstract + * @return {any} + */ + toJSON () {} +} + +/** + * @param {AbstractType} type + * @return {Array} + * + * @private + * @function + */ +const typeListToArray = type => { + const cs = []; + let n = type._start; + while (n !== null) { + if (n.countable && !n.deleted) { + const c = n.content.getContent(); + for (let i = 0; i < c.length; i++) { + cs.push(c[i]); + } + } + n = n.right; + } + return cs +}; + +/** + * @param {AbstractType} type + * @param {Snapshot} snapshot + * @return {Array} + * + * @private + * @function + */ +const typeListToArraySnapshot = (type, snapshot) => { + const cs = []; + let n = type._start; + while (n !== null) { + if (n.countable && isVisible(n, snapshot)) { + const c = n.content.getContent(); + for (let i = 0; i < c.length; i++) { + cs.push(c[i]); + } + } + n = n.right; + } + return cs +}; + +/** + * Executes a provided function on once on overy element of this YArray. + * + * @param {AbstractType} type + * @param {function(any,number,any):void} f A function to execute on every element of this YArray. + * + * @private + * @function + */ +const typeListForEach = (type, f) => { + let index = 0; + let n = type._start; + while (n !== null) { + if (n.countable && !n.deleted) { + const c = n.content.getContent(); + for (let i = 0; i < c.length; i++) { + f(c[i], index++, type); + } + } + n = n.right; + } +}; + +/** + * @template C,R + * @param {AbstractType} type + * @param {function(C,number,AbstractType):R} f + * @return {Array} + * + * @private + * @function + */ +const typeListMap = (type, f) => { + /** + * @type {Array} + */ + const result = []; + typeListForEach(type, (c, i) => { + result.push(f(c, i, type)); + }); + return result +}; + +/** + * @param {AbstractType} type + * @return {IterableIterator} + * + * @private + * @function + */ +const typeListCreateIterator = type => { + let n = type._start; + /** + * @type {Array|null} + */ + let currentContent = null; + let currentContentIndex = 0; + return { + [Symbol.iterator] () { + return this + }, + next: () => { + // find some content + if (currentContent === null) { + while (n !== null && n.deleted) { + n = n.right; + } + // check if we reached the end, no need to check currentContent, because it does not exist + if (n === null) { + return { + done: true, + value: undefined + } + } + // we found n, so we can set currentContent + currentContent = n.content.getContent(); + currentContentIndex = 0; + n = n.right; // we used the content of n, now iterate to next + } + const value = currentContent[currentContentIndex++]; + // check if we need to empty currentContent + if (currentContent.length <= currentContentIndex) { + currentContent = null; + } + return { + done: false, + value + } + } + } +}; + +/** + * Executes a provided function on once on overy element of this YArray. + * Operates on a snapshotted state of the document. + * + * @param {AbstractType} type + * @param {function(any,number,AbstractType):void} f A function to execute on every element of this YArray. + * @param {Snapshot} snapshot + * + * @private + * @function + */ +const typeListForEachSnapshot = (type, f, snapshot) => { + let index = 0; + let n = type._start; + while (n !== null) { + if (n.countable && isVisible(n, snapshot)) { + const c = n.content.getContent(); + for (let i = 0; i < c.length; i++) { + f(c[i], index++, type); + } + } + n = n.right; + } +}; + +/** + * @param {AbstractType} type + * @param {number} index + * @return {any} + * + * @private + * @function + */ +const typeListGet = (type, index) => { + const marker = findMarker(type, index); + let n = type._start; + if (marker !== null) { + n = marker.p; + index -= marker.index; + } + for (; n !== null; n = n.right) { + if (!n.deleted && n.countable) { + if (index < n.length) { + return n.content.getContent()[index] + } + index -= n.length; + } + } +}; + +/** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {Item?} referenceItem + * @param {Array|Array|boolean|number|string|Uint8Array>} content + * + * @private + * @function + */ +const typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => { + let left = referenceItem; + const doc = transaction.doc; + const ownClientId = doc.clientID; + const store = doc.store; + const right = referenceItem === null ? parent._start : referenceItem.right; + /** + * @type {Array|number>} + */ + let jsonContent = []; + const packJsonContent = () => { + if (jsonContent.length > 0) { + left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent)); + left.integrate(transaction, 0); + jsonContent = []; + } + }; + content.forEach(c => { + switch (c.constructor) { + case Number: + case Object: + case Boolean: + case Array: + case String: + jsonContent.push(c); + break + default: + packJsonContent(); + switch (c.constructor) { + case Uint8Array: + case ArrayBuffer: + left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array(/** @type {Uint8Array} */ (c)))); + left.integrate(transaction, 0); + break + case Doc: + left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc(/** @type {Doc} */ (c))); + left.integrate(transaction, 0); + break + default: + if (c instanceof AbstractType) { + left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c)); + left.integrate(transaction, 0); + } else { + throw new Error('Unexpected content type in insert operation') + } + } + } + }); + packJsonContent(); +}; + +/** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {number} index + * @param {Array|Array|number|string|Uint8Array>} content + * + * @private + * @function + */ +const typeListInsertGenerics = (transaction, parent, index, content) => { + if (index === 0) { + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, index, content.length); + } + return typeListInsertGenericsAfter(transaction, parent, null, content) + } + const startIndex = index; + const marker = findMarker(parent, index); + let n = parent._start; + if (marker !== null) { + n = marker.p; + index -= marker.index; + // we need to iterate one to the left so that the algorithm works + if (index === 0) { + // @todo refactor this as it actually doesn't consider formats + n = n.prev; // important! get the left undeleted item so that we can actually decrease index + index += (n && n.countable && !n.deleted) ? n.length : 0; + } + } + for (; n !== null; n = n.right) { + if (!n.deleted && n.countable) { + if (index <= n.length) { + if (index < n.length) { + // insert in-between + getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index)); + } + break + } + index -= n.length; + } + } + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, startIndex, content.length); + } + return typeListInsertGenericsAfter(transaction, parent, n, content) +}; + +/** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {number} index + * @param {number} length + * + * @private + * @function + */ +const typeListDelete = (transaction, parent, index, length) => { + if (length === 0) { return } + const startIndex = index; + const startLength = length; + const marker = findMarker(parent, index); + let n = parent._start; + if (marker !== null) { + n = marker.p; + index -= marker.index; + } + // compute the first item to be deleted + for (; n !== null && index > 0; n = n.right) { + if (!n.deleted && n.countable) { + if (index < n.length) { + getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index)); + } + index -= n.length; + } + } + // delete all items until done + while (length > 0 && n !== null) { + if (!n.deleted) { + if (length < n.length) { + getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length)); + } + n.delete(transaction); + length -= n.length; + } + n = n.right; + } + if (length > 0) { + throw error.create('array length exceeded') + } + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, startIndex, -startLength + length /* in case we remove the above exception */); + } +}; + +/** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {string} key + * + * @private + * @function + */ +const typeMapDelete = (transaction, parent, key) => { + const c = parent._map.get(key); + if (c !== undefined) { + c.delete(transaction); + } +}; + +/** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {string} key + * @param {Object|number|Array|string|Uint8Array|AbstractType} value + * + * @private + * @function + */ +const typeMapSet = (transaction, parent, key, value) => { + const left = parent._map.get(key) || null; + const doc = transaction.doc; + const ownClientId = doc.clientID; + let content; + if (value == null) { + content = new ContentAny([value]); + } else { + switch (value.constructor) { + case Number: + case Object: + case Boolean: + case Array: + case String: + content = new ContentAny([value]); + break + case Uint8Array: + content = new ContentBinary(/** @type {Uint8Array} */ (value)); + break + case Doc: + content = new ContentDoc(/** @type {Doc} */ (value)); + break + default: + if (value instanceof AbstractType) { + content = new ContentType(value); + } else { + throw new Error('Unexpected content type') + } + } + } + new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0); +}; + +/** + * @param {AbstractType} parent + * @param {string} key + * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined} + * + * @private + * @function + */ +const typeMapGet = (parent, key) => { + const val = parent._map.get(key); + return val !== undefined && !val.deleted ? val.content.getContent()[val.length - 1] : undefined +}; + +/** + * @param {AbstractType} parent + * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined>} + * + * @private + * @function + */ +const typeMapGetAll = (parent) => { + /** + * @type {Object} + */ + const res = {}; + parent._map.forEach((value, key) => { + if (!value.deleted) { + res[key] = value.content.getContent()[value.length - 1]; + } + }); + return res +}; + +/** + * @param {AbstractType} parent + * @param {string} key + * @return {boolean} + * + * @private + * @function + */ +const typeMapHas = (parent, key) => { + const val = parent._map.get(key); + return val !== undefined && !val.deleted +}; + +/** + * @param {AbstractType} parent + * @param {string} key + * @param {Snapshot} snapshot + * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined} + * + * @private + * @function + */ +const typeMapGetSnapshot = (parent, key, snapshot) => { + let v = parent._map.get(key) || null; + while (v !== null && (!snapshot.sv.has(v.id.client) || v.id.clock >= (snapshot.sv.get(v.id.client) || 0))) { + v = v.left; + } + return v !== null && isVisible(v, snapshot) ? v.content.getContent()[v.length - 1] : undefined +}; + +/** + * @param {Map} map + * @return {IterableIterator>} + * + * @private + * @function + */ +const createMapIterator = map => iterator.iteratorFilter(map.entries(), /** @param {any} entry */ entry => !entry[1].deleted); + +/** + * @module YArray + */ + +/** + * Event that describes the changes on a YArray + * @template T + */ +class YArrayEvent extends YEvent { + /** + * @param {YArray} yarray The changed type + * @param {Transaction} transaction The transaction object + */ + constructor (yarray, transaction) { + super(yarray, transaction); + this._transaction = transaction; + } +} + +/** + * A shared Array implementation. + * @template T + * @extends AbstractType> + * @implements {Iterable} + */ +class YArray extends AbstractType { + constructor () { + super(); + /** + * @type {Array?} + * @private + */ + this._prelimContent = []; + /** + * @type {Array} + */ + this._searchMarker = []; + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item); + this.insert(0, /** @type {Array} */ (this._prelimContent)); + this._prelimContent = null; + } + + _copy () { + return new YArray() + } + + get length () { + return this._prelimContent === null ? this._length : this._prelimContent.length + } + + /** + * Creates YArrayEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + super._callObserver(transaction, parentSubs); + callTypeObservers(this, transaction, new YArrayEvent(this, transaction)); + } + + /** + * Inserts new content at an index. + * + * Important: This function expects an array of content. Not just a content + * object. The reason for this "weirdness" is that inserting several elements + * is very efficient when it is done as a single operation. + * + * @example + * // Insert character 'a' at position 0 + * yarray.insert(0, ['a']) + * // Insert numbers 1, 2 at position 1 + * yarray.insert(1, [1, 2]) + * + * @param {number} index The index to insert content at. + * @param {Array} content The array of content + */ + insert (index, content) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListInsertGenerics(transaction, this, index, content); + }); + } else { + /** @type {Array} */ (this._prelimContent).splice(index, 0, ...content); + } + } + + /** + * Appends content to this YArray. + * + * @param {Array} content Array of content to append. + */ + push (content) { + this.insert(this.length, content); + } + + /** + * Preppends content to this YArray. + * + * @param {Array} content Array of content to preppend. + */ + unshift (content) { + this.insert(0, content); + } + + /** + * Deletes elements starting from an index. + * + * @param {number} index Index at which to start deleting elements + * @param {number} length The number of elements to remove. Defaults to 1. + */ + delete (index, length = 1) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListDelete(transaction, this, index, length); + }); + } else { + /** @type {Array} */ (this._prelimContent).splice(index, length); + } + } + + /** + * Returns the i-th element from a YArray. + * + * @param {number} index The index of the element to return from the YArray + * @return {T} + */ + get (index) { + return typeListGet(this, index) + } + + /** + * Transforms this YArray to a JavaScript Array. + * + * @return {Array} + */ + toArray () { + return typeListToArray(this) + } + + /** + * Transforms this Shared Type to a JSON object. + * + * @return {Array} + */ + toJSON () { + return this.map(c => c instanceof AbstractType ? c.toJSON() : c) + } + + /** + * Returns an Array with the result of calling a provided function on every + * element of this YArray. + * + * @template T,M + * @param {function(T,number,YArray):M} f Function that produces an element of the new Array + * @return {Array} A new array with each element being the result of the + * callback function + */ + map (f) { + return typeListMap(this, /** @type {any} */ (f)) + } + + /** + * Executes a provided function on once on overy element of this YArray. + * + * @param {function(T,number,YArray):void} f A function to execute on every element of this YArray. + */ + forEach (f) { + typeListForEach(this, f); + } + + /** + * @return {IterableIterator} + */ + [Symbol.iterator] () { + return typeListCreateIterator(this) + } + + /** + * @param {AbstractUpdateEncoder} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YArrayRefID); + } +} + +/** + * @param {AbstractUpdateDecoder} decoder + * + * @private + * @function + */ +const readYArray = decoder => new YArray(); + +/** + * @template T + * Event that describes the changes on a YMap. + */ +class YMapEvent extends YEvent { + /** + * @param {YMap} ymap The YArray that changed. + * @param {Transaction} transaction + * @param {Set} subs The keys that changed. + */ + constructor (ymap, transaction, subs) { + super(ymap, transaction); + this.keysChanged = subs; + } +} + +/** + * @template T number|string|Object|Array|Uint8Array + * A shared Map implementation. + * + * @extends AbstractType> + * @implements {Iterable} + */ +class YMap extends AbstractType { + /** + * + * @param {Iterable=} entries - an optional iterable to initialize the YMap + */ + constructor (entries) { + super(); + /** + * @type {Map?} + * @private + */ + this._prelimContent = null; + + if (entries === undefined) { + this._prelimContent = new Map(); + } else { + this._prelimContent = new Map(entries); + } + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item) + ;/** @type {Map} */ (this._prelimContent).forEach((value, key) => { + this.set(key, value); + }); + this._prelimContent = null; + } + + _copy () { + return new YMap() + } + + /** + * Creates YMapEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs)); + } + + /** + * Transforms this Shared Type to a JSON object. + * + * @return {Object} + */ + toJSON () { + /** + * @type {Object} + */ + const map = {}; + this._map.forEach((item, key) => { + if (!item.deleted) { + const v = item.content.getContent()[item.length - 1]; + map[key] = v instanceof AbstractType ? v.toJSON() : v; + } + }); + return map + } + + /** + * Returns the size of the YMap (count of key/value pairs) + * + * @return {number} + */ + get size () { + return [...createMapIterator(this._map)].length + } + + /** + * Returns the keys for each element in the YMap Type. + * + * @return {IterableIterator} + */ + keys () { + return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[0]) + } + + /** + * Returns the values for each element in the YMap Type. + * + * @return {IterableIterator} + */ + values () { + return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[1].content.getContent()[v[1].length - 1]) + } + + /** + * Returns an Iterator of [key, value] pairs + * + * @return {IterableIterator} + */ + entries () { + return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => [v[0], v[1].content.getContent()[v[1].length - 1]]) + } + + /** + * Executes a provided function on once on every key-value pair. + * + * @param {function(T,string,YMap):void} f A function to execute on every element of this YArray. + */ + forEach (f) { + /** + * @type {Object} + */ + const map = {}; + this._map.forEach((item, key) => { + if (!item.deleted) { + f(item.content.getContent()[item.length - 1], key, this); + } + }); + return map + } + + /** + * @return {IterableIterator} + */ + [Symbol.iterator] () { + return this.entries() + } + + /** + * Remove a specified element from this YMap. + * + * @param {string} key The key of the element to remove. + */ + delete (key) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapDelete(transaction, this, key); + }); + } else { + /** @type {Map} */ (this._prelimContent).delete(key); + } + } + + /** + * Adds or updates an element with a specified key and value. + * + * @param {string} key The key of the element to add to this YMap + * @param {T} value The value of the element to add + */ + set (key, value) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapSet(transaction, this, key, value); + }); + } else { + /** @type {Map} */ (this._prelimContent).set(key, value); + } + return value + } + + /** + * Returns a specified element from this YMap. + * + * @param {string} key + * @return {T|undefined} + */ + get (key) { + return /** @type {any} */ (typeMapGet(this, key)) + } + + /** + * Returns a boolean indicating whether the specified key exists or not. + * + * @param {string} key The key to test. + * @return {boolean} + */ + has (key) { + return typeMapHas(this, key) + } + + /** + * @param {AbstractUpdateEncoder} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YMapRefID); + } +} + +/** + * @param {AbstractUpdateDecoder} decoder + * + * @private + * @function + */ +const readYMap = decoder => new YMap(); + +/** + * @param {any} a + * @param {any} b + * @return {boolean} + */ +const equalAttrs = (a, b) => a === b || (typeof a === 'object' && typeof b === 'object' && a && b && object.equalFlat(a, b)); + +class ItemTextListPosition { + /** + * @param {Item|null} left + * @param {Item|null} right + * @param {number} index + * @param {Map} currentAttributes + */ + constructor (left, right, index, currentAttributes) { + this.left = left; + this.right = right; + this.index = index; + this.currentAttributes = currentAttributes; + } + + /** + * Only call this if you know that this.right is defined + */ + forward () { + if (this.right === null) { + error.unexpectedCase(); + } + switch (this.right.content.constructor) { + case ContentEmbed: + case ContentString: + if (!this.right.deleted) { + this.index += this.right.length; + } + break + case ContentFormat: + if (!this.right.deleted) { + updateCurrentAttributes(this.currentAttributes, /** @type {ContentFormat} */ (this.right.content)); + } + break + } + this.left = this.right; + this.right = this.right.right; + } +} + +/** + * @param {Transaction} transaction + * @param {ItemTextListPosition} pos + * @param {number} count steps to move forward + * @return {ItemTextListPosition} + * + * @private + * @function + */ +const findNextPosition = (transaction, pos, count) => { + while (pos.right !== null && count > 0) { + switch (pos.right.content.constructor) { + case ContentEmbed: + case ContentString: + if (!pos.right.deleted) { + if (count < pos.right.length) { + // split right + getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count)); + } + pos.index += pos.right.length; + count -= pos.right.length; + } + break + case ContentFormat: + if (!pos.right.deleted) { + updateCurrentAttributes(pos.currentAttributes, /** @type {ContentFormat} */ (pos.right.content)); + } + break + } + pos.left = pos.right; + pos.right = pos.right.right; + // pos.forward() - we don't forward because that would halve the performance because we already do the checks above + } + return pos +}; + +/** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {number} index + * @return {ItemTextListPosition} + * + * @private + * @function + */ +const findPosition = (transaction, parent, index) => { + const currentAttributes = new Map(); + const marker = findMarker(parent, index); + if (marker) { + const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes); + return findNextPosition(transaction, pos, index - marker.index) + } else { + const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes); + return findNextPosition(transaction, pos, index) + } +}; + +/** + * Negate applied formats + * + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {Map} negatedAttributes + * + * @private + * @function + */ +const insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => { + // check if we really need to remove attributes + while ( + currPos.right !== null && ( + currPos.right.deleted === true || ( + currPos.right.content.constructor === ContentFormat && + equalAttrs(negatedAttributes.get(/** @type {ContentFormat} */ (currPos.right.content).key), /** @type {ContentFormat} */ (currPos.right.content).value) + ) + ) + ) { + if (!currPos.right.deleted) { + negatedAttributes.delete(/** @type {ContentFormat} */ (currPos.right.content).key); + } + currPos.forward(); + } + const doc = transaction.doc; + const ownClientId = doc.clientID; + let left = currPos.left; + const right = currPos.right; + negatedAttributes.forEach((val, key) => { + left = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val)); + left.integrate(transaction, 0); + }); +}; + +/** + * @param {Map} currentAttributes + * @param {ContentFormat} format + * + * @private + * @function + */ +const updateCurrentAttributes = (currentAttributes, format) => { + const { key, value } = format; + if (value === null) { + currentAttributes.delete(key); + } else { + currentAttributes.set(key, value); + } +}; + +/** + * @param {ItemTextListPosition} currPos + * @param {Object} attributes + * + * @private + * @function + */ +const minimizeAttributeChanges = (currPos, attributes) => { + // go right while attributes[right.key] === right.value (or right is deleted) + while (true) { + if (currPos.right === null) { + break + } else if (currPos.right.deleted || (currPos.right.content.constructor === ContentFormat && equalAttrs(attributes[(/** @type {ContentFormat} */ (currPos.right.content)).key] || null, /** @type {ContentFormat} */ (currPos.right.content).value))) ; else { + break + } + currPos.forward(); + } +}; + +/** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {Object} attributes + * @return {Map} + * + * @private + * @function + **/ +const insertAttributes = (transaction, parent, currPos, attributes) => { + const doc = transaction.doc; + const ownClientId = doc.clientID; + const negatedAttributes = new Map(); + // insert format-start items + for (const key in attributes) { + const val = attributes[key]; + const currentVal = currPos.currentAttributes.get(key) || null; + if (!equalAttrs(currentVal, val)) { + // save negated attribute (set null if currentVal undefined) + negatedAttributes.set(key, currentVal); + const { left, right } = currPos; + currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val)); + currPos.right.integrate(transaction, 0); + currPos.forward(); + } + } + return negatedAttributes +}; + +/** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {string|object} text + * @param {Object} attributes + * + * @private + * @function + **/ +const insertText = (transaction, parent, currPos, text, attributes) => { + currPos.currentAttributes.forEach((val, key) => { + if (attributes[key] === undefined) { + attributes[key] = null; + } + }); + const doc = transaction.doc; + const ownClientId = doc.clientID; + minimizeAttributeChanges(currPos, attributes); + const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes); + // insert content + const content = text.constructor === String ? new ContentString(/** @type {string} */ (text)) : new ContentEmbed(text); + let { left, right, index } = currPos; + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength()); + } + right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content); + right.integrate(transaction, 0); + currPos.right = right; + currPos.index = index; + currPos.forward(); + insertNegatedAttributes(transaction, parent, currPos, negatedAttributes); +}; + +/** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {number} length + * @param {Object} attributes + * + * @private + * @function + */ +const formatText = (transaction, parent, currPos, length, attributes) => { + const doc = transaction.doc; + const ownClientId = doc.clientID; + minimizeAttributeChanges(currPos, attributes); + const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes); + // iterate until first non-format or null is found + // delete all formats with attributes[format.key] != null + while (length > 0 && currPos.right !== null) { + if (!currPos.right.deleted) { + switch (currPos.right.content.constructor) { + case ContentFormat: { + const { key, value } = /** @type {ContentFormat} */ (currPos.right.content); + const attr = attributes[key]; + if (attr !== undefined) { + if (equalAttrs(attr, value)) { + negatedAttributes.delete(key); + } else { + negatedAttributes.set(key, value); + } + currPos.right.delete(transaction); + } + break + } + case ContentEmbed: + case ContentString: + if (length < currPos.right.length) { + getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length)); + } + length -= currPos.right.length; + break + } + } + currPos.forward(); + } + // Quill just assumes that the editor starts with a newline and that it always + // ends with a newline. We only insert that newline when a new newline is + // inserted - i.e when length is bigger than type.length + if (length > 0) { + let newlines = ''; + for (; length > 0; length--) { + newlines += '\n'; + } + currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines)); + currPos.right.integrate(transaction, 0); + currPos.forward(); + } + insertNegatedAttributes(transaction, parent, currPos, negatedAttributes); +}; + +/** + * Call this function after string content has been deleted in order to + * clean up formatting Items. + * + * @param {Transaction} transaction + * @param {Item} start + * @param {Item|null} end exclusive end, automatically iterates to the next Content Item + * @param {Map} startAttributes + * @param {Map} endAttributes This attribute is modified! + * @return {number} The amount of formatting Items deleted. + * + * @function + */ +const cleanupFormattingGap = (transaction, start, end, startAttributes, endAttributes) => { + while (end && end.content.constructor !== ContentString && end.content.constructor !== ContentEmbed) { + if (!end.deleted && end.content.constructor === ContentFormat) { + updateCurrentAttributes(endAttributes, /** @type {ContentFormat} */ (end.content)); + } + end = end.right; + } + let cleanups = 0; + while (start !== end) { + if (!start.deleted) { + const content = start.content; + switch (content.constructor) { + case ContentFormat: { + const { key, value } = /** @type {ContentFormat} */ (content); + if ((endAttributes.get(key) || null) !== value || (startAttributes.get(key) || null) === value) { + // Either this format is overwritten or it is not necessary because the attribute already existed. + start.delete(transaction); + cleanups++; + } + break + } + } + } + start = /** @type {Item} */ (start.right); + } + return cleanups +}; + +/** + * @param {Transaction} transaction + * @param {Item | null} item + */ +const cleanupContextlessFormattingGap = (transaction, item) => { + // iterate until item.right is null or content + while (item && item.right && (item.right.deleted || (item.right.content.constructor !== ContentString && item.right.content.constructor !== ContentEmbed))) { + item = item.right; + } + const attrs = new Set(); + // iterate back until a content item is found + while (item && (item.deleted || (item.content.constructor !== ContentString && item.content.constructor !== ContentEmbed))) { + if (!item.deleted && item.content.constructor === ContentFormat) { + const key = /** @type {ContentFormat} */ (item.content).key; + if (attrs.has(key)) { + item.delete(transaction); + } else { + attrs.add(key); + } + } + item = item.left; + } +}; + +/** + * This function is experimental and subject to change / be removed. + * + * Ideally, we don't need this function at all. Formatting attributes should be cleaned up + * automatically after each change. This function iterates twice over the complete YText type + * and removes unnecessary formatting attributes. This is also helpful for testing. + * + * This function won't be exported anymore as soon as there is confidence that the YText type works as intended. + * + * @param {YText} type + * @return {number} How many formatting attributes have been cleaned up. + */ +const cleanupYTextFormatting = type => { + let res = 0; + transact(/** @type {Doc} */ (type.doc), transaction => { + let start = /** @type {Item} */ (type._start); + let end = type._start; + let startAttributes = map.create(); + const currentAttributes = map.copy(startAttributes); + while (end) { + if (end.deleted === false) { + switch (end.content.constructor) { + case ContentFormat: + updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (end.content)); + break + case ContentEmbed: + case ContentString: + res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes); + startAttributes = map.copy(currentAttributes); + start = end; + break + } + } + end = end.right; + } + }); + return res +}; + +/** + * @param {Transaction} transaction + * @param {ItemTextListPosition} currPos + * @param {number} length + * @return {ItemTextListPosition} + * + * @private + * @function + */ +const deleteText = (transaction, currPos, length) => { + const startLength = length; + const startAttrs = map.copy(currPos.currentAttributes); + const start = currPos.right; + while (length > 0 && currPos.right !== null) { + if (currPos.right.deleted === false) { + switch (currPos.right.content.constructor) { + case ContentEmbed: + case ContentString: + if (length < currPos.right.length) { + getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length)); + } + length -= currPos.right.length; + currPos.right.delete(transaction); + break + } + } + currPos.forward(); + } + if (start) { + cleanupFormattingGap(transaction, start, currPos.right, startAttrs, map.copy(currPos.currentAttributes)); + } + const parent = /** @type {AbstractType} */ (/** @type {Item} */ (currPos.left || currPos.right).parent); + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length); + } + return currPos +}; + +/** + * The Quill Delta format represents changes on a text document with + * formatting information. For mor information visit {@link https://quilljs.com/docs/delta/|Quill Delta} + * + * @example + * { + * ops: [ + * { insert: 'Gandalf', attributes: { bold: true } }, + * { insert: ' the ' }, + * { insert: 'Grey', attributes: { color: '#cccccc' } } + * ] + * } + * + */ + +/** + * Attributes that can be assigned to a selection of text. + * + * @example + * { + * bold: true, + * font-size: '40px' + * } + * + * @typedef {Object} TextAttributes + */ + +/** + * @typedef {Object} DeltaItem + * @property {number|undefined} DeltaItem.delete + * @property {number|undefined} DeltaItem.retain + * @property {string|undefined} DeltaItem.insert + * @property {Object} DeltaItem.attributes + */ + +/** + * Event that describes the changes on a YText type. + */ +class YTextEvent extends YEvent { + /** + * @param {YText} ytext + * @param {Transaction} transaction + */ + constructor (ytext, transaction) { + super(ytext, transaction); + /** + * @type {Array|null} + */ + this._delta = null; + } + + /** + * Compute the changes in the delta format. + * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document. + * + * @type {Array} + * + * @public + */ + get delta () { + if (this._delta === null) { + const y = /** @type {Doc} */ (this.target.doc); + this._delta = []; + transact(y, transaction => { + const delta = /** @type {Array} */ (this._delta); + const currentAttributes = new Map(); // saves all current attributes for insert + const oldAttributes = new Map(); + let item = this.target._start; + /** + * @type {string?} + */ + let action = null; + /** + * @type {Object} + */ + const attributes = {}; // counts added or removed new attributes for retain + /** + * @type {string|object} + */ + let insert = ''; + let retain = 0; + let deleteLen = 0; + const addOp = () => { + if (action !== null) { + /** + * @type {any} + */ + let op; + switch (action) { + case 'delete': + op = { delete: deleteLen }; + deleteLen = 0; + break + case 'insert': + op = { insert }; + if (currentAttributes.size > 0) { + op.attributes = {}; + currentAttributes.forEach((value, key) => { + if (value !== null) { + op.attributes[key] = value; + } + }); + } + insert = ''; + break + case 'retain': + op = { retain }; + if (Object.keys(attributes).length > 0) { + op.attributes = {}; + for (const key in attributes) { + op.attributes[key] = attributes[key]; + } + } + retain = 0; + break + } + delta.push(op); + action = null; + } + }; + while (item !== null) { + switch (item.content.constructor) { + case ContentEmbed: + if (this.adds(item)) { + if (!this.deletes(item)) { + addOp(); + action = 'insert'; + insert = /** @type {ContentEmbed} */ (item.content).embed; + addOp(); + } + } else if (this.deletes(item)) { + if (action !== 'delete') { + addOp(); + action = 'delete'; + } + deleteLen += 1; + } else if (!item.deleted) { + if (action !== 'retain') { + addOp(); + action = 'retain'; + } + retain += 1; + } + break + case ContentString: + if (this.adds(item)) { + if (!this.deletes(item)) { + if (action !== 'insert') { + addOp(); + action = 'insert'; + } + insert += /** @type {ContentString} */ (item.content).str; + } + } else if (this.deletes(item)) { + if (action !== 'delete') { + addOp(); + action = 'delete'; + } + deleteLen += item.length; + } else if (!item.deleted) { + if (action !== 'retain') { + addOp(); + action = 'retain'; + } + retain += item.length; + } + break + case ContentFormat: { + const { key, value } = /** @type {ContentFormat} */ (item.content); + if (this.adds(item)) { + if (!this.deletes(item)) { + const curVal = currentAttributes.get(key) || null; + if (!equalAttrs(curVal, value)) { + if (action === 'retain') { + addOp(); + } + if (equalAttrs(value, (oldAttributes.get(key) || null))) { + delete attributes[key]; + } else { + attributes[key] = value; + } + } else { + item.delete(transaction); + } + } + } else if (this.deletes(item)) { + oldAttributes.set(key, value); + const curVal = currentAttributes.get(key) || null; + if (!equalAttrs(curVal, value)) { + if (action === 'retain') { + addOp(); + } + attributes[key] = curVal; + } + } else if (!item.deleted) { + oldAttributes.set(key, value); + const attr = attributes[key]; + if (attr !== undefined) { + if (!equalAttrs(attr, value)) { + if (action === 'retain') { + addOp(); + } + if (value === null) { + attributes[key] = value; + } else { + delete attributes[key]; + } + } else { + item.delete(transaction); + } + } + } + if (!item.deleted) { + if (action === 'insert') { + addOp(); + } + updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (item.content)); + } + break + } + } + item = item.right; + } + addOp(); + while (delta.length > 0) { + const lastOp = delta[delta.length - 1]; + if (lastOp.retain !== undefined && lastOp.attributes === undefined) { + // retain delta's if they don't assign attributes + delta.pop(); + } else { + break + } + } + }); + } + return this._delta + } +} + +/** + * Type that represents text with formatting information. + * + * This type replaces y-richtext as this implementation is able to handle + * block formats (format information on a paragraph), embeds (complex elements + * like pictures and videos), and text formats (**bold**, *italic*). + * + * @extends AbstractType + */ +class YText extends AbstractType { + /** + * @param {String} [string] The initial value of the YText. + */ + constructor (string) { + super(); + /** + * Array of pending operations on this type + * @type {Array?} + */ + this._pending = string !== undefined ? [() => this.insert(0, string)] : []; + /** + * @type {Array} + */ + this._searchMarker = []; + } + + /** + * Number of characters of this text type. + * + * @type {number} + */ + get length () { + return this._length + } + + /** + * @param {Doc} y + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item); + try { + /** @type {Array} */ (this._pending).forEach(f => f()); + } catch (e) { + console.error(e); + } + this._pending = null; + } + + _copy () { + return new YText() + } + + /** + * Creates YTextEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + super._callObserver(transaction, parentSubs); + const event = new YTextEvent(this, transaction); + const doc = transaction.doc; + // If a remote change happened, we try to cleanup potential formatting duplicates. + if (!transaction.local) { + // check if another formatting item was inserted + let foundFormattingItem = false; + for (const [client, afterClock] of transaction.afterState.entries()) { + const clock = transaction.beforeState.get(client) || 0; + if (afterClock === clock) { + continue + } + iterateStructs(transaction, /** @type {Array} */ (doc.store.clients.get(client)), clock, afterClock, item => { + if (!item.deleted && /** @type {Item} */ (item).content.constructor === ContentFormat) { + foundFormattingItem = true; + } + }); + if (foundFormattingItem) { + break + } + } + if (!foundFormattingItem) { + iterateDeletedStructs(transaction, transaction.deleteSet, item => { + if (item instanceof GC || foundFormattingItem) { + return + } + if (item.parent === this && item.content.constructor === ContentFormat) { + foundFormattingItem = true; + } + }); + } + transact(doc, (t) => { + if (foundFormattingItem) { + // If a formatting item was inserted, we simply clean the whole type. + // We need to compute currentAttributes for the current position anyway. + cleanupYTextFormatting(this); + } else { + // If no formatting attribute was inserted, we can make due with contextless + // formatting cleanups. + // Contextless: it is not necessary to compute currentAttributes for the affected position. + iterateDeletedStructs(t, t.deleteSet, item => { + if (item instanceof GC) { + return + } + if (item.parent === this) { + cleanupContextlessFormattingGap(t, item); + } + }); + } + }); + } + callTypeObservers(this, transaction, event); + } + + /** + * Returns the unformatted string representation of this YText type. + * + * @public + */ + toString () { + let str = ''; + /** + * @type {Item|null} + */ + let n = this._start; + while (n !== null) { + if (!n.deleted && n.countable && n.content.constructor === ContentString) { + str += /** @type {ContentString} */ (n.content).str; + } + n = n.right; + } + return str + } + + /** + * Returns the unformatted string representation of this YText type. + * + * @return {string} + * @public + */ + toJSON () { + return this.toString() + } + + /** + * Apply a {@link Delta} on this shared YText type. + * + * @param {any} delta The changes to apply on this element. + * @param {object} [opts] + * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true. + * + * + * @public + */ + applyDelta (delta, { sanitize = true } = {}) { + if (this.doc !== null) { + transact(this.doc, transaction => { + const currPos = new ItemTextListPosition(null, this._start, 0, new Map()); + for (let i = 0; i < delta.length; i++) { + const op = delta[i]; + if (op.insert !== undefined) { + // Quill assumes that the content starts with an empty paragraph. + // Yjs/Y.Text assumes that it starts empty. We always hide that + // there is a newline at the end of the content. + // If we omit this step, clients will see a different number of + // paragraphs, but nothing bad will happen. + const ins = (!sanitize && typeof op.insert === 'string' && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === '\n') ? op.insert.slice(0, -1) : op.insert; + if (typeof ins !== 'string' || ins.length > 0) { + insertText(transaction, this, currPos, ins, op.attributes || {}); + } + } else if (op.retain !== undefined) { + formatText(transaction, this, currPos, op.retain, op.attributes || {}); + } else if (op.delete !== undefined) { + deleteText(transaction, currPos, op.delete); + } + } + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.applyDelta(delta)); + } + } + + /** + * Returns the Delta representation of this YText type. + * + * @param {Snapshot} [snapshot] + * @param {Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', ID):any} [computeYChange] + * @return {any} The Delta representation of this type. + * + * @public + */ + toDelta (snapshot, prevSnapshot, computeYChange) { + /** + * @type{Array} + */ + const ops = []; + const currentAttributes = new Map(); + const doc = /** @type {Doc} */ (this.doc); + let str = ''; + let n = this._start; + function packStr () { + if (str.length > 0) { + // pack str with attributes to ops + /** + * @type {Object} + */ + const attributes = {}; + let addAttributes = false; + currentAttributes.forEach((value, key) => { + addAttributes = true; + attributes[key] = value; + }); + /** + * @type {Object} + */ + const op = { insert: str }; + if (addAttributes) { + op.attributes = attributes; + } + ops.push(op); + str = ''; + } + } + // snapshots are merged again after the transaction, so we need to keep the + // transalive until we are done + transact(doc, transaction => { + if (snapshot) { + splitSnapshotAffectedStructs(transaction, snapshot); + } + if (prevSnapshot) { + splitSnapshotAffectedStructs(transaction, prevSnapshot); + } + while (n !== null) { + if (isVisible(n, snapshot) || (prevSnapshot !== undefined && isVisible(n, prevSnapshot))) { + switch (n.content.constructor) { + case ContentString: { + const cur = currentAttributes.get('ychange'); + if (snapshot !== undefined && !isVisible(n, snapshot)) { + if (cur === undefined || cur.user !== n.id.client || cur.state !== 'removed') { + packStr(); + currentAttributes.set('ychange', computeYChange ? computeYChange('removed', n.id) : { type: 'removed' }); + } + } else if (prevSnapshot !== undefined && !isVisible(n, prevSnapshot)) { + if (cur === undefined || cur.user !== n.id.client || cur.state !== 'added') { + packStr(); + currentAttributes.set('ychange', computeYChange ? computeYChange('added', n.id) : { type: 'added' }); + } + } else if (cur !== undefined) { + packStr(); + currentAttributes.delete('ychange'); + } + str += /** @type {ContentString} */ (n.content).str; + break + } + case ContentEmbed: { + packStr(); + /** + * @type {Object} + */ + const op = { + insert: /** @type {ContentEmbed} */ (n.content).embed + }; + if (currentAttributes.size > 0) { + const attrs = /** @type {Object} */ ({}); + op.attributes = attrs; + currentAttributes.forEach((value, key) => { + attrs[key] = value; + }); + } + ops.push(op); + break + } + case ContentFormat: + if (isVisible(n, snapshot)) { + packStr(); + updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (n.content)); + } + break + } + } + n = n.right; + } + packStr(); + }, splitSnapshotAffectedStructs); + return ops + } + + /** + * Insert text at a given index. + * + * @param {number} index The index at which to start inserting. + * @param {String} text The text to insert at the specified position. + * @param {TextAttributes} [attributes] Optionally define some formatting + * information to apply on the inserted + * Text. + * @public + */ + insert (index, text, attributes) { + if (text.length <= 0) { + return + } + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + const pos = findPosition(transaction, this, index); + if (!attributes) { + attributes = {}; + // @ts-ignore + pos.currentAttributes.forEach((v, k) => { attributes[k] = v; }); + } + insertText(transaction, this, pos, text, attributes); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.insert(index, text, attributes)); + } + } + + /** + * Inserts an embed at a index. + * + * @param {number} index The index to insert the embed at. + * @param {Object} embed The Object that represents the embed. + * @param {TextAttributes} attributes Attribute information to apply on the + * embed + * + * @public + */ + insertEmbed (index, embed, attributes = {}) { + if (embed.constructor !== Object) { + throw new Error('Embed must be an Object') + } + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + const pos = findPosition(transaction, this, index); + insertText(transaction, this, pos, embed, attributes); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.insertEmbed(index, embed, attributes)); + } + } + + /** + * Deletes text starting from an index. + * + * @param {number} index Index at which to start deleting. + * @param {number} length The number of characters to remove. Defaults to 1. + * + * @public + */ + delete (index, length) { + if (length === 0) { + return + } + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + deleteText(transaction, findPosition(transaction, this, index), length); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.delete(index, length)); + } + } + + /** + * Assigns properties to a range of text. + * + * @param {number} index The position where to start formatting. + * @param {number} length The amount of characters to assign properties to. + * @param {TextAttributes} attributes Attribute information to apply on the + * text. + * + * @public + */ + format (index, length, attributes) { + if (length === 0) { + return + } + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + const pos = findPosition(transaction, this, index); + if (pos.right === null) { + return + } + formatText(transaction, this, pos, length, attributes); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.format(index, length, attributes)); + } + } + + /** + * @param {AbstractUpdateEncoder} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YTextRefID); + } +} + +/** + * @param {AbstractUpdateDecoder} decoder + * @return {YText} + * + * @private + * @function + */ +const readYText = decoder => new YText(); + +/** + * @module YXml + */ + +/** + * Define the elements to which a set of CSS queries apply. + * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors|CSS_Selectors} + * + * @example + * query = '.classSelector' + * query = 'nodeSelector' + * query = '#idSelector' + * + * @typedef {string} CSS_Selector + */ + +/** + * Dom filter function. + * + * @callback domFilter + * @param {string} nodeName The nodeName of the element + * @param {Map} attributes The map of attributes. + * @return {boolean} Whether to include the Dom node in the YXmlElement. + */ + +/** + * Represents a subset of the nodes of a YXmlElement / YXmlFragment and a + * position within them. + * + * Can be created with {@link YXmlFragment#createTreeWalker} + * + * @public + * @implements {Iterable} + */ +class YXmlTreeWalker { + /** + * @param {YXmlFragment | YXmlElement} root + * @param {function(AbstractType):boolean} [f] + */ + constructor (root, f = () => true) { + this._filter = f; + this._root = root; + /** + * @type {Item} + */ + this._currentNode = /** @type {Item} */ (root._start); + this._firstCall = true; + } + + [Symbol.iterator] () { + return this + } + + /** + * Get the next node. + * + * @return {IteratorResult} The next node. + * + * @public + */ + next () { + /** + * @type {Item|null} + */ + let n = this._currentNode; + let type = /** @type {any} */ (n.content).type; + if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { // if first call, we check if we can use the first item + do { + type = /** @type {any} */ (n.content).type; + if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) { + // walk down in the tree + n = type._start; + } else { + // walk right or up in the tree + while (n !== null) { + if (n.right !== null) { + n = n.right; + break + } else if (n.parent === this._root) { + n = null; + } else { + n = /** @type {AbstractType} */ (n.parent)._item; + } + } + } + } while (n !== null && (n.deleted || !this._filter(/** @type {ContentType} */ (n.content).type))) + } + this._firstCall = false; + if (n === null) { + // @ts-ignore + return { value: undefined, done: true } + } + this._currentNode = n; + return { value: /** @type {any} */ (n.content).type, done: false } + } +} + +/** + * Represents a list of {@link YXmlElement}.and {@link YXmlText} types. + * A YxmlFragment is similar to a {@link YXmlElement}, but it does not have a + * nodeName and it does not have attributes. Though it can be bound to a DOM + * element - in this case the attributes and the nodeName are not shared. + * + * @public + * @extends AbstractType + */ +class YXmlFragment extends AbstractType { + constructor () { + super(); + /** + * @type {Array|null} + */ + this._prelimContent = []; + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item); + this.insert(0, /** @type {Array} */ (this._prelimContent)); + this._prelimContent = null; + } + + _copy () { + return new YXmlFragment() + } + + get length () { + return this._prelimContent === null ? this._length : this._prelimContent.length + } + + /** + * Create a subtree of childNodes. + * + * @example + * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div') + * for (let node in walker) { + * // `node` is a div node + * nop(node) + * } + * + * @param {function(AbstractType):boolean} filter Function that is called on each child element and + * returns a Boolean indicating whether the child + * is to be included in the subtree. + * @return {YXmlTreeWalker} A subtree and a position within it. + * + * @public + */ + createTreeWalker (filter) { + return new YXmlTreeWalker(this, filter) + } + + /** + * Returns the first YXmlElement that matches the query. + * Similar to DOM's {@link querySelector}. + * + * Query support: + * - tagname + * TODO: + * - id + * - attribute + * + * @param {CSS_Selector} query The query on the children. + * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null. + * + * @public + */ + querySelector (query) { + query = query.toUpperCase(); + // @ts-ignore + const iterator = new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query); + const next = iterator.next(); + if (next.done) { + return null + } else { + return next.value + } + } + + /** + * Returns all YXmlElements that match the query. + * Similar to Dom's {@link querySelectorAll}. + * + * @todo Does not yet support all queries. Currently only query by tagName. + * + * @param {CSS_Selector} query The query on the children + * @return {Array} The elements that match this query. + * + * @public + */ + querySelectorAll (query) { + query = query.toUpperCase(); + // @ts-ignore + return Array.from(new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query)) + } + + /** + * Creates YXmlEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction)); + } + + /** + * Get the string representation of all the children of this YXmlFragment. + * + * @return {string} The string representation of all children. + */ + toString () { + return typeListMap(this, xml => xml.toString()).join('') + } + + /** + * @return {string} + */ + toJSON () { + return this.toString() + } + + /** + * Creates a Dom Element that mirrors this YXmlElement. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object} [hooks={}] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type. + * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks = {}, binding) { + const fragment = _document.createDocumentFragment(); + if (binding !== undefined) { + binding._createAssociation(fragment, this); + } + typeListForEach(this, xmlType => { + fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null); + }); + return fragment + } + + /** + * Inserts new content at an index. + * + * @example + * // Insert character 'a' at position 0 + * xml.insert(0, [new Y.XmlText('text')]) + * + * @param {number} index The index to insert content at + * @param {Array} content The array of content + */ + insert (index, content) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListInsertGenerics(transaction, this, index, content); + }); + } else { + // @ts-ignore _prelimContent is defined because this is not yet integrated + this._prelimContent.splice(index, 0, ...content); + } + } + + /** + * Deletes elements starting from an index. + * + * @param {number} index Index at which to start deleting elements + * @param {number} [length=1] The number of elements to remove. Defaults to 1. + */ + delete (index, length = 1) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListDelete(transaction, this, index, length); + }); + } else { + // @ts-ignore _prelimContent is defined because this is not yet integrated + this._prelimContent.splice(index, length); + } + } + + /** + * Transforms this YArray to a JavaScript Array. + * + * @return {Array} + */ + toArray () { + return typeListToArray(this) + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {AbstractUpdateEncoder} encoder The encoder to write data to. + */ + _write (encoder) { + encoder.writeTypeRef(YXmlFragmentRefID); + } +} + +/** + * @param {AbstractUpdateDecoder} decoder + * @return {YXmlFragment} + * + * @private + * @function + */ +const readYXmlFragment = decoder => new YXmlFragment(); + +/** + * An YXmlElement imitates the behavior of a + * {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}. + * + * * An YXmlElement has attributes (key value pairs) + * * An YXmlElement has childElements that must inherit from YXmlElement + */ +class YXmlElement extends YXmlFragment { + constructor (nodeName = 'UNDEFINED') { + super(); + this.nodeName = nodeName; + /** + * @type {Map|null} + */ + this._prelimAttrs = new Map(); + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item) + ;(/** @type {Map} */ (this._prelimAttrs)).forEach((value, key) => { + this.setAttribute(key, value); + }); + this._prelimAttrs = null; + } + + /** + * Creates an Item with the same effect as this Item (without position effect) + * + * @return {YXmlElement} + */ + _copy () { + return new YXmlElement(this.nodeName) + } + + /** + * Returns the XML serialization of this YXmlElement. + * The attributes are ordered by attribute-name, so you can easily use this + * method to compare YXmlElements + * + * @return {string} The string representation of this type. + * + * @public + */ + toString () { + const attrs = this.getAttributes(); + const stringBuilder = []; + const keys = []; + for (const key in attrs) { + keys.push(key); + } + keys.sort(); + const keysLen = keys.length; + for (let i = 0; i < keysLen; i++) { + const key = keys[i]; + stringBuilder.push(key + '="' + attrs[key] + '"'); + } + const nodeName = this.nodeName.toLocaleLowerCase(); + const attrsString = stringBuilder.length > 0 ? ' ' + stringBuilder.join(' ') : ''; + return `<${nodeName}${attrsString}>${super.toString()}` + } + + /** + * Removes an attribute from this YXmlElement. + * + * @param {String} attributeName The attribute name that is to be removed. + * + * @public + */ + removeAttribute (attributeName) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapDelete(transaction, this, attributeName); + }); + } else { + /** @type {Map} */ (this._prelimAttrs).delete(attributeName); + } + } + + /** + * Sets or updates an attribute. + * + * @param {String} attributeName The attribute name that is to be set. + * @param {String} attributeValue The attribute value that is to be set. + * + * @public + */ + setAttribute (attributeName, attributeValue) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapSet(transaction, this, attributeName, attributeValue); + }); + } else { + /** @type {Map} */ (this._prelimAttrs).set(attributeName, attributeValue); + } + } + + /** + * Returns an attribute value that belongs to the attribute name. + * + * @param {String} attributeName The attribute name that identifies the + * queried value. + * @return {String} The queried attribute value. + * + * @public + */ + getAttribute (attributeName) { + return /** @type {any} */ (typeMapGet(this, attributeName)) + } + + /** + * Returns all attribute name/value pairs in a JSON Object. + * + * @param {Snapshot} [snapshot] + * @return {Object} A JSON Object that describes the attributes. + * + * @public + */ + getAttributes (snapshot) { + return typeMapGetAll(this) + } + + /** + * Creates a Dom Element that mirrors this YXmlElement. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object} [hooks={}] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type. + * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks = {}, binding) { + const dom = _document.createElement(this.nodeName); + const attrs = this.getAttributes(); + for (const key in attrs) { + dom.setAttribute(key, attrs[key]); + } + typeListForEach(this, yxml => { + dom.appendChild(yxml.toDOM(_document, hooks, binding)); + }); + if (binding !== undefined) { + binding._createAssociation(dom, this); + } + return dom + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {AbstractUpdateEncoder} encoder The encoder to write data to. + */ + _write (encoder) { + encoder.writeTypeRef(YXmlElementRefID); + encoder.writeKey(this.nodeName); + } +} + +/** + * @param {AbstractUpdateDecoder} decoder + * @return {YXmlElement} + * + * @function + */ +const readYXmlElement = decoder => new YXmlElement(decoder.readKey()); + +/** + * An Event that describes changes on a YXml Element or Yxml Fragment + */ +class YXmlEvent extends YEvent { + /** + * @param {YXmlElement|YXmlFragment} target The target on which the event is created. + * @param {Set} subs The set of changed attributes. `null` is included if the + * child list changed. + * @param {Transaction} transaction The transaction instance with wich the + * change was created. + */ + constructor (target, subs, transaction) { + super(target, transaction); + /** + * Whether the children changed. + * @type {Boolean} + * @private + */ + this.childListChanged = false; + /** + * Set of all changed attributes. + * @type {Set} + */ + this.attributesChanged = new Set(); + subs.forEach((sub) => { + if (sub === null) { + this.childListChanged = true; + } else { + this.attributesChanged.add(sub); + } + }); + } +} + +/** + * You can manage binding to a custom type with YXmlHook. + * + * @extends {YMap} + */ +class YXmlHook extends YMap { + /** + * @param {string} hookName nodeName of the Dom Node. + */ + constructor (hookName) { + super(); + /** + * @type {string} + */ + this.hookName = hookName; + } + + /** + * Creates an Item with the same effect as this Item (without position effect) + */ + _copy () { + return new YXmlHook(this.hookName) + } + + /** + * Creates a Dom Element that mirrors this YXmlElement. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object.} [hooks] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type + * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks = {}, binding) { + const hook = hooks[this.hookName]; + let dom; + if (hook !== undefined) { + dom = hook.createDom(this); + } else { + dom = document.createElement(this.hookName); + } + dom.setAttribute('data-yjs-hook', this.hookName); + if (binding !== undefined) { + binding._createAssociation(dom, this); + } + return dom + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {AbstractUpdateEncoder} encoder The encoder to write data to. + */ + _write (encoder) { + encoder.writeTypeRef(YXmlHookRefID); + encoder.writeKey(this.hookName); + } +} + +/** + * @param {AbstractUpdateDecoder} decoder + * @return {YXmlHook} + * + * @private + * @function + */ +const readYXmlHook = decoder => + new YXmlHook(decoder.readKey()); + +/** + * Represents text in a Dom Element. In the future this type will also handle + * simple formatting information like bold and italic. + */ +class YXmlText extends YText { + _copy () { + return new YXmlText() + } + + /** + * Creates a Dom Element that mirrors this YXmlText. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object} [hooks] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type. + * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks, binding) { + const dom = _document.createTextNode(this.toString()); + if (binding !== undefined) { + binding._createAssociation(dom, this); + } + return dom + } + + toString () { + // @ts-ignore + return this.toDelta().map(delta => { + const nestedNodes = []; + for (const nodeName in delta.attributes) { + const attrs = []; + for (const key in delta.attributes[nodeName]) { + attrs.push({ key, value: delta.attributes[nodeName][key] }); + } + // sort attributes to get a unique order + attrs.sort((a, b) => a.key < b.key ? -1 : 1); + nestedNodes.push({ nodeName, attrs }); + } + // sort node order to get a unique order + nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1); + // now convert to dom string + let str = ''; + for (let i = 0; i < nestedNodes.length; i++) { + const node = nestedNodes[i]; + str += `<${node.nodeName}`; + for (let j = 0; j < node.attrs.length; j++) { + const attr = node.attrs[j]; + str += ` ${attr.key}="${attr.value}"`; + } + str += '>'; + } + str += delta.insert; + for (let i = nestedNodes.length - 1; i >= 0; i--) { + str += ``; + } + return str + }).join('') + } + + /** + * @return {string} + */ + toJSON () { + return this.toString() + } + + /** + * @param {AbstractUpdateEncoder} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YXmlTextRefID); + } +} + +/** + * @param {AbstractUpdateDecoder} decoder + * @return {YXmlText} + * + * @private + * @function + */ +const readYXmlText = decoder => new YXmlText(); + +class AbstractStruct { + /** + * @param {ID} id + * @param {number} length + */ + constructor (id, length) { + this.id = id; + this.length = length; + } + + /** + * @type {boolean} + */ + get deleted () { + throw error.methodUnimplemented() + } + + /** + * Merge this struct with the item to the right. + * This method is already assuming that `this.id.clock + this.length === this.id.clock`. + * Also this method does *not* remove right from StructStore! + * @param {AbstractStruct} right + * @return {boolean} wether this merged with right + */ + mergeWith (right) { + return false + } + + /** + * @param {AbstractUpdateEncoder} encoder The encoder to write data to. + * @param {number} offset + * @param {number} encodingRef + */ + write (encoder, offset, encodingRef) { + throw error.methodUnimplemented() + } + + /** + * @param {Transaction} transaction + * @param {number} offset + */ + integrate (transaction, offset) { + throw error.methodUnimplemented() + } +} + +const structGCRefNumber = 0; + +/** + * @private + */ +class GC extends AbstractStruct { + get deleted () { + return true + } + + delete () {} + + /** + * @param {GC} right + * @return {boolean} + */ + mergeWith (right) { + this.length += right.length; + return true + } + + /** + * @param {Transaction} transaction + * @param {number} offset + */ + integrate (transaction, offset) { + if (offset > 0) { + this.id.clock += offset; + this.length -= offset; + } + addStruct(transaction.doc.store, this); + } + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeInfo(structGCRefNumber); + encoder.writeLen(this.length - offset); + } + + /** + * @param {Transaction} transaction + * @param {StructStore} store + * @return {null | number} + */ + getMissing (transaction, store) { + return null + } +} + +class ContentBinary { + /** + * @param {Uint8Array} content + */ + constructor (content) { + this.content = content; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.content] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentBinary} + */ + copy () { + return new ContentBinary(this.content) + } + + /** + * @param {number} offset + * @return {ContentBinary} + */ + splice (offset) { + throw error.methodUnimplemented() + } + + /** + * @param {ContentBinary} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeBuf(this.content); + } + + /** + * @return {number} + */ + getRef () { + return 3 + } +} + +/** + * @param {AbstractUpdateDecoder} decoder + * @return {ContentBinary} + */ +const readContentBinary = decoder => new ContentBinary(decoder.readBuf()); + +class ContentDeleted { + /** + * @param {number} len + */ + constructor (len) { + this.len = len; + } + + /** + * @return {number} + */ + getLength () { + return this.len + } + + /** + * @return {Array} + */ + getContent () { + return [] + } + + /** + * @return {boolean} + */ + isCountable () { + return false + } + + /** + * @return {ContentDeleted} + */ + copy () { + return new ContentDeleted(this.len) + } + + /** + * @param {number} offset + * @return {ContentDeleted} + */ + splice (offset) { + const right = new ContentDeleted(this.len - offset); + this.len = offset; + return right + } + + /** + * @param {ContentDeleted} right + * @return {boolean} + */ + mergeWith (right) { + this.len += right.len; + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len); + item.markDeleted(); + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeLen(this.len - offset); + } + + /** + * @return {number} + */ + getRef () { + return 1 + } +} + +/** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentDeleted} + */ +const readContentDeleted = decoder => new ContentDeleted(decoder.readLen()); + +/** + * @private + */ +class ContentDoc { + /** + * @param {Doc} doc + */ + constructor (doc) { + if (doc._item) { + console.error('This document was already integrated as a sub-document. You should create a second instance instead with the same guid.'); + } + /** + * @type {Doc} + */ + this.doc = doc; + /** + * @type {any} + */ + const opts = {}; + this.opts = opts; + if (!doc.gc) { + opts.gc = false; + } + if (doc.autoLoad) { + opts.autoLoad = true; + } + if (doc.meta !== null) { + opts.meta = doc.meta; + } + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.doc] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentDoc} + */ + copy () { + return new ContentDoc(this.doc) + } + + /** + * @param {number} offset + * @return {ContentDoc} + */ + splice (offset) { + throw error.methodUnimplemented() + } + + /** + * @param {ContentDoc} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + // this needs to be reflected in doc.destroy as well + this.doc._item = item; + transaction.subdocsAdded.add(this.doc); + if (this.doc.shouldLoad) { + transaction.subdocsLoaded.add(this.doc); + } + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) { + if (transaction.subdocsAdded.has(this.doc)) { + transaction.subdocsAdded.delete(this.doc); + } else { + transaction.subdocsRemoved.add(this.doc); + } + } + + /** + * @param {StructStore} store + */ + gc (store) { } + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeString(this.doc.guid); + encoder.writeAny(this.opts); + } + + /** + * @return {number} + */ + getRef () { + return 9 + } +} + +/** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentDoc} + */ +const readContentDoc = decoder => new ContentDoc(new Doc({ guid: decoder.readString(), ...decoder.readAny() })); + +/** + * @private + */ +class ContentEmbed { + /** + * @param {Object} embed + */ + constructor (embed) { + this.embed = embed; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.embed] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentEmbed} + */ + copy () { + return new ContentEmbed(this.embed) + } + + /** + * @param {number} offset + * @return {ContentEmbed} + */ + splice (offset) { + throw error.methodUnimplemented() + } + + /** + * @param {ContentEmbed} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeJSON(this.embed); + } + + /** + * @return {number} + */ + getRef () { + return 5 + } +} + +/** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentEmbed} + */ +const readContentEmbed = decoder => new ContentEmbed(decoder.readJSON()); + +/** + * @private + */ +class ContentFormat { + /** + * @param {string} key + * @param {Object} value + */ + constructor (key, value) { + this.key = key; + this.value = value; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [] + } + + /** + * @return {boolean} + */ + isCountable () { + return false + } + + /** + * @return {ContentFormat} + */ + copy () { + return new ContentFormat(this.key, this.value) + } + + /** + * @param {number} offset + * @return {ContentFormat} + */ + splice (offset) { + throw error.methodUnimplemented() + } + + /** + * @param {ContentFormat} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + // @todo searchmarker are currently unsupported for rich text documents + /** @type {AbstractType} */ (item.parent)._searchMarker = null; + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeKey(this.key); + encoder.writeJSON(this.value); + } + + /** + * @return {number} + */ + getRef () { + return 6 + } +} + +/** + * @param {AbstractUpdateDecoder} decoder + * @return {ContentFormat} + */ +const readContentFormat = decoder => new ContentFormat(decoder.readString(), decoder.readJSON()); + +/** + * @private + */ +class ContentJSON { + /** + * @param {Array} arr + */ + constructor (arr) { + /** + * @type {Array} + */ + this.arr = arr; + } + + /** + * @return {number} + */ + getLength () { + return this.arr.length + } + + /** + * @return {Array} + */ + getContent () { + return this.arr + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentJSON} + */ + copy () { + return new ContentJSON(this.arr) + } + + /** + * @param {number} offset + * @return {ContentJSON} + */ + splice (offset) { + const right = new ContentJSON(this.arr.slice(offset)); + this.arr = this.arr.slice(0, offset); + return right + } + + /** + * @param {ContentJSON} right + * @return {boolean} + */ + mergeWith (right) { + this.arr = this.arr.concat(right.arr); + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + const len = this.arr.length; + encoder.writeLen(len - offset); + for (let i = offset; i < len; i++) { + const c = this.arr[i]; + encoder.writeString(c === undefined ? 'undefined' : JSON.stringify(c)); + } + } + + /** + * @return {number} + */ + getRef () { + return 2 + } +} + +/** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentJSON} + */ +const readContentJSON = decoder => { + const len = decoder.readLen(); + const cs = []; + for (let i = 0; i < len; i++) { + const c = decoder.readString(); + if (c === 'undefined') { + cs.push(undefined); + } else { + cs.push(JSON.parse(c)); + } + } + return new ContentJSON(cs) +}; + +class ContentAny { + /** + * @param {Array} arr + */ + constructor (arr) { + /** + * @type {Array} + */ + this.arr = arr; + } + + /** + * @return {number} + */ + getLength () { + return this.arr.length + } + + /** + * @return {Array} + */ + getContent () { + return this.arr + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentAny} + */ + copy () { + return new ContentAny(this.arr) + } + + /** + * @param {number} offset + * @return {ContentAny} + */ + splice (offset) { + const right = new ContentAny(this.arr.slice(offset)); + this.arr = this.arr.slice(0, offset); + return right + } + + /** + * @param {ContentAny} right + * @return {boolean} + */ + mergeWith (right) { + this.arr = this.arr.concat(right.arr); + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + const len = this.arr.length; + encoder.writeLen(len - offset); + for (let i = offset; i < len; i++) { + const c = this.arr[i]; + encoder.writeAny(c); + } + } + + /** + * @return {number} + */ + getRef () { + return 8 + } +} + +/** + * @param {AbstractUpdateDecoder} decoder + * @return {ContentAny} + */ +const readContentAny = decoder => { + const len = decoder.readLen(); + const cs = []; + for (let i = 0; i < len; i++) { + cs.push(decoder.readAny()); + } + return new ContentAny(cs) +}; + +/** + * @private + */ +class ContentString { + /** + * @param {string} str + */ + constructor (str) { + /** + * @type {string} + */ + this.str = str; + } + + /** + * @return {number} + */ + getLength () { + return this.str.length + } + + /** + * @return {Array} + */ + getContent () { + return this.str.split('') + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentString} + */ + copy () { + return new ContentString(this.str) + } + + /** + * @param {number} offset + * @return {ContentString} + */ + splice (offset) { + const right = new ContentString(this.str.slice(offset)); + this.str = this.str.slice(0, offset); + + // Prevent encoding invalid documents because of splitting of surrogate pairs: https://github.com/yjs/yjs/issues/248 + const firstCharCode = this.str.charCodeAt(offset - 1); + if (firstCharCode >= 0xD800 && firstCharCode <= 0xDBFF) { + // Last character of the left split is the start of a surrogate utf16/ucs2 pair. + // We don't support splitting of surrogate pairs because this may lead to invalid documents. + // Replace the invalid character with a unicode replacement character (� / U+FFFD) + this.str = this.str.slice(0, offset - 1) + '�'; + // replace right as well + right.str = '�' + right.str.slice(1); + } + return right + } + + /** + * @param {ContentString} right + * @return {boolean} + */ + mergeWith (right) { + this.str += right.str; + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeString(offset === 0 ? this.str : this.str.slice(offset)); + } + + /** + * @return {number} + */ + getRef () { + return 4 + } +} + +/** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentString} + */ +const readContentString = decoder => new ContentString(decoder.readString()); + +/** + * @type {Array>} + * @private + */ +const typeRefs = [ + readYArray, + readYMap, + readYText, + readYXmlElement, + readYXmlFragment, + readYXmlHook, + readYXmlText +]; + +const YArrayRefID = 0; +const YMapRefID = 1; +const YTextRefID = 2; +const YXmlElementRefID = 3; +const YXmlFragmentRefID = 4; +const YXmlHookRefID = 5; +const YXmlTextRefID = 6; + +/** + * @private + */ +class ContentType { + /** + * @param {AbstractType} type + */ + constructor (type) { + /** + * @type {AbstractType} + */ + this.type = type; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.type] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentType} + */ + copy () { + return new ContentType(this.type._copy()) + } + + /** + * @param {number} offset + * @return {ContentType} + */ + splice (offset) { + throw error.methodUnimplemented() + } + + /** + * @param {ContentType} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + this.type._integrate(transaction.doc, item); + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) { + let item = this.type._start; + while (item !== null) { + if (!item.deleted) { + item.delete(transaction); + } else { + // Whis will be gc'd later and we want to merge it if possible + // We try to merge all deleted items after each transaction, + // but we have no knowledge about that this needs to be merged + // since it is not in transaction.ds. Hence we add it to transaction._mergeStructs + transaction._mergeStructs.push(item); + } + item = item.right; + } + this.type._map.forEach(item => { + if (!item.deleted) { + item.delete(transaction); + } else { + // same as above + transaction._mergeStructs.push(item); + } + }); + transaction.changed.delete(this.type); + } + + /** + * @param {StructStore} store + */ + gc (store) { + let item = this.type._start; + while (item !== null) { + item.gc(store, true); + item = item.right; + } + this.type._start = null; + this.type._map.forEach(/** @param {Item | null} item */ (item) => { + while (item !== null) { + item.gc(store, true); + item = item.left; + } + }); + this.type._map = new Map(); + } + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + this.type._write(encoder); + } + + /** + * @return {number} + */ + getRef () { + return 7 + } +} + +/** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentType} + */ +const readContentType = decoder => new ContentType(typeRefs[decoder.readTypeRef()](decoder)); + +/** + * @todo This should return several items + * + * @param {StructStore} store + * @param {ID} id + * @return {{item:Item, diff:number}} + */ +const followRedone = (store, id) => { + /** + * @type {ID|null} + */ + let nextID = id; + let diff = 0; + let item; + do { + if (diff > 0) { + nextID = createID(nextID.client, nextID.clock + diff); + } + item = getItem(store, nextID); + diff = nextID.clock - item.id.clock; + nextID = item.redone; + } while (nextID !== null && item instanceof Item) + return { + item, diff + } +}; + +/** + * Make sure that neither item nor any of its parents is ever deleted. + * + * This property does not persist when storing it into a database or when + * sending it to other peers + * + * @param {Item|null} item + * @param {boolean} keep + */ +const keepItem = (item, keep) => { + while (item !== null && item.keep !== keep) { + item.keep = keep; + item = /** @type {AbstractType} */ (item.parent)._item; + } +}; + +/** + * Split leftItem into two items + * @param {Transaction} transaction + * @param {Item} leftItem + * @param {number} diff + * @return {Item} + * + * @function + * @private + */ +const splitItem = (transaction, leftItem, diff) => { + // create rightItem + const { client, clock } = leftItem.id; + const rightItem = new Item( + createID(client, clock + diff), + leftItem, + createID(client, clock + diff - 1), + leftItem.right, + leftItem.rightOrigin, + leftItem.parent, + leftItem.parentSub, + leftItem.content.splice(diff) + ); + if (leftItem.deleted) { + rightItem.markDeleted(); + } + if (leftItem.keep) { + rightItem.keep = true; + } + if (leftItem.redone !== null) { + rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff); + } + // update left (do not set leftItem.rightOrigin as it will lead to problems when syncing) + leftItem.right = rightItem; + // update right + if (rightItem.right !== null) { + rightItem.right.left = rightItem; + } + // right is more specific. + transaction._mergeStructs.push(rightItem); + // update parent._map + if (rightItem.parentSub !== null && rightItem.right === null) { + /** @type {AbstractType} */ (rightItem.parent)._map.set(rightItem.parentSub, rightItem); + } + leftItem.length = diff; + return rightItem +}; + +/** + * Redoes the effect of this operation. + * + * @param {Transaction} transaction The Yjs instance. + * @param {Item} item + * @param {Set} redoitems + * + * @return {Item|null} + * + * @private + */ +const redoItem = (transaction, item, redoitems) => { + const doc = transaction.doc; + const store = doc.store; + const ownClientID = doc.clientID; + const redone = item.redone; + if (redone !== null) { + return getItemCleanStart(transaction, redone) + } + let parentItem = /** @type {AbstractType} */ (item.parent)._item; + /** + * @type {Item|null} + */ + let left; + /** + * @type {Item|null} + */ + let right; + if (item.parentSub === null) { + // Is an array item. Insert at the old position + left = item.left; + right = item; + } else { + // Is a map item. Insert as current value + left = item; + while (left.right !== null) { + left = left.right; + if (left.id.client !== ownClientID) { + // It is not possible to redo this item because it conflicts with a + // change from another client + return null + } + } + if (left.right !== null) { + left = /** @type {Item} */ (/** @type {AbstractType} */ (item.parent)._map.get(item.parentSub)); + } + right = null; + } + // make sure that parent is redone + if (parentItem !== null && parentItem.deleted === true && parentItem.redone === null) { + // try to undo parent if it will be undone anyway + if (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems) === null) { + return null + } + } + if (parentItem !== null && parentItem.redone !== null) { + while (parentItem.redone !== null) { + parentItem = getItemCleanStart(transaction, parentItem.redone); + } + // find next cloned_redo items + while (left !== null) { + /** + * @type {Item|null} + */ + let leftTrace = left; + // trace redone until parent matches + while (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item !== parentItem) { + leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone); + } + if (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item === parentItem) { + left = leftTrace; + break + } + left = left.left; + } + while (right !== null) { + /** + * @type {Item|null} + */ + let rightTrace = right; + // trace redone until parent matches + while (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item !== parentItem) { + rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone); + } + if (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item === parentItem) { + right = rightTrace; + break + } + right = right.right; + } + } + const nextClock = getState(store, ownClientID); + const nextId = createID(ownClientID, nextClock); + const redoneItem = new Item( + nextId, + left, left && left.lastId, + right, right && right.id, + parentItem === null ? item.parent : /** @type {ContentType} */ (parentItem.content).type, + item.parentSub, + item.content.copy() + ); + item.redone = nextId; + keepItem(redoneItem, true); + redoneItem.integrate(transaction, 0); + return redoneItem +}; + +/** + * Abstract class that represents any content. + */ +class Item extends AbstractStruct { + /** + * @param {ID} id + * @param {Item | null} left + * @param {ID | null} origin + * @param {Item | null} right + * @param {ID | null} rightOrigin + * @param {AbstractType|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it. + * @param {string | null} parentSub + * @param {AbstractContent} content + */ + constructor (id, left, origin, right, rightOrigin, parent, parentSub, content) { + super(id, content.getLength()); + /** + * The item that was originally to the left of this item. + * @type {ID | null} + */ + this.origin = origin; + /** + * The item that is currently to the left of this item. + * @type {Item | null} + */ + this.left = left; + /** + * The item that is currently to the right of this item. + * @type {Item | null} + */ + this.right = right; + /** + * The item that was originally to the right of this item. + * @type {ID | null} + */ + this.rightOrigin = rightOrigin; + /** + * @type {AbstractType|ID|null} + */ + this.parent = parent; + /** + * If the parent refers to this item with some kind of key (e.g. YMap, the + * key is specified here. The key is then used to refer to the list in which + * to insert this item. If `parentSub = null` type._start is the list in + * which to insert to. Otherwise it is `parent._map`. + * @type {String | null} + */ + this.parentSub = parentSub; + /** + * If this type's effect is reundone this type refers to the type that undid + * this operation. + * @type {ID | null} + */ + this.redone = null; + /** + * @type {AbstractContent} + */ + this.content = content; + /** + * bit1: keep + * bit2: countable + * bit3: deleted + * bit4: mark - mark node as fast-search-marker + * @type {number} byte + */ + this.info = this.content.isCountable() ? binary.BIT2 : 0; + } + + /** + * This is used to mark the item as an indexed fast-search marker + * + * @type {boolean} + */ + set marker (isMarked) { + if (((this.info & binary.BIT4) > 0) !== isMarked) { + this.info ^= binary.BIT4; + } + } + + get marker () { + return (this.info & binary.BIT4) > 0 + } + + /** + * If true, do not garbage collect this Item. + */ + get keep () { + return (this.info & binary.BIT1) > 0 + } + + set keep (doKeep) { + if (this.keep !== doKeep) { + this.info ^= binary.BIT1; + } + } + + get countable () { + return (this.info & binary.BIT2) > 0 + } + + /** + * Whether this item was deleted or not. + * @type {Boolean} + */ + get deleted () { + return (this.info & binary.BIT3) > 0 + } + + set deleted (doDelete) { + if (this.deleted !== doDelete) { + this.info ^= binary.BIT3; + } + } + + markDeleted () { + this.info |= binary.BIT3; + } + + /** + * Return the creator clientID of the missing op or define missing items and return null. + * + * @param {Transaction} transaction + * @param {StructStore} store + * @return {null | number} + */ + getMissing (transaction, store) { + if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) { + return this.origin.client + } + if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) { + return this.rightOrigin.client + } + if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) { + return this.parent.client + } + + // We have all missing ids, now find the items + + if (this.origin) { + this.left = getItemCleanEnd(transaction, store, this.origin); + this.origin = this.left.lastId; + } + if (this.rightOrigin) { + this.right = getItemCleanStart(transaction, this.rightOrigin); + this.rightOrigin = this.right.id; + } + if ((this.left && this.left.constructor === GC) || (this.right && this.right.constructor === GC)) { + this.parent = null; + } + // only set parent if this shouldn't be garbage collected + if (!this.parent) { + if (this.left && this.left.constructor === Item) { + this.parent = this.left.parent; + this.parentSub = this.left.parentSub; + } + if (this.right && this.right.constructor === Item) { + this.parent = this.right.parent; + this.parentSub = this.right.parentSub; + } + } else if (this.parent.constructor === ID) { + const parentItem = getItem(store, this.parent); + if (parentItem.constructor === GC) { + this.parent = null; + } else { + this.parent = /** @type {ContentType} */ (parentItem.content).type; + } + } + return null + } + + /** + * @param {Transaction} transaction + * @param {number} offset + */ + integrate (transaction, offset) { + if (offset > 0) { + this.id.clock += offset; + this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1)); + this.origin = this.left.lastId; + this.content = this.content.splice(offset); + this.length -= offset; + } + + if (this.parent) { + if ((!this.left && (!this.right || this.right.left !== null)) || (this.left && this.left.right !== this.right)) { + /** + * @type {Item|null} + */ + let left = this.left; + + /** + * @type {Item|null} + */ + let o; + // set o to the first conflicting item + if (left !== null) { + o = left.right; + } else if (this.parentSub !== null) { + o = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null; + while (o !== null && o.left !== null) { + o = o.left; + } + } else { + o = /** @type {AbstractType} */ (this.parent)._start; + } + // TODO: use something like DeleteSet here (a tree implementation would be best) + // @todo use global set definitions + /** + * @type {Set} + */ + const conflictingItems = new Set(); + /** + * @type {Set} + */ + const itemsBeforeOrigin = new Set(); + // Let c in conflictingItems, b in itemsBeforeOrigin + // ***{origin}bbbb{this}{c,b}{c,b}{o}*** + // Note that conflictingItems is a subset of itemsBeforeOrigin + while (o !== null && o !== this.right) { + itemsBeforeOrigin.add(o); + conflictingItems.add(o); + if (compareIDs(this.origin, o.origin)) { + // case 1 + if (o.id.client < this.id.client) { + left = o; + conflictingItems.clear(); + } else if (compareIDs(this.rightOrigin, o.rightOrigin)) { + // this and o are conflicting and point to the same integration points. The id decides which item comes first. + // Since this is to the left of o, we can break here + break + } // else, o might be integrated before an item that this conflicts with. If so, we will find it in the next iterations + } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) { // use getItem instead of getItemCleanEnd because we don't want / need to split items. + // case 2 + if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) { + left = o; + conflictingItems.clear(); + } + } else { + break + } + o = o.right; + } + this.left = left; + } + // reconnect left/right + update parent map/start if necessary + if (this.left !== null) { + const right = this.left.right; + this.right = right; + this.left.right = this; + } else { + let r; + if (this.parentSub !== null) { + r = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null; + while (r !== null && r.left !== null) { + r = r.left; + } + } else { + r = /** @type {AbstractType} */ (this.parent)._start + ;/** @type {AbstractType} */ (this.parent)._start = this; + } + this.right = r; + } + if (this.right !== null) { + this.right.left = this; + } else if (this.parentSub !== null) { + // set as current parent value if right === null and this is parentSub + /** @type {AbstractType} */ (this.parent)._map.set(this.parentSub, this); + if (this.left !== null) { + // this is the current attribute value of parent. delete right + this.left.delete(transaction); + } + } + // adjust length of parent + if (this.parentSub === null && this.countable && !this.deleted) { + /** @type {AbstractType} */ (this.parent)._length += this.length; + } + addStruct(transaction.doc.store, this); + this.content.integrate(transaction, this); + // add parent to transaction.changed + addChangedTypeToTransaction(transaction, /** @type {AbstractType} */ (this.parent), this.parentSub); + if ((/** @type {AbstractType} */ (this.parent)._item !== null && /** @type {AbstractType} */ (this.parent)._item.deleted) || (this.parentSub !== null && this.right !== null)) { + // delete if parent is deleted or if this is not the current attribute value of parent + this.delete(transaction); + } + } else { + // parent is not defined. Integrate GC struct instead + new GC(this.id, this.length).integrate(transaction, 0); + } + } + + /** + * Returns the next non-deleted item + */ + get next () { + let n = this.right; + while (n !== null && n.deleted) { + n = n.right; + } + return n + } + + /** + * Returns the previous non-deleted item + */ + get prev () { + let n = this.left; + while (n !== null && n.deleted) { + n = n.left; + } + return n + } + + /** + * Computes the last content address of this Item. + */ + get lastId () { + // allocating ids is pretty costly because of the amount of ids created, so we try to reuse whenever possible + return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1) + } + + /** + * Try to merge two items + * + * @param {Item} right + * @return {boolean} + */ + mergeWith (right) { + if ( + compareIDs(right.origin, this.lastId) && + this.right === right && + compareIDs(this.rightOrigin, right.rightOrigin) && + this.id.client === right.id.client && + this.id.clock + this.length === right.id.clock && + this.deleted === right.deleted && + this.redone === null && + right.redone === null && + this.content.constructor === right.content.constructor && + this.content.mergeWith(right.content) + ) { + if (right.keep) { + this.keep = true; + } + this.right = right.right; + if (this.right !== null) { + this.right.left = this; + } + this.length += right.length; + return true + } + return false + } + + /** + * Mark this Item as deleted. + * + * @param {Transaction} transaction + */ + delete (transaction) { + if (!this.deleted) { + const parent = /** @type {AbstractType} */ (this.parent); + // adjust the length of parent + if (this.countable && this.parentSub === null) { + parent._length -= this.length; + } + this.markDeleted(); + addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length); + addChangedTypeToTransaction(transaction, parent, this.parentSub); + this.content.delete(transaction); + } + } + + /** + * @param {StructStore} store + * @param {boolean} parentGCd + */ + gc (store, parentGCd) { + if (!this.deleted) { + throw error.unexpectedCase() + } + this.content.gc(store); + if (parentGCd) { + replaceStruct(store, this, new GC(this.id, this.length)); + } else { + this.content = new ContentDeleted(this.length); + } + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {AbstractUpdateEncoder} encoder The encoder to write data to. + * @param {number} offset + */ + write (encoder, offset) { + const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin; + const rightOrigin = this.rightOrigin; + const parentSub = this.parentSub; + const info = (this.content.getRef() & binary.BITS5) | + (origin === null ? 0 : binary.BIT8) | // origin is defined + (rightOrigin === null ? 0 : binary.BIT7) | // right origin is defined + (parentSub === null ? 0 : binary.BIT6); // parentSub is non-null + encoder.writeInfo(info); + if (origin !== null) { + encoder.writeLeftID(origin); + } + if (rightOrigin !== null) { + encoder.writeRightID(rightOrigin); + } + if (origin === null && rightOrigin === null) { + const parent = /** @type {AbstractType} */ (this.parent); + const parentItem = parent._item; + if (parentItem === null) { + // parent type on y._map + // find the correct key + const ykey = findRootTypeKey(parent); + encoder.writeParentInfo(true); // write parentYKey + encoder.writeString(ykey); + } else { + encoder.writeParentInfo(false); // write parent id + encoder.writeLeftID(parentItem.id); + } + if (parentSub !== null) { + encoder.writeString(parentSub); + } + } + this.content.write(encoder, offset); + } +} + +/** + * @param {AbstractUpdateDecoder} decoder + * @param {number} info + */ +const readItemContent = (decoder, info) => contentRefs[info & binary.BITS5](decoder); + +/** + * A lookup map for reading Item content. + * + * @type {Array} + */ +const contentRefs = [ + () => { throw error.unexpectedCase() }, // GC is not ItemContent + readContentDeleted, // 1 + readContentJSON, // 2 + readContentBinary, // 3 + readContentString, // 4 + readContentEmbed, // 5 + readContentFormat, // 6 + readContentType, // 7 + readContentAny, // 8 + readContentDoc // 9 +]; + +/** + * Do not implement this class! + */ +class AbstractContent { + /** + * @return {number} + */ + getLength () { + throw error.methodUnimplemented() + } + + /** + * @return {Array} + */ + getContent () { + throw error.methodUnimplemented() + } + + /** + * Should return false if this Item is some kind of meta information + * (e.g. format information). + * + * * Whether this Item should be addressable via `yarray.get(i)` + * * Whether this Item should be counted when computing yarray.length + * + * @return {boolean} + */ + isCountable () { + throw error.methodUnimplemented() + } + + /** + * @return {AbstractContent} + */ + copy () { + throw error.methodUnimplemented() + } + + /** + * @param {number} offset + * @return {AbstractContent} + */ + splice (offset) { + throw error.methodUnimplemented() + } + + /** + * @param {AbstractContent} right + * @return {boolean} + */ + mergeWith (right) { + throw error.methodUnimplemented() + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + throw error.methodUnimplemented() + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) { + throw error.methodUnimplemented() + } + + /** + * @param {StructStore} store + */ + gc (store) { + throw error.methodUnimplemented() + } + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + throw error.methodUnimplemented() + } + + /** + * @return {number} + */ + getRef () { + throw error.methodUnimplemented() + } +} + +var Y = /*#__PURE__*/Object.freeze({ + __proto__: null, + AbstractConnector: AbstractConnector, + DeleteItem: DeleteItem, + DeleteSet: DeleteSet, + iterateDeletedStructs: iterateDeletedStructs, + findIndexDS: findIndexDS, + isDeleted: isDeleted, + sortAndMergeDeleteSet: sortAndMergeDeleteSet, + mergeDeleteSets: mergeDeleteSets, + addToDeleteSet: addToDeleteSet, + createDeleteSet: createDeleteSet, + createDeleteSetFromStructStore: createDeleteSetFromStructStore, + writeDeleteSet: writeDeleteSet, + readDeleteSet: readDeleteSet, + readAndApplyDeleteSet: readAndApplyDeleteSet, + generateNewClientId: generateNewClientId, + Doc: Doc, + AbstractDSDecoder: AbstractDSDecoder, + AbstractUpdateDecoder: AbstractUpdateDecoder, + DSDecoderV1: DSDecoderV1, + UpdateDecoderV1: UpdateDecoderV1, + DSDecoderV2: DSDecoderV2, + UpdateDecoderV2: UpdateDecoderV2, + AbstractDSEncoder: AbstractDSEncoder, + AbstractUpdateEncoder: AbstractUpdateEncoder, + DSEncoderV1: DSEncoderV1, + UpdateEncoderV1: UpdateEncoderV1, + DSEncoderV2: DSEncoderV2, + UpdateEncoderV2: UpdateEncoderV2, + get DefaultDSEncoder () { return DefaultDSEncoder; }, + get DefaultDSDecoder () { return DefaultDSDecoder; }, + get DefaultUpdateEncoder () { return DefaultUpdateEncoder; }, + get DefaultUpdateDecoder () { return DefaultUpdateDecoder; }, + useV1Encoding: useV1Encoding, + useV2Encoding: useV2Encoding, + writeClientsStructs: writeClientsStructs, + readClientsStructRefs: readClientsStructRefs, + tryResumePendingDeleteReaders: tryResumePendingDeleteReaders, + writeStructsFromTransaction: writeStructsFromTransaction, + readStructs: readStructs, + readUpdateV2: readUpdateV2, + readUpdate: readUpdate, + applyUpdateV2: applyUpdateV2, + applyUpdate: applyUpdate, + writeStateAsUpdate: writeStateAsUpdate, + encodeStateAsUpdateV2: encodeStateAsUpdateV2, + encodeStateAsUpdate: encodeStateAsUpdate, + readStateVector: readStateVector, + decodeStateVectorV2: decodeStateVectorV2, + decodeStateVector: decodeStateVector, + writeStateVector: writeStateVector, + writeDocumentStateVector: writeDocumentStateVector, + encodeStateVectorV2: encodeStateVectorV2, + encodeStateVector: encodeStateVector, + EventHandler: EventHandler, + createEventHandler: createEventHandler, + addEventHandlerListener: addEventHandlerListener, + removeEventHandlerListener: removeEventHandlerListener, + removeAllEventHandlerListeners: removeAllEventHandlerListeners, + callEventHandlerListeners: callEventHandlerListeners, + ID: ID, + compareIDs: compareIDs, + createID: createID, + writeID: writeID, + readID: readID, + findRootTypeKey: findRootTypeKey, + isParentOf: isParentOf, + logType: logType, + PermanentUserData: PermanentUserData, + RelativePosition: RelativePosition, + createRelativePositionFromJSON: createRelativePositionFromJSON, + AbsolutePosition: AbsolutePosition, + createAbsolutePosition: createAbsolutePosition, + createRelativePosition: createRelativePosition, + createRelativePositionFromTypeIndex: createRelativePositionFromTypeIndex, + writeRelativePosition: writeRelativePosition, + encodeRelativePosition: encodeRelativePosition, + readRelativePosition: readRelativePosition, + decodeRelativePosition: decodeRelativePosition, + createAbsolutePositionFromRelativePosition: createAbsolutePositionFromRelativePosition, + compareRelativePositions: compareRelativePositions, + Snapshot: Snapshot, + equalSnapshots: equalSnapshots, + encodeSnapshotV2: encodeSnapshotV2, + encodeSnapshot: encodeSnapshot, + decodeSnapshotV2: decodeSnapshotV2, + decodeSnapshot: decodeSnapshot, + createSnapshot: createSnapshot, + emptySnapshot: emptySnapshot, + snapshot: snapshot, + isVisible: isVisible, + splitSnapshotAffectedStructs: splitSnapshotAffectedStructs, + createDocFromSnapshot: createDocFromSnapshot, + StructStore: StructStore, + getStateVector: getStateVector, + getState: getState, + integretyCheck: integretyCheck, + addStruct: addStruct, + findIndexSS: findIndexSS, + find: find, + getItem: getItem, + findIndexCleanStart: findIndexCleanStart, + getItemCleanStart: getItemCleanStart, + getItemCleanEnd: getItemCleanEnd, + replaceStruct: replaceStruct, + iterateStructs: iterateStructs, + Transaction: Transaction, + writeUpdateMessageFromTransaction: writeUpdateMessageFromTransaction, + nextID: nextID, + addChangedTypeToTransaction: addChangedTypeToTransaction, + tryGc: tryGc, + transact: transact, + UndoManager: UndoManager, + YEvent: YEvent, + ArraySearchMarker: ArraySearchMarker, + findMarker: findMarker, + updateMarkerChanges: updateMarkerChanges, + getTypeChildren: getTypeChildren, + callTypeObservers: callTypeObservers, + AbstractType: AbstractType, + typeListToArray: typeListToArray, + typeListToArraySnapshot: typeListToArraySnapshot, + typeListForEach: typeListForEach, + typeListMap: typeListMap, + typeListCreateIterator: typeListCreateIterator, + typeListForEachSnapshot: typeListForEachSnapshot, + typeListGet: typeListGet, + typeListInsertGenericsAfter: typeListInsertGenericsAfter, + typeListInsertGenerics: typeListInsertGenerics, + typeListDelete: typeListDelete, + typeMapDelete: typeMapDelete, + typeMapSet: typeMapSet, + typeMapGet: typeMapGet, + typeMapGetAll: typeMapGetAll, + typeMapHas: typeMapHas, + typeMapGetSnapshot: typeMapGetSnapshot, + createMapIterator: createMapIterator, + YArrayEvent: YArrayEvent, + YArray: YArray, + readYArray: readYArray, + YMapEvent: YMapEvent, + YMap: YMap, + readYMap: readYMap, + ItemTextListPosition: ItemTextListPosition, + cleanupYTextFormatting: cleanupYTextFormatting, + YTextEvent: YTextEvent, + YText: YText, + readYText: readYText, + YXmlTreeWalker: YXmlTreeWalker, + YXmlFragment: YXmlFragment, + readYXmlFragment: readYXmlFragment, + YXmlElement: YXmlElement, + readYXmlElement: readYXmlElement, + YXmlEvent: YXmlEvent, + YXmlHook: YXmlHook, + readYXmlHook: readYXmlHook, + YXmlText: YXmlText, + readYXmlText: readYXmlText, + AbstractStruct: AbstractStruct, + structGCRefNumber: structGCRefNumber, + GC: GC, + ContentBinary: ContentBinary, + readContentBinary: readContentBinary, + ContentDeleted: ContentDeleted, + readContentDeleted: readContentDeleted, + ContentDoc: ContentDoc, + readContentDoc: readContentDoc, + ContentEmbed: ContentEmbed, + readContentEmbed: readContentEmbed, + ContentFormat: ContentFormat, + readContentFormat: readContentFormat, + ContentJSON: ContentJSON, + readContentJSON: readContentJSON, + ContentAny: ContentAny, + readContentAny: readContentAny, + ContentString: ContentString, + readContentString: readContentString, + typeRefs: typeRefs, + YArrayRefID: YArrayRefID, + YMapRefID: YMapRefID, + YTextRefID: YTextRefID, + YXmlElementRefID: YXmlElementRefID, + YXmlFragmentRefID: YXmlFragmentRefID, + YXmlHookRefID: YXmlHookRefID, + YXmlTextRefID: YXmlTextRefID, + ContentType: ContentType, + readContentType: readContentType, + followRedone: followRedone, + keepItem: keepItem, + splitItem: splitItem, + redoItem: redoItem, + Item: Item, + readItemContent: readItemContent, + contentRefs: contentRefs, + AbstractContent: AbstractContent +}); + +/** + * @module sync-protocol + */ + +/** + * @typedef {Map} StateMap + */ + +/** + * Core Yjs defines three message types: + * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2. + * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the the client is assured that + * it received all information from the remote client. + * + * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection + * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both + * SyncStep2 and SyncDone, it is assured that it is synced to the remote client. + * + * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1. + * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies + * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the + * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can + * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them. + * Therefore it is necesarry that the client initiates the sync. + * + * Construction of a message: + * [messageType : varUint, message definition..] + * + * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol! + * + * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer) + */ + +const messageYjsSyncStep1 = 0; +const messageYjsSyncStep2 = 1; +const messageYjsUpdate = 2; + +/** + * Create a sync step 1 message based on the state of the current shared document. + * + * @param {encoding.Encoder} encoder + * @param {Y.Doc} doc + */ +const writeSyncStep1 = (encoder, doc) => { + encoding.writeVarUint(encoder, messageYjsSyncStep1); + const sv = encodeStateVector(doc); + encoding.writeVarUint8Array(encoder, sv); +}; + +/** + * @param {encoding.Encoder} encoder + * @param {Y.Doc} doc + * @param {Uint8Array} [encodedStateVector] + */ +const writeSyncStep2 = (encoder, doc, encodedStateVector) => { + encoding.writeVarUint(encoder, messageYjsSyncStep2); + encoding.writeVarUint8Array(encoder, encodeStateAsUpdate(doc, encodedStateVector)); +}; + +/** + * Read SyncStep1 message and reply with SyncStep2. + * + * @param {decoding.Decoder} decoder The reply to the received message + * @param {encoding.Encoder} encoder The received message + * @param {Y.Doc} doc + */ +const readSyncStep1 = (decoder, encoder, doc) => + writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder)); + +/** + * Read and apply Structs and then DeleteStore to a y instance. + * + * @param {decoding.Decoder} decoder + * @param {Y.Doc} doc + * @param {any} transactionOrigin + */ +const readSyncStep2 = (decoder, doc, transactionOrigin) => { + applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin); +}; + +/** + * @param {encoding.Encoder} encoder + * @param {Uint8Array} update + */ +const writeUpdate = (encoder, update) => { + encoding.writeVarUint(encoder, messageYjsUpdate); + encoding.writeVarUint8Array(encoder, update); +}; + +/** + * Read and apply Structs and then DeleteStore to a y instance. + * + * @param {decoding.Decoder} decoder + * @param {Y.Doc} doc + * @param {any} transactionOrigin + */ +const readUpdate$1 = readSyncStep2; + +/** + * @param {decoding.Decoder} decoder A message received from another client + * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty. + * @param {Y.Doc} doc + * @param {any} transactionOrigin + */ +const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => { + const messageType = decoding.readVarUint(decoder); + switch (messageType) { + case messageYjsSyncStep1: + readSyncStep1(decoder, encoder, doc); + break + case messageYjsSyncStep2: + readSyncStep2(decoder, doc, transactionOrigin); + break + case messageYjsUpdate: + readUpdate$1(decoder, doc, transactionOrigin); + break + default: + throw new Error('Unknown message type') + } + return messageType +}; + +if (typeof window !== 'undefined') { + // @ts-ignore + window.Y = Y; // eslint-disable-line +} + +/** + * @param {TestYInstance} y // publish message created by `y` to all other online clients + * @param {Uint8Array} m + */ +const broadcastMessage = (y, m) => { + if (y.tc.onlineConns.has(y)) { + y.tc.onlineConns.forEach(remoteYInstance => { + if (remoteYInstance !== y) { + remoteYInstance._receive(m, y); + } + }); + } +}; + +class TestYInstance extends Doc { + /** + * @param {TestConnector} testConnector + * @param {number} clientID + */ + constructor (testConnector, clientID) { + super(); + this.userID = clientID; // overwriting clientID + /** + * @type {TestConnector} + */ + this.tc = testConnector; + /** + * @type {Map>} + */ + this.receiving = new Map(); + testConnector.allConns.add(this); + // set up observe on local model + this.on('update', /** @param {Uint8Array} update @param {any} origin */ (update, origin) => { + if (origin !== testConnector) { + const encoder = encoding.createEncoder(); + writeUpdate(encoder, update); + broadcastMessage(this, encoding.toUint8Array(encoder)); + } + }); + this.connect(); + } + + /** + * Disconnect from TestConnector. + */ + disconnect () { + this.receiving = new Map(); + this.tc.onlineConns.delete(this); + } + + /** + * Append yourself to the list of known Y instances in testconnector. + * Also initiate sync with all clients. + */ + connect () { + if (!this.tc.onlineConns.has(this)) { + this.tc.onlineConns.add(this); + const encoder = encoding.createEncoder(); + writeSyncStep1(encoder, this); + // publish SyncStep1 + broadcastMessage(this, encoding.toUint8Array(encoder)); + this.tc.onlineConns.forEach(remoteYInstance => { + if (remoteYInstance !== this) { + // remote instance sends instance to this instance + const encoder = encoding.createEncoder(); + writeSyncStep1(encoder, remoteYInstance); + this._receive(encoding.toUint8Array(encoder), remoteYInstance); + } + }); + } + } + + /** + * Receive a message from another client. This message is only appended to the list of receiving messages. + * TestConnector decides when this client actually reads this message. + * + * @param {Uint8Array} message + * @param {TestYInstance} remoteClient + */ + _receive (message, remoteClient) { + let messages = this.receiving.get(remoteClient); + if (messages === undefined) { + messages = []; + this.receiving.set(remoteClient, messages); + } + messages.push(message); + } +} + +/** + * Keeps track of TestYInstances. + * + * The TestYInstances add/remove themselves from the list of connections maiained in this object. + * I think it makes sense. Deal with it. + */ +class TestConnector { + /** + * @param {prng.PRNG} gen + */ + constructor (gen) { + /** + * @type {Set} + */ + this.allConns = new Set(); + /** + * @type {Set} + */ + this.onlineConns = new Set(); + /** + * @type {prng.PRNG} + */ + this.prng = gen; + } + + /** + * Create a new Y instance and add it to the list of connections + * @param {number} clientID + */ + createY (clientID) { + return new TestYInstance(this, clientID) + } + + /** + * Choose random connection and flush a random message from a random sender. + * + * If this function was unable to flush a message, because there are no more messages to flush, it returns false. true otherwise. + * @return {boolean} + */ + flushRandomMessage () { + const gen = this.prng; + const conns = Array.from(this.onlineConns).filter(conn => conn.receiving.size > 0); + if (conns.length > 0) { + const receiver = prng.oneOf(gen, conns); + const [sender, messages] = prng.oneOf(gen, Array.from(receiver.receiving)); + const m = messages.shift(); + if (messages.length === 0) { + receiver.receiving.delete(sender); + } + if (m === undefined) { + return this.flushRandomMessage() + } + const encoder = encoding.createEncoder(); + // console.log('receive (' + sender.userID + '->' + receiver.userID + '):\n', syncProtocol.stringifySyncMessage(decoding.createDecoder(m), receiver)) + // do not publish data created when this function is executed (could be ss2 or update message) + readSyncMessage(decoding.createDecoder(m), encoder, receiver, receiver.tc); + if (encoding.length(encoder) > 0) { + // send reply message + sender._receive(encoding.toUint8Array(encoder), receiver); + } + return true + } + return false + } + + /** + * @return {boolean} True iff this function actually flushed something + */ + flushAllMessages () { + let didSomething = false; + while (this.flushRandomMessage()) { + didSomething = true; + } + return didSomething + } + + reconnectAll () { + this.allConns.forEach(conn => conn.connect()); + } + + disconnectAll () { + this.allConns.forEach(conn => conn.disconnect()); + } + + syncAll () { + this.reconnectAll(); + this.flushAllMessages(); + } + + /** + * @return {boolean} Whether it was possible to disconnect a randon connection. + */ + disconnectRandom () { + if (this.onlineConns.size === 0) { + return false + } + prng.oneOf(this.prng, Array.from(this.onlineConns)).disconnect(); + return true + } + + /** + * @return {boolean} Whether it was possible to reconnect a random connection. + */ + reconnectRandom () { + /** + * @type {Array} + */ + const reconnectable = []; + this.allConns.forEach(conn => { + if (!this.onlineConns.has(conn)) { + reconnectable.push(conn); + } + }); + if (reconnectable.length === 0) { + return false + } + prng.oneOf(this.prng, reconnectable).connect(); + return true + } +} + +/** + * @template T + * @param {t.TestCase} tc + * @param {{users?:number}} conf + * @param {InitTestObjectCallback} [initTestObject] + * @return {{testObjects:Array,testConnector:TestConnector,users:Array,array0:Y.YArray,array1:Y.YArray,array2:Y.YArray,map0:Y.YMap,map1:Y.YMap,map2:Y.YMap,map3:Y.YMap,text0:Y.YText,text1:Y.YText,text2:Y.YText,xml0:Y.YXmlElement,xml1:Y.YXmlElement,xml2:Y.YXmlElement}} + */ +const init = (tc, { users = 5 } = {}, initTestObject) => { + /** + * @type {Object} + */ + const result = { + users: [] + }; + const gen = tc.prng; + // choose an encoding approach at random + if (prng.bool(gen)) { + useV2Encoding(); + } else { + useV1Encoding(); + } + + const testConnector = new TestConnector(gen); + result.testConnector = testConnector; + for (let i = 0; i < users; i++) { + const y = testConnector.createY(i); + y.clientID = i; + result.users.push(y); + result['array' + i] = y.getArray('array'); + result['map' + i] = y.getMap('map'); + result['xml' + i] = y.get('xml', YXmlElement); + result['text' + i] = y.getText('text'); + } + testConnector.syncAll(); + result.testObjects = result.users.map(initTestObject || (() => null)); + useV1Encoding(); + return /** @type {any} */ (result) +}; + +/** + * 1. reconnect and flush all + * 2. user 0 gc + * 3. get type content + * 4. disconnect & reconnect all (so gc is propagated) + * 5. compare os, ds, ss + * + * @param {Array} users + */ +const compare = users => { + users.forEach(u => u.connect()); + while (users[0].tc.flushAllMessages()) {} + const userArrayValues = users.map(u => u.getArray('array').toJSON()); + const userMapValues = users.map(u => u.getMap('map').toJSON()); + const userXmlValues = users.map(u => u.get('xml', YXmlElement).toString()); + const userTextValues = users.map(u => u.getText('text').toDelta()); + for (const u of users) { + t.assert(u.store.pendingDeleteReaders.length === 0); + t.assert(u.store.pendingStack.length === 0); + t.assert(u.store.pendingClientsStructRefs.size === 0); + } + // Test Array iterator + t.compare(users[0].getArray('array').toArray(), Array.from(users[0].getArray('array'))); + // Test Map iterator + const ymapkeys = Array.from(users[0].getMap('map').keys()); + t.assert(ymapkeys.length === Object.keys(userMapValues[0]).length); + ymapkeys.forEach(key => t.assert(object.hasProperty(userMapValues[0], key))); + /** + * @type {Object} + */ + const mapRes = {}; + for (const [k, v] of users[0].getMap('map')) { + mapRes[k] = v instanceof AbstractType ? v.toJSON() : v; + } + t.compare(userMapValues[0], mapRes); + // Compare all users + for (let i = 0; i < users.length - 1; i++) { + t.compare(userArrayValues[i].length, users[i].getArray('array').length); + t.compare(userArrayValues[i], userArrayValues[i + 1]); + t.compare(userMapValues[i], userMapValues[i + 1]); + t.compare(userXmlValues[i], userXmlValues[i + 1]); + t.compare(userTextValues[i].map(/** @param {any} a */ a => typeof a.insert === 'string' ? a.insert : ' ').join('').length, users[i].getText('text').length); + t.compare(userTextValues[i], userTextValues[i + 1]); + t.compare(getStateVector(users[i].store), getStateVector(users[i + 1].store)); + compareDS(createDeleteSetFromStructStore(users[i].store), createDeleteSetFromStructStore(users[i + 1].store)); + compareStructStores(users[i].store, users[i + 1].store); + } + users.map(u => u.destroy()); +}; + +/** + * @param {Y.Item?} a + * @param {Y.Item?} b + * @return {boolean} + */ +const compareItemIDs = (a, b) => a === b || (a !== null && b != null && compareIDs(a.id, b.id)); + +/** + * @param {Y.StructStore} ss1 + * @param {Y.StructStore} ss2 + */ +const compareStructStores = (ss1, ss2) => { + t.assert(ss1.clients.size === ss2.clients.size); + for (const [client, structs1] of ss1.clients) { + const structs2 = /** @type {Array} */ (ss2.clients.get(client)); + t.assert(structs2 !== undefined && structs1.length === structs2.length); + for (let i = 0; i < structs1.length; i++) { + const s1 = structs1[i]; + const s2 = structs2[i]; + // checks for abstract struct + if ( + s1.constructor !== s2.constructor || + !compareIDs(s1.id, s2.id) || + s1.deleted !== s2.deleted || + // @ts-ignore + s1.length !== s2.length + ) { + t.fail('Structs dont match'); + } + if (s1 instanceof Item) { + if ( + !(s2 instanceof Item) || + !((s1.left === null && s2.left === null) || (s1.left !== null && s2.left !== null && compareIDs(s1.left.lastId, s2.left.lastId))) || + !compareItemIDs(s1.right, s2.right) || + !compareIDs(s1.origin, s2.origin) || + !compareIDs(s1.rightOrigin, s2.rightOrigin) || + s1.parentSub !== s2.parentSub + ) { + return t.fail('Items dont match') + } + // make sure that items are connected correctly + t.assert(s1.left === null || s1.left.right === s1); + t.assert(s1.right === null || s1.right.left === s1); + t.assert(s2.left === null || s2.left.right === s2); + t.assert(s2.right === null || s2.right.left === s2); + } + } + } +}; + +/** + * @param {Y.DeleteSet} ds1 + * @param {Y.DeleteSet} ds2 + */ +const compareDS = (ds1, ds2) => { + t.assert(ds1.clients.size === ds2.clients.size); + ds1.clients.forEach((deleteItems1, client) => { + const deleteItems2 = /** @type {Array} */ (ds2.clients.get(client)); + t.assert(deleteItems2 !== undefined && deleteItems1.length === deleteItems2.length); + for (let i = 0; i < deleteItems1.length; i++) { + const di1 = deleteItems1[i]; + const di2 = deleteItems2[i]; + if (di1.clock !== di2.clock || di1.len !== di2.len) { + t.fail('DeleteSets dont match'); + } + } + }); +}; + +/** + * @template T + * @callback InitTestObjectCallback + * @param {TestYInstance} y + * @return {T} + */ + +/** + * @template T + * @param {t.TestCase} tc + * @param {Array} mods + * @param {number} iterations + * @param {InitTestObjectCallback} [initTestObject] + */ +const applyRandomTests = (tc, mods, iterations, initTestObject) => { + const gen = tc.prng; + const result = init(tc, { users: 5 }, initTestObject); + const { testConnector, users } = result; + for (let i = 0; i < iterations; i++) { + if (prng.int32(gen, 0, 100) <= 2) { + // 2% chance to disconnect/reconnect a random user + if (prng.bool(gen)) { + testConnector.disconnectRandom(); + } else { + testConnector.reconnectRandom(); + } + } else if (prng.int32(gen, 0, 100) <= 1) { + // 1% chance to flush all + testConnector.flushAllMessages(); + } else if (prng.int32(gen, 0, 100) <= 50) { + // 50% chance to flush a random message + testConnector.flushRandomMessage(); + } + const user = prng.int32(gen, 0, users.length - 1); + const test = prng.oneOf(gen, mods); + test(users[user], gen, result.testObjects[user]); + } + compare(users); + return result +}; + +/** + * The unique prosemirror plugin key for syncPlugin + * + * @public + */ +const ySyncPluginKey = new prosemirrorState.PluginKey('y-sync'); + +/** + * The unique prosemirror plugin key for undoPlugin + * + * @public + */ +const yUndoPluginKey = new prosemirrorState.PluginKey('y-undo'); + +/** + * The unique prosemirror plugin key for cursorPlugin + * + * @public + */ +const yCursorPluginKey = new prosemirrorState.PluginKey('yjs-cursor'); + +/** + * @module bindings/prosemirror + */ + +/** + * @param {Y.Item} item + * @param {Y.Snapshot} [snapshot] + */ +const isVisible$1 = (item, snapshot) => snapshot === undefined ? !item.deleted : (snapshot.sv.has(item.id.client) && /** @type {number} */ (snapshot.sv.get(item.id.client)) > item.id.clock && !isDeleted(snapshot.ds, item.id)); + +/** + * Either a node if type is YXmlElement or an Array of text nodes if YXmlText + * @typedef {Map>} ProsemirrorMapping + */ + +/** + * @typedef {Object} ColorDef + * @property {string} ColorDef.light + * @property {string} ColorDef.dark + */ + +/** + * @typedef {Object} YSyncOpts + * @property {Array} [YSyncOpts.colors] + * @property {Map} [YSyncOpts.colorMapping] + * @property {Y.PermanentUserData|null} [YSyncOpts.permanentUserData] + */ + +/** + * @type {Array} + */ +const defaultColors = [{ light: '#ecd44433', dark: '#ecd444' }]; + +/** + * @param {Map} colorMapping + * @param {Array} colors + * @param {string} user + * @return {ColorDef} + */ +const getUserColor = (colorMapping, colors, user) => { + if (!colorMapping.has(user)) { + colorMapping.set(user, colors[colorMapping.size % colors.length]); + } + return /** @type {ColorDef} */ (colorMapping.get(user)); +}; + +/** + * This plugin listens to changes in prosemirror view and keeps yXmlState and view in sync. + * + * This plugin also keeps references to the type and the shared document so other plugins can access it. + * @param {Y.XmlFragment} yXmlFragment + * @param {YSyncOpts} opts + * @return {any} Returns a prosemirror plugin that binds to this type + */ +const ySyncPlugin = (yXmlFragment, { colors = defaultColors, colorMapping = new Map(), permanentUserData = null } = {}) => { + let changedInitialContent = false; + const plugin = new prosemirrorState.Plugin({ + props: { + editable: (state) => { + const syncState = ySyncPluginKey.getState(state); + return syncState.snapshot == null && syncState.prevSnapshot == null + } + }, + key: ySyncPluginKey, + state: { + init: (initargs, state) => { + return { + type: yXmlFragment, + doc: yXmlFragment.doc, + binding: null, + snapshot: null, + prevSnapshot: null, + isChangeOrigin: false, + colors, + colorMapping, + permanentUserData + } + }, + apply: (tr, pluginState) => { + const change = tr.getMeta(ySyncPluginKey); + if (change !== undefined) { + pluginState = Object.assign({}, pluginState); + for (const key in change) { + pluginState[key] = change[key]; + } + } + // always set isChangeOrigin. If undefined, this is not change origin. + pluginState.isChangeOrigin = change !== undefined && !!change.isChangeOrigin; + if (pluginState.binding !== null) { + if (change !== undefined && (change.snapshot != null || change.prevSnapshot != null)) { + // snapshot changed, rerender next + setTimeout(() => { + if (change.restore == null) { + pluginState.binding._renderSnapshot(change.snapshot, change.prevSnapshot, pluginState); + } else { + pluginState.binding._renderSnapshot(change.snapshot, change.snapshot, pluginState); + // reset to current prosemirror state + delete pluginState.restore; + delete pluginState.snapshot; + delete pluginState.prevSnapshot; + pluginState.binding._prosemirrorChanged(pluginState.binding.prosemirrorView.state.doc); + } + }, 0); + } + } + return pluginState + } + }, + view: view => { + + const binding = new ProsemirrorBinding(yXmlFragment, view); + binding._forceRerender(); + view.dispatch(view.state.tr.setMeta(ySyncPluginKey, { binding })); + + return { + update: () => { + const pluginState = plugin.getState(view.state); + if (pluginState.snapshot == null && pluginState.prevSnapshot == null) { + if (changedInitialContent || view.state.doc.content.findDiffStart(view.state.doc.type.createAndFill().content) != null) { + changedInitialContent = true; + binding._prosemirrorChanged(view.state.doc); + } + } + }, + destroy: () => { + binding.destroy(); + } + } + } + }); + return plugin +}; + +/** + * @param {any} tr + * @param {any} relSel + * @param {ProsemirrorBinding} binding + */ +const restoreRelativeSelection = (tr, relSel, binding) => { + if (relSel !== null && relSel.anchor !== null && relSel.head !== null) { + const anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping); + const head = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.head, binding.mapping); + if (anchor !== null && head !== null) { + tr = tr.setSelection(prosemirrorState.TextSelection.create(tr.doc, anchor, head)); + } + } +}; + +const getRelativeSelection = (pmbinding, state) => ({ + anchor: absolutePositionToRelativePosition(state.selection.anchor, pmbinding.type, pmbinding.mapping), + head: absolutePositionToRelativePosition(state.selection.head, pmbinding.type, pmbinding.mapping) +}); + +/** + * Binding for prosemirror. + * + * @protected + */ +class ProsemirrorBinding { + /** + * @param {Y.XmlFragment} yXmlFragment The bind source + * @param {any} prosemirrorView The target binding + */ + constructor (yXmlFragment, prosemirrorView) { + this.type = yXmlFragment; + this.prosemirrorView = prosemirrorView; + this.mux = mutex_js.createMutex(); + /** + * @type {ProsemirrorMapping} + */ + this.mapping = new Map(); + this._observeFunction = this._typeChanged.bind(this); + /** + * @type {Y.Doc} + */ + // @ts-ignore + this.doc = yXmlFragment.doc; + /** + * current selection as relative positions in the Yjs model + */ + this.beforeTransactionSelection = null; + this.beforeAllTransactions = () => { + if (this.beforeTransactionSelection === null) { + this.beforeTransactionSelection = getRelativeSelection(this, prosemirrorView.state); + } + }; + this.afterAllTransactions = () => { + this.beforeTransactionSelection = null; + }; + + this.doc.on('beforeAllTransactions', this.beforeAllTransactions); + this.doc.on('afterAllTransactions', this.afterAllTransactions); + yXmlFragment.observeDeep(this._observeFunction); + + this._domSelectionInView = null; + } + + _isLocalCursorInView () { + if (!this.prosemirrorView.hasFocus()) return false + if (environment_js.isBrowser && this._domSelectionInView === null) { + // Calculate the domSelectionInView and clear by next tick after all events are finished + setTimeout(() => { + this._domSelectionInView = null; + }, 0); + this._domSelectionInView = this._isDomSelectionInView(); + } + return this._domSelectionInView + } + + _isDomSelectionInView () { + const selection = this.prosemirrorView._root.getSelection(); + + const range = this.prosemirrorView._root.createRange(); + range.setStart(selection.anchorNode, selection.anchorOffset); + range.setEnd(selection.focusNode, selection.focusOffset); + + // This is a workaround for an edgecase where getBoundingClientRect will + // return zero values if the selection is collapsed at the start of a newline + // see reference here: https://stackoverflow.com/a/59780954 + const rects = range.getClientRects(); + if (rects.length === 0) { + // probably buggy newline behavior, explicitly select the node contents + if (range.startContainer && range.collapsed) { + range.selectNodeContents(range.startContainer); + } + } + + const bounding = range.getBoundingClientRect(); + const documentElement = dom_js.doc.documentElement; + + return bounding.bottom >= 0 && bounding.right >= 0 && + bounding.left <= (window.innerWidth || documentElement.clientWidth || 0) && + bounding.top <= (window.innerHeight || documentElement.clientHeight || 0) + } + + renderSnapshot (snapshot, prevSnapshot) { + if (!prevSnapshot) { + prevSnapshot = createSnapshot(createDeleteSet(), new Map()); + } + this.prosemirrorView.dispatch(this.prosemirrorView.state.tr.setMeta(ySyncPluginKey, { snapshot, prevSnapshot })); + } + + unrenderSnapshot () { + this.mapping = new Map(); + this.mux(() => { + const fragmentContent = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null); + // @ts-ignore + const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new prosemirrorModel.Slice(new prosemirrorModel.Fragment(fragmentContent), 0, 0)); + tr.setMeta(ySyncPluginKey, { snapshot: null, prevSnapshot: null }); + this.prosemirrorView.dispatch(tr); + }); + } + + _forceRerender () { + this.mapping = new Map(); + this.mux(() => { + let content = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null); + if (content.length) { + // @ts-ignore + const tr = this.prosemirrorView.state.tr.replaceWith(0, this.prosemirrorView.state.doc.content.size, new prosemirrorModel.Fragment(content)); + this.prosemirrorView.dispatch(tr); + } + }); + } + + /** + * @param {Y.Snapshot} snapshot + * @param {Y.Snapshot} prevSnapshot + * @param {Object} pluginState + */ + _renderSnapshot (snapshot$1, prevSnapshot, pluginState) { + if (!snapshot$1) { + snapshot$1 = snapshot(this.doc); + } + // clear mapping because we are going to rerender + this.mapping = new Map(); + this.mux(() => { + this.doc.transact(transaction => { + // before rendering, we are going to sanitize ops and split deleted ops + // if they were deleted by seperate users. + const pud = pluginState.permanentUserData; + if (pud) { + pud.dss.forEach(ds => { + iterateDeletedStructs(transaction, ds, item => {}); + }); + } + const computeYChange = (type, id) => { + const user = type === 'added' ? pud.getUserByClientId(id.client) : pud.getUserByDeletedId(id); + return { + user, + type, + color: getUserColor(pluginState.colorMapping, pluginState.colors, user) + } + }; + // Create document fragment and render + const fragmentContent = typeListToArraySnapshot(this.type, new Snapshot(prevSnapshot.ds, snapshot$1.sv)).map(t => { + if (!t._item.deleted || isVisible$1(t._item, snapshot$1) || isVisible$1(t._item, prevSnapshot)) { + return createNodeFromYElement(t, this.prosemirrorView.state.schema, new Map(), snapshot$1, prevSnapshot, computeYChange) + } else { + // No need to render elements that are not visible by either snapshot. + // If a client adds and deletes content in the same snapshot the element is not visible by either snapshot. + return null + } + }).filter(n => n !== null); + // @ts-ignore + const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new prosemirrorModel.Slice(new prosemirrorModel.Fragment(fragmentContent), 0, 0)); + this.prosemirrorView.dispatch(tr); + }, ySyncPluginKey); + }); + } + + /** + * @param {Array} events + * @param {Y.Transaction} transaction + */ + _typeChanged (events, transaction) { + const syncState = ySyncPluginKey.getState(this.prosemirrorView.state); + if (events.length === 0 || syncState.snapshot != null || syncState.prevSnapshot != null) { + // drop out if snapshot is active + this.renderSnapshot(syncState.snapshot, syncState.prevSnapshot); + return + } + this.mux(() => { + /** + * @param {any} _ + * @param {Y.AbstractType} type + */ + const delType = (_, type) => this.mapping.delete(type); + iterateDeletedStructs(transaction, transaction.deleteSet, struct => struct.constructor === Item && this.mapping.delete(/** @type {Y.ContentType} */ (/** @type {Y.Item} */ (struct).content).type)); + transaction.changed.forEach(delType); + transaction.changedParentTypes.forEach(delType); + const fragmentContent = this.type.toArray().map(t => createNodeIfNotExists(/** @type {Y.XmlElement | Y.XmlHook} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null); + // @ts-ignore + let tr = this.prosemirrorView.state.tr.replaceWith(0, this.prosemirrorView.state.doc.content.size, new prosemirrorModel.Fragment(fragmentContent)); + restoreRelativeSelection(tr, this.beforeTransactionSelection, this); + tr = tr.setMeta(ySyncPluginKey, { isChangeOrigin: true }); + if (this.beforeTransactionSelection !== null && this._isLocalCursorInView()) { + tr.scrollIntoView(); + } + this.prosemirrorView.dispatch(tr); + }); + } + + _prosemirrorChanged (doc) { + this.mux(() => { + this.doc.transact(() => { + updateYFragment(this.doc, this.type, doc, this.mapping); + this.beforeTransactionSelection = getRelativeSelection(this, this.prosemirrorView.state); + }, ySyncPluginKey); + }); + } + + destroy () { + this.type.unobserveDeep(this._observeFunction); + this.doc.off('beforeAllTransactions', this.beforeAllTransactions); + this.doc.off('afterAllTransactions', this.afterAllTransactions); + } +} + +/** + * @private + * @param {Y.XmlElement | Y.XmlHook} el + * @param {PMSchema} schema + * @param {ProsemirrorMapping} mapping + * @param {Y.Snapshot} [snapshot] + * @param {Y.Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', Y.ID):any} [computeYChange] + * @return {PMNode | null} + */ +const createNodeIfNotExists = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => { + const node = /** @type {PMNode} */ (mapping.get(el)); + if (node === undefined) { + if (el instanceof YXmlElement) { + return createNodeFromYElement(el, schema, mapping, snapshot, prevSnapshot, computeYChange) + } else { + throw error.methodUnimplemented() // we are currently not handling hooks + } + } + return node +}; + +/** + * @private + * @param {Y.XmlElement} el + * @param {any} schema + * @param {ProsemirrorMapping} mapping + * @param {Y.Snapshot} [snapshot] + * @param {Y.Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', Y.ID):any} [computeYChange] + * @return {PMNode | null} Returns node if node could be created. Otherwise it deletes the yjs type and returns null + */ +const createNodeFromYElement = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => { + const children = []; + const createChildren = type => { + if (type.constructor === YXmlElement) { + const n = createNodeIfNotExists(type, schema, mapping, snapshot, prevSnapshot, computeYChange); + if (n !== null) { + children.push(n); + } + } else { + const ns = createTextNodesFromYText(type, schema, mapping, snapshot, prevSnapshot, computeYChange); + if (ns !== null) { + ns.forEach(textchild => { + if (textchild !== null) { + children.push(textchild); + } + }); + } + } + }; + if (snapshot === undefined || prevSnapshot === undefined) { + el.toArray().forEach(createChildren); + } else { + typeListToArraySnapshot(el, new Snapshot(prevSnapshot.ds, snapshot.sv)).forEach(createChildren); + } + try { + const attrs = el.getAttributes(snapshot); + if (snapshot !== undefined) { + if (!isVisible$1(/** @type {Y.Item} */ (el._item), snapshot)) { + attrs.ychange = computeYChange ? computeYChange('removed', /** @type {Y.Item} */ (el._item).id) : { type: 'removed' }; + } else if (!isVisible$1(/** @type {Y.Item} */ (el._item), prevSnapshot)) { + attrs.ychange = computeYChange ? computeYChange('added', /** @type {Y.Item} */ (el._item).id) : { type: 'added' }; + } + } + const node = schema.node(el.nodeName, attrs, children); + mapping.set(el, node); + return node + } catch (e) { + // an error occured while creating the node. This is probably a result of a concurrent action. + /** @type {Y.Doc} */ (el.doc).transact(transaction => { + /** @type {Y.Item} */ (el._item).delete(transaction); + }, ySyncPluginKey); + mapping.delete(el); + return null + } +}; + +/** + * @private + * @param {Y.XmlText} text + * @param {any} schema + * @param {ProsemirrorMapping} mapping + * @param {Y.Snapshot} [snapshot] + * @param {Y.Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', Y.ID):any} [computeYChange] + * @return {Array|null} + */ +const createTextNodesFromYText = (text, schema, mapping, snapshot, prevSnapshot, computeYChange) => { + const nodes = []; + const deltas = text.toDelta(snapshot, prevSnapshot, computeYChange); + try { + for (let i = 0; i < deltas.length; i++) { + const delta = deltas[i]; + const marks = []; + for (const markName in delta.attributes) { + marks.push(schema.mark(markName, delta.attributes[markName])); + } + nodes.push(schema.text(delta.insert, marks)); + } + } catch (e) { + // an error occured while creating the node. This is probably a result of a concurrent action. + /** @type {Y.Doc} */ (text.doc).transact(transaction => { + /** @type {Y.Item} */ (text._item).delete(transaction); + }, ySyncPluginKey); + return null + } + // @ts-ignore + return nodes +}; + +/** + * @private + * @param {Array} nodes prosemirror node + * @param {ProsemirrorMapping} mapping + * @return {Y.XmlText} + */ +const createTypeFromTextNodes = (nodes, mapping) => { + const type = new YXmlText(); + const delta = nodes.map(node => ({ + // @ts-ignore + insert: node.text, + attributes: marksToAttributes(node.marks) + })); + type.applyDelta(delta); + mapping.set(type, nodes); + return type +}; + +/** + * @private + * @param {any} node prosemirror node + * @param {ProsemirrorMapping} mapping + * @return {Y.XmlElement} + */ +const createTypeFromElementNode = (node, mapping) => { + const type = new YXmlElement(node.type.name); + for (const key in node.attrs) { + const val = node.attrs[key]; + if (val !== null && key !== 'ychange') { + type.setAttribute(key, val); + } + } + type.insert(0, normalizePNodeContent(node).map(n => createTypeFromTextOrElementNode(n, mapping))); + mapping.set(type, node); + return type +}; + +/** + * @private + * @param {PMNode|Array} node prosemirror text node + * @param {ProsemirrorMapping} mapping + * @return {Y.XmlElement|Y.XmlText} + */ +const createTypeFromTextOrElementNode = (node, mapping) => node instanceof Array ? createTypeFromTextNodes(node, mapping) : createTypeFromElementNode(node, mapping); + +const equalAttrs$1 = (pattrs, yattrs) => { + const keys = Object.keys(pattrs).filter(key => pattrs[key] !== null); + let eq = keys.length === Object.keys(yattrs).filter(key => yattrs[key] !== null).length; + for (let i = 0; i < keys.length && eq; i++) { + const key = keys[i]; + const l = pattrs[key]; + const r = yattrs[key]; + eq = key === 'ychange' || l === r || (typeof l === 'object' && typeof r === 'object' && equalAttrs$1(l, r)); + } + return eq +}; + +/** + * @typedef {Array|PMNode>} NormalizedPNodeContent + */ + +/** + * @param {any} pnode + * @return {NormalizedPNodeContent} + */ +const normalizePNodeContent = pnode => { + const c = pnode.content.content; + const res = []; + for (let i = 0; i < c.length; i++) { + const n = c[i]; + if (n.isText) { + const textNodes = []; + for (let tnode = c[i]; i < c.length && tnode.isText; tnode = c[++i]) { + textNodes.push(tnode); + } + i--; + res.push(textNodes); + } else { + res.push(n); + } + } + return res +}; + +/** + * @param {Y.XmlText} ytext + * @param {Array} ptexts + */ +const equalYTextPText = (ytext, ptexts) => { + const delta = ytext.toDelta(); + return delta.length === ptexts.length && delta.every((d, i) => d.insert === /** @type {any} */ (ptexts[i]).text && object.keys(d.attributes || {}).length === ptexts[i].marks.length && ptexts[i].marks.every(mark => equalAttrs$1(d.attributes[mark.type.name] || {}, mark.attrs))) +}; + +/** + * @param {Y.XmlElement|Y.XmlText|Y.XmlHook} ytype + * @param {any|Array} pnode + */ +const equalYTypePNode = (ytype, pnode) => { + if (ytype instanceof YXmlElement && !(pnode instanceof Array) && matchNodeName(ytype, pnode)) { + const normalizedContent = normalizePNodeContent(pnode); + return ytype._length === normalizedContent.length && equalAttrs$1(ytype.getAttributes(), pnode.attrs) && ytype.toArray().every((ychild, i) => equalYTypePNode(ychild, normalizedContent[i])) + } + return ytype instanceof YXmlText && pnode instanceof Array && equalYTextPText(ytype, pnode) +}; + +/** + * @param {PMNode | Array | undefined} mapped + * @param {PMNode | Array} pcontent + */ +const mappedIdentity = (mapped, pcontent) => mapped === pcontent || (mapped instanceof Array && pcontent instanceof Array && mapped.length === pcontent.length && mapped.every((a, i) => pcontent[i] === a)); + +/** + * @param {Y.XmlElement} ytype + * @param {PMNode} pnode + * @param {ProsemirrorMapping} mapping + * @return {{ foundMappedChild: boolean, equalityFactor: number }} + */ +const computeChildEqualityFactor = (ytype, pnode, mapping) => { + const yChildren = ytype.toArray(); + const pChildren = normalizePNodeContent(pnode); + const pChildCnt = pChildren.length; + const yChildCnt = yChildren.length; + const minCnt = math.min(yChildCnt, pChildCnt); + let left = 0; + let right = 0; + let foundMappedChild = false; + for (; left < minCnt; left++) { + const leftY = yChildren[left]; + const leftP = pChildren[left]; + if (mappedIdentity(mapping.get(leftY), leftP)) { + foundMappedChild = true;// definite (good) match! + } else if (!equalYTypePNode(leftY, leftP)) { + break + } + } + for (; left + right < minCnt; right++) { + const rightY = yChildren[yChildCnt - right - 1]; + const rightP = pChildren[pChildCnt - right - 1]; + if (mappedIdentity(mapping.get(rightY), rightP)) { + foundMappedChild = true; + } else if (!equalYTypePNode(rightY, rightP)) { + break + } + } + return { + equalityFactor: left + right, + foundMappedChild + } +}; + +const ytextTrans = ytext => { + let str = ''; + /** + * @type {Y.Item|null} + */ + let n = ytext._start; + const nAttrs = {}; + while (n !== null) { + if (!n.deleted) { + if (n.countable && n.content instanceof ContentString) { + str += n.content.str; + } else if (n.content instanceof ContentFormat) { + nAttrs[n.content.key] = null; + } + } + n = n.right; + } + return { + str, + nAttrs + } +}; + +/** + * @todo test this more + * + * @param {Y.Text} ytext + * @param {Array} ptexts + * @param {ProsemirrorMapping} mapping + */ +const updateYText = (ytext, ptexts, mapping) => { + mapping.set(ytext, ptexts); + const { nAttrs, str } = ytextTrans(ytext); + const content = ptexts.map(p => ({ insert: /** @type {any} */ (p).text, attributes: Object.assign({}, nAttrs, marksToAttributes(p.marks)) })); + const { insert, remove, index } = diff_js.simpleDiff(str, content.map(c => c.insert).join('')); + ytext.delete(index, remove); + ytext.insert(index, insert); + ytext.applyDelta(content.map(c => ({ retain: c.insert.length, attributes: c.attributes }))); +}; + +const marksToAttributes = marks => { + const pattrs = {}; + marks.forEach(mark => { + if (mark.type.name !== 'ychange') { + pattrs[mark.type.name] = mark.attrs; + } + }); + return pattrs +}; + +/** + * @private + * @param {Y.Doc} y + * @param {Y.XmlFragment} yDomFragment + * @param {any} pNode + * @param {ProsemirrorMapping} mapping + */ +const updateYFragment = (y, yDomFragment, pNode, mapping) => { + if (yDomFragment instanceof YXmlElement && yDomFragment.nodeName !== pNode.type.name) { + throw new Error('node name mismatch!') + } + mapping.set(yDomFragment, pNode); + // update attributes + if (yDomFragment instanceof YXmlElement) { + const yDomAttrs = yDomFragment.getAttributes(); + const pAttrs = pNode.attrs; + for (const key in pAttrs) { + if (pAttrs[key] !== null) { + if (yDomAttrs[key] !== pAttrs[key] && key !== 'ychange') { + yDomFragment.setAttribute(key, pAttrs[key]); + } + } else { + yDomFragment.removeAttribute(key); + } + } + // remove all keys that are no longer in pAttrs + for (const key in yDomAttrs) { + if (pAttrs[key] === undefined) { + yDomFragment.removeAttribute(key); + } + } + } + // update children + const pChildren = normalizePNodeContent(pNode); + const pChildCnt = pChildren.length; + const yChildren = yDomFragment.toArray(); + const yChildCnt = yChildren.length; + const minCnt = math.min(pChildCnt, yChildCnt); + let left = 0; + let right = 0; + // find number of matching elements from left + for (;left < minCnt; left++) { + const leftY = yChildren[left]; + const leftP = pChildren[left]; + if (!mappedIdentity(mapping.get(leftY), leftP)) { + if (equalYTypePNode(leftY, leftP)) { + // update mapping + mapping.set(leftY, leftP); + } else { + break + } + } + } + // find number of matching elements from right + for (;right + left + 1 < minCnt; right++) { + const rightY = yChildren[yChildCnt - right - 1]; + const rightP = pChildren[pChildCnt - right - 1]; + if (!mappedIdentity(mapping.get(rightY), rightP)) { + if (equalYTypePNode(rightY, rightP)) { + // update mapping + mapping.set(rightY, rightP); + } else { + break + } + } + } + y.transact(() => { + // try to compare and update + while (yChildCnt - left - right > 0 && pChildCnt - left - right > 0) { + const leftY = yChildren[left]; + const leftP = pChildren[left]; + const rightY = yChildren[yChildCnt - right - 1]; + const rightP = pChildren[pChildCnt - right - 1]; + if (leftY instanceof YXmlText && leftP instanceof Array) { + if (!equalYTextPText(leftY, leftP)) { + updateYText(leftY, leftP, mapping); + } + left += 1; + } else { + let updateLeft = leftY instanceof YXmlElement && matchNodeName(leftY, leftP); + let updateRight = rightY instanceof YXmlElement && matchNodeName(rightY, rightP); + if (updateLeft && updateRight) { + // decide which which element to update + const equalityLeft = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (leftY), /** @type {PMNode} */ (leftP), mapping); + const equalityRight = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (rightY), /** @type {PMNode} */ (rightP), mapping); + if (equalityLeft.foundMappedChild && !equalityRight.foundMappedChild) { + updateRight = false; + } else if (!equalityLeft.foundMappedChild && equalityRight.foundMappedChild) { + updateLeft = false; + } else if (equalityLeft.equalityFactor < equalityRight.equalityFactor) { + updateLeft = false; + } else { + updateRight = false; + } + } + if (updateLeft) { + updateYFragment(y, /** @type {Y.XmlFragment} */ (leftY), /** @type {PMNode} */ (leftP), mapping); + left += 1; + } else if (updateRight) { + updateYFragment(y, /** @type {Y.XmlFragment} */ (rightY), /** @type {PMNode} */ (rightP), mapping); + right += 1; + } else { + yDomFragment.delete(left, 1); + yDomFragment.insert(left, [createTypeFromTextOrElementNode(leftP, mapping)]); + left += 1; + } + } + } + const yDelLen = yChildCnt - left - right; + if (yDelLen > 0) { + yDomFragment.delete(left, yDelLen); + } + if (left + right < pChildCnt) { + const ins = []; + for (let i = left; i < pChildCnt - right; i++) { + ins.push(createTypeFromTextOrElementNode(pChildren[i], mapping)); + } + yDomFragment.insert(left, ins); + } + }, ySyncPluginKey); +}; + +/** + * @function + * @param {Y.XmlElement} yElement + * @param {any} pNode Prosemirror Node + */ +const matchNodeName = (yElement, pNode) => !(pNode instanceof Array) && yElement.nodeName === pNode.type.name; + +/** + * Transforms a Prosemirror based absolute position to a Yjs Cursor (relative position in the Yjs model). + * + * @param {number} pos + * @param {Y.XmlFragment} type + * @param {ProsemirrorMapping} mapping + * @return {any} relative position + */ +const absolutePositionToRelativePosition = (pos, type, mapping) => { + if (pos === 0) { + return createRelativePositionFromTypeIndex(type, 0) + } + let n = type._first === null ? null : /** @type {Y.ContentType} */ (type._first.content).type; + while (n !== null && type !== n) { + if (n.constructor === YXmlText) { + if (n._length >= pos) { + return createRelativePositionFromTypeIndex(n, pos) + } else { + pos -= n._length; + } + if (n._item !== null && n._item.next !== null) { + n = /** @type {Y.ContentType} */ (n._item.next.content).type; + } else { + do { + n = n._item === null ? null : n._item.parent; + pos--; + } while (n !== type && n !== null && n._item !== null && n._item.next === null) + if (n !== null && n !== type) { + // @ts-gnore we know that n.next !== null because of above loop conditition + n = n._item === null ? null : /** @type {Y.ContentType} */ (/** @type Y.Item */ (n._item.next).content).type; + } + } + } else { + const pNodeSize = /** @type {any} */ (mapping.get(n) || { nodeSize: 0 }).nodeSize; + if (n._first !== null && pos < pNodeSize) { + n = /** @type {Y.ContentType} */ (n._first.content).type; + pos--; + } else { + if (pos === 1 && n._length === 0 && pNodeSize > 1) { + // edge case, should end in this paragraph + return new RelativePosition(n._item === null ? null : n._item.id, n._item === null ? findRootTypeKey(n) : null, null) + } + pos -= pNodeSize; + if (n._item !== null && n._item.next !== null) { + n = /** @type {Y.ContentType} */ (n._item.next.content).type; + } else { + if (pos === 0) { + // set to end of n.parent + n = n._item === null ? n : n._item.parent; + return new RelativePosition(n._item === null ? null : n._item.id, n._item === null ? findRootTypeKey(n) : null, null) + } + do { + n = /** @type {Y.Item} */ (n._item).parent; + pos--; + } while (n !== type && /** @type {Y.Item} */ (n._item).next === null) + // if n is null at this point, we have an unexpected case + if (n !== type) { + // We know that n._item.next is defined because of above loop condition + n = /** @type {Y.ContentType} */ (/** @type {Y.Item} */ (/** @type {Y.Item} */ (n._item).next).content).type; + } + } + } + } + if (n === null) { + throw error.unexpectedCase() + } + if (pos === 0 && n.constructor !== YXmlText && n !== type) { // TODO: set to <= 0 + return createRelativePosition$1(n._item.parent, n._item) + } + } + return createRelativePositionFromTypeIndex(type, type._length) +}; + +const createRelativePosition$1 = (type, item) => { + let typeid = null; + let tname = null; + if (type._item === null) { + tname = findRootTypeKey(type); + } else { + typeid = createID(type._item.id.client, type._item.id.clock); + } + return new RelativePosition(typeid, tname, item.id) +}; + +/** + * @param {Y.Doc} y + * @param {Y.XmlFragment} documentType Top level type that is bound to pView + * @param {any} relPos Encoded Yjs based relative position + * @param {ProsemirrorMapping} mapping + * @return {null|number} + */ +const relativePositionToAbsolutePosition = (y, documentType, relPos, mapping) => { + const decodedPos = createAbsolutePositionFromRelativePosition(relPos, y); + if (decodedPos === null || (decodedPos.type !== documentType && !isParentOf(documentType, decodedPos.type._item))) { + return null + } + let type = decodedPos.type; + let pos = 0; + if (type.constructor === YXmlText) { + pos = decodedPos.index; + } else if (type._item === null || !type._item.deleted) { + let n = type._first; + let i = 0; + while (i < type._length && i < decodedPos.index && n !== null) { + if (!n.deleted) { + const t = /** @type {Y.ContentType} */ (n.content).type; + i++; + if (t.constructor === YXmlText) { + pos += t._length; + } else { + pos += /** @type {any} */ (mapping.get(t)).nodeSize; + } + } + n = /** @type {Y.Item} */ (n.right); + } + pos += 1; // increase because we go out of n + } + while (type !== documentType && type._item !== null) { + // @ts-ignore + const parent = type._item.parent; + // @ts-ignore + if (parent._item === null || !parent._item.deleted) { + pos += 1; // the start tag + let n = parent._first; + // now iterate until we found type + while (n !== null) { + const contentType = /** @type {Y.ContentType} */ (n.content).type; + if (contentType === type) { + break + } + if (!n.deleted) { + if (contentType.constructor === YXmlText) { + pos += contentType._length; + } else { + pos += /** @type {any} */ (mapping.get(contentType)).nodeSize; + } + } + n = n.right; + } + } + type = parent; + } + return pos - 1 // we don't count the most outer tag, because it is a fragment +}; + +/** + * Utility method to convert a Prosemirror Doc Node into a Y.Doc. + * + * This can be used when importing existing content to Y.Doc for the first time, + * note that this should not be used to rehydrate a Y.Doc from a database once + * collaboration has begun as all history will be lost + * + * @param {Node} doc + * @param {string} xmlFragment + * @return {Y.Doc} + */ +function prosemirrorToYDoc (doc, xmlFragment = 'prosemirror') { + const ydoc = new Doc(); + const type = ydoc.get(xmlFragment, YXmlFragment); + if (!type.doc) { + return ydoc + } + + updateYFragment(type.doc, type, doc, new Map()); + return type.doc +} + +/** + * Utility method to convert Prosemirror compatible JSON into a Y.Doc. + * + * This can be used when importing existing content to Y.Doc for the first time, + * note that this should not be used to rehydrate a Y.Doc from a database once + * collaboration has begun as all history will be lost + * + * @param {Schema} schema + * @param {any} state + * @param {string} xmlFragment + * @return {Y.Doc} + */ +function prosemirrorJSONToYDoc (schema, state, xmlFragment = 'prosemirror') { + const doc = prosemirrorModel.Node.fromJSON(schema, state); + return prosemirrorToYDoc(doc, xmlFragment) +} + +/** + * Utility method to convert a Y.Doc to Prosemirror compatible JSON. + * + * @param {Y.Doc} ydoc + * @param {string} xmlFragment + * @return {Record} + */ +function yDocToProsemirrorJSON ( + ydoc, + xmlFragment = 'prosemirror' +) { + const items = ydoc.getXmlFragment(xmlFragment).toArray(); + + function serialize (item) { + /** + * @type {Object} NodeObject + * @property {string} NodeObject.type + * @property {Record=} NodeObject.attrs + * @property {Array=} NodeObject.content + */ + let response; + + // TODO: Must be a better way to detect text nodes than this + if (!item.nodeName) { + const delta = item.toDelta(); + response = delta.map((d) => { + const text = { + type: 'text', + text: d.insert + }; + + if (d.attributes) { + text.marks = Object.keys(d.attributes).map((type) => { + const attrs = d.attributes[type]; + const mark = { + type + }; + + if (Object.keys(attrs)) { + mark.attrs = attrs; + } + + return mark + }); + } + return text + }); + } else { + response = { + type: item.nodeName + }; + + const attrs = item.getAttributes(); + if (Object.keys(attrs).length) { + response.attrs = attrs; + } + + const children = item.toArray(); + if (children.length) { + response.content = children.map(serialize).flat(); + } + } + + return response + } + + return { + type: 'doc', + content: items.map(serialize) + } +} + +const brDOM = ['br']; + +const calcYchangeDomAttrs = (attrs, domAttrs = {}) => { + domAttrs = Object.assign({}, domAttrs); + if (attrs.ychange !== null) { + domAttrs.ychange_user = attrs.ychange.user; + domAttrs.ychange_state = attrs.ychange.state; + } + return domAttrs +}; + +// :: Object +// [Specs](#model.NodeSpec) for the nodes defined in this schema. +const nodes = { + // :: NodeSpec The top level document node. + doc: { + content: 'custom paragraph' + }, + + custom: { + atom: true, + attrs: { checked: { default: false } }, + parseDOM: [{ tag: 'div' }], + toDOM () { + return ['div'] + } + }, + + // :: NodeSpec A plain paragraph textblock. Represented in the DOM + // as a `

` element. + paragraph: { + attrs: { ychange: { default: null } }, + content: 'inline*', + group: 'block', + parseDOM: [{ tag: 'p' }], + toDOM (node) { + return ['p', calcYchangeDomAttrs(node.attrs), 0] + } + }, + + // :: NodeSpec A blockquote (`

`) wrapping one or more blocks. + blockquote: { + attrs: { ychange: { default: null } }, + content: 'block+', + group: 'block', + defining: true, + parseDOM: [{ tag: 'blockquote' }], + toDOM (node) { + return ['blockquote', calcYchangeDomAttrs(node.attrs), 0] + } + }, + + // :: NodeSpec A horizontal rule (`
`). + horizontal_rule: { + attrs: { ychange: { default: null } }, + group: 'block', + parseDOM: [{ tag: 'hr' }], + toDOM (node) { + return ['hr', calcYchangeDomAttrs(node.attrs)] + } + }, + + // :: NodeSpec A heading textblock, with a `level` attribute that + // should hold the number 1 to 6. Parsed and serialized as `

` to + // `

` elements. + heading: { + attrs: { + level: { default: 1 }, + ychange: { default: null } + }, + content: 'inline*', + group: 'block', + defining: true, + parseDOM: [ + { tag: 'h1', attrs: { level: 1 } }, + { tag: 'h2', attrs: { level: 2 } }, + { tag: 'h3', attrs: { level: 3 } }, + { tag: 'h4', attrs: { level: 4 } }, + { tag: 'h5', attrs: { level: 5 } }, + { tag: 'h6', attrs: { level: 6 } } + ], + toDOM (node) { + return ['h' + node.attrs.level, calcYchangeDomAttrs(node.attrs), 0] + } + }, + + // :: NodeSpec A code listing. Disallows marks or non-text inline + // nodes by default. Represented as a `
` element with a
+  // `` element inside of it.
+  code_block: {
+    attrs: { ychange: { default: null } },
+    content: 'text*',
+    marks: '',
+    group: 'block',
+    code: true,
+    defining: true,
+    parseDOM: [{ tag: 'pre', preserveWhitespace: 'full' }],
+    toDOM (node) {
+      return ['pre', calcYchangeDomAttrs(node.attrs), ['code', 0]]
+    }
+  },
+
+  // :: NodeSpec The text node.
+  text: {
+    group: 'inline'
+  },
+
+  // :: NodeSpec An inline image (``) node. Supports `src`,
+  // `alt`, and `href` attributes. The latter two default to the empty
+  // string.
+  image: {
+    inline: true,
+    attrs: {
+      ychange: { default: null },
+      src: {},
+      alt: { default: null },
+      title: { default: null }
+    },
+    group: 'inline',
+    draggable: true,
+    parseDOM: [
+      {
+        tag: 'img[src]',
+        getAttrs (dom) {
+          return {
+            src: dom.getAttribute('src'),
+            title: dom.getAttribute('title'),
+            alt: dom.getAttribute('alt')
+          }
+        }
+      }
+    ],
+    toDOM (node) {
+      const domAttrs = {
+        src: node.attrs.src,
+        title: node.attrs.title,
+        alt: node.attrs.alt
+      };
+      return ['img', calcYchangeDomAttrs(node.attrs, domAttrs)]
+    }
+  },
+
+  // :: NodeSpec A hard line break, represented in the DOM as `
`. + hard_break: { + inline: true, + group: 'inline', + selectable: false, + parseDOM: [{ tag: 'br' }], + toDOM () { + return brDOM + } + } +}; + +const emDOM = ['em', 0]; +const strongDOM = ['strong', 0]; +const codeDOM = ['code', 0]; + +// :: Object [Specs](#model.MarkSpec) for the marks in the schema. +const marks = { + // :: MarkSpec A link. Has `href` and `title` attributes. `title` + // defaults to the empty string. Rendered and parsed as an `` + // element. + link: { + attrs: { + href: {}, + title: { default: null } + }, + inclusive: false, + parseDOM: [ + { + tag: 'a[href]', + getAttrs (dom) { + return { + href: dom.getAttribute('href'), + title: dom.getAttribute('title') + } + } + } + ], + toDOM (node) { + return ['a', node.attrs, 0] + } + }, + + // :: MarkSpec An emphasis mark. Rendered as an `` element. + // Has parse rules that also match `` and `font-style: italic`. + em: { + parseDOM: [{ tag: 'i' }, { tag: 'em' }, { style: 'font-style=italic' }], + toDOM () { + return emDOM + } + }, + + // :: MarkSpec A strong mark. Rendered as ``, parse rules + // also match `` and `font-weight: bold`. + strong: { + parseDOM: [ + { tag: 'strong' }, + // This works around a Google Docs misbehavior where + // pasted content will be inexplicably wrapped in `` + // tags with a font-weight normal. + { + tag: 'b', + getAttrs: node => node.style.fontWeight !== 'normal' && null + }, + { + style: 'font-weight', + getAttrs: value => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null + } + ], + toDOM () { + return strongDOM + } + }, + + // :: MarkSpec Code font mark. Represented as a `` element. + code: { + parseDOM: [{ tag: 'code' }], + toDOM () { + return codeDOM + } + }, + ychange: { + attrs: { + user: { default: null }, + state: { default: null } + }, + inclusive: false, + parseDOM: [{ tag: 'ychange' }], + toDOM (node) { + return [ + 'ychange', + { ychange_user: node.attrs.user, ychange_state: node.attrs.state }, + 0 + ] + } + } +}; + +// :: Schema +// This schema rougly corresponds to the document schema used by +// [CommonMark](http://commonmark.org/), minus the list elements, +// which are defined in the [`prosemirror-schema-list`](#schema-list) +// module. +// +// To reuse elements from this schema, extend or read from its +// `spec.nodes` and `spec.marks` [properties](#model.Schema.spec). +const schema = new prosemirrorModel.Schema({ nodes, marks }); + +const schema$1 = /** @type {any} */ (basicSchema.schema); + +/** + * @param {t.TestCase} tc + */ +const testDocTransformation = tc => { + const view = createNewProsemirrorView(new Doc()); + view.dispatch(view.state.tr.insert(0, /** @type {any} */ (schema$1.node('paragraph', undefined, schema$1.text('hello world'))))); + const stateJSON = view.state.doc.toJSON(); + // test if transforming back and forth from Yjs doc works + const backandforth = yDocToProsemirrorJSON(prosemirrorJSONToYDoc(/** @type {any} */ (schema$1), stateJSON)); + t.compare(stateJSON, backandforth); +}; + +/** + * @param {t.TestCase} tc + */ +const testEmptyNotSync = tc => { + const ydoc = new Doc(); + const type = ydoc.getXmlFragment('prosemirror'); + const view = createNewComplexProsemirrorView(ydoc); + t.assert(type.toString() === '', 'should only sync after first change'); + + view.dispatch( + view.state.tr.setNodeMarkup(0, undefined, { + checked: true + }) + ); + t.compareStrings(type.toString(), ''); +}; + +const createNewComplexProsemirrorView = y => { + const view = new prosemirrorView.EditorView(null, { + // @ts-ignore + state: prosemirrorState.EditorState.create({ + schema: schema, + plugins: [ySyncPlugin(y.get('prosemirror', YXmlFragment))] + }) + }); + return view +}; + +const createNewProsemirrorView = y => { + const view = new prosemirrorView.EditorView(null, { + // @ts-ignore + state: prosemirrorState.EditorState.create({ + schema: schema$1, + plugins: [ySyncPlugin(y.get('prosemirror', YXmlFragment))] + }) + }); + return view +}; + +let charCounter = 0; + +const marksChoices = [ + [schema$1.mark('strong')], + [schema$1.mark('em')], + [schema$1.mark('em'), schema$1.mark('strong')], + [], + [] +]; + +const pmChanges = [ + /** + * @param {Y.Doc} y + * @param {prng.PRNG} gen + * @param {EditorView} p + */ + (y, gen, p) => { // insert text + const insertPos = prng.int32(gen, 0, p.state.doc.content.size); + const marks = prng.oneOf(gen, marksChoices); + const tr = p.state.tr; + const text = charCounter++ + prng.word(gen); + p.dispatch(tr.insert(insertPos, schema$1.text(text, marks))); + }, + /** + * @param {Y.Doc} y + * @param {prng.PRNG} gen + * @param {EditorView} p + */ + (y, gen, p) => { // delete text + const insertPos = prng.int32(gen, 0, p.state.doc.content.size); + const overwrite = math.min(prng.int32(gen, 0, p.state.doc.content.size - insertPos), 2); + p.dispatch(p.state.tr.insertText('', insertPos, insertPos + overwrite)); + }, + /** + * @param {Y.Doc} y + * @param {prng.PRNG} gen + * @param {EditorView} p + */ + (y, gen, p) => { // replace text + const insertPos = prng.int32(gen, 0, p.state.doc.content.size); + const overwrite = math.min(prng.int32(gen, 0, p.state.doc.content.size - insertPos), 2); + const text = charCounter++ + prng.word(gen); + p.dispatch(p.state.tr.insertText(text, insertPos, insertPos + overwrite)); + }, + /** + * @param {Y.Doc} y + * @param {prng.PRNG} gen + * @param {EditorView} p + */ + (y, gen, p) => { // insert paragraph + const insertPos = prng.int32(gen, 0, p.state.doc.content.size); + const marks = prng.oneOf(gen, marksChoices); + const tr = p.state.tr; + const text = charCounter++ + prng.word(gen); + p.dispatch(tr.insert(insertPos, schema$1.node('paragraph', undefined, schema$1.text(text, marks)))); + }, + /** + * @param {Y.Doc} y + * @param {prng.PRNG} gen + * @param {EditorView} p + */ + (y, gen, p) => { // insert codeblock + const insertPos = prng.int32(gen, 0, p.state.doc.content.size); + const tr = p.state.tr; + const text = charCounter++ + prng.word(gen); + p.dispatch(tr.insert(insertPos, schema$1.node('code_block', undefined, schema$1.text(text)))); + }, + /** + * @param {Y.Doc} y + * @param {prng.PRNG} gen + * @param {EditorView} p + */ + (y, gen, p) => { // wrap in blockquote + const insertPos = prng.int32(gen, 0, p.state.doc.content.size); + const overwrite = prng.int32(gen, 0, p.state.doc.content.size - insertPos); + const tr = p.state.tr; + tr.setSelection(prosemirrorState.TextSelection.create(tr.doc, insertPos, insertPos + overwrite)); + const $from = tr.selection.$from; + const $to = tr.selection.$to; + const range = $from.blockRange($to); + const wrapping = range && prosemirrorTransform.findWrapping(range, schema$1.nodes.blockquote); + if (wrapping) { + p.dispatch(tr.wrap(range, wrapping)); + } + } +]; + +/** + * @param {any} result + */ +const checkResult = result => { + for (let i = 1; i < result.testObjects.length; i++) { + const p1 = result.testObjects[i - 1].state.doc.toJSON(); + const p2 = result.testObjects[i].state.doc.toJSON(); + t.compare(p1, p2); + } +}; + +/** + * @param {t.TestCase} tc + */ +const testRepeatGenerateProsemirrorChanges2 = tc => { + checkResult(applyRandomTests(tc, pmChanges, 2, createNewProsemirrorView)); +}; + +/** + * @param {t.TestCase} tc + */ +const testRepeatGenerateProsemirrorChanges3 = tc => { + checkResult(applyRandomTests(tc, pmChanges, 3, createNewProsemirrorView)); +}; + +/** + * @param {t.TestCase} tc + */ +const testRepeatGenerateProsemirrorChanges30 = tc => { + checkResult(applyRandomTests(tc, pmChanges, 30, createNewProsemirrorView)); +}; + +/** + * @param {t.TestCase} tc + */ +const testRepeatGenerateProsemirrorChanges40 = tc => { + checkResult(applyRandomTests(tc, pmChanges, 40, createNewProsemirrorView)); +}; + +/** + * @param {t.TestCase} tc + */ +const testRepeatGenerateProsemirrorChanges70 = tc => { + checkResult(applyRandomTests(tc, pmChanges, 70, createNewProsemirrorView)); +}; + +/** + * @param {t.TestCase} tc + */ +const testRepeatGenerateProsemirrorChanges100 = tc => { + checkResult(applyRandomTests(tc, pmChanges, 100, createNewProsemirrorView)); +}; + +/** + * @param {t.TestCase} tc + */ +const testRepeatGenerateProsemirrorChanges300 = tc => { + checkResult(applyRandomTests(tc, pmChanges, 300, createNewProsemirrorView)); +}; + +var prosemirror = /*#__PURE__*/Object.freeze({ + __proto__: null, + testDocTransformation: testDocTransformation, + testEmptyNotSync: testEmptyNotSync, + testRepeatGenerateProsemirrorChanges2: testRepeatGenerateProsemirrorChanges2, + testRepeatGenerateProsemirrorChanges3: testRepeatGenerateProsemirrorChanges3, + testRepeatGenerateProsemirrorChanges30: testRepeatGenerateProsemirrorChanges30, + testRepeatGenerateProsemirrorChanges40: testRepeatGenerateProsemirrorChanges40, + testRepeatGenerateProsemirrorChanges70: testRepeatGenerateProsemirrorChanges70, + testRepeatGenerateProsemirrorChanges100: testRepeatGenerateProsemirrorChanges100, + testRepeatGenerateProsemirrorChanges300: testRepeatGenerateProsemirrorChanges300 +}); + +// @ts-nocheck + +const documentContent = fs__default['default'].readFileSync(path__default['default'].join(__dirname, '../test.html')); +const { window: window$1 } = new jsdom__default['default'].JSDOM(documentContent); + +global.window = window$1; +global.document = window$1.document; +global.innerHeight = 0; +document.getSelection = () => ({ }); + +document.createRange = () => ({ + setStart () {}, + setEnd () {}, + getClientRects () { + return { + left: 0, + top: 0, + right: 0, + bottom: 0 + } + }, + getBoundingClientRect () { + return { + left: 0, + top: 0, + right: 0, + bottom: 0 + } + } +}); + +if (environment_js.isBrowser) { + logging.createVConsole(document.body); +} +t.runTests({ + prosemirror +}).then(success => { + /* istanbul ignore next */ + if (environment_js.isNode) { + process.exit(success ? 0 : 1); + } +}); +//# sourceMappingURL=test.cjs.map diff --git a/dist/test.cjs.map b/dist/test.cjs.map new file mode 100644 index 0000000..7d0a6f7 --- /dev/null +++ b/dist/test.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"test.cjs","sources":["../node_modules/yjs/src/utils/AbstractConnector.js","../node_modules/yjs/src/utils/DeleteSet.js","../node_modules/yjs/src/utils/Doc.js","../node_modules/yjs/src/utils/UpdateDecoder.js","../node_modules/yjs/src/utils/UpdateEncoder.js","../node_modules/yjs/src/utils/encoding.js","../node_modules/yjs/src/utils/EventHandler.js","../node_modules/yjs/src/utils/ID.js","../node_modules/yjs/src/utils/isParentOf.js","../node_modules/yjs/src/utils/logging.js","../node_modules/yjs/src/utils/PermanentUserData.js","../node_modules/yjs/src/utils/RelativePosition.js","../node_modules/yjs/src/utils/Snapshot.js","../node_modules/yjs/src/utils/StructStore.js","../node_modules/yjs/src/utils/Transaction.js","../node_modules/yjs/src/utils/UndoManager.js","../node_modules/yjs/src/utils/YEvent.js","../node_modules/yjs/src/types/AbstractType.js","../node_modules/yjs/src/types/YArray.js","../node_modules/yjs/src/types/YMap.js","../node_modules/yjs/src/types/YText.js","../node_modules/yjs/src/types/YXmlFragment.js","../node_modules/yjs/src/types/YXmlElement.js","../node_modules/yjs/src/types/YXmlEvent.js","../node_modules/yjs/src/types/YXmlHook.js","../node_modules/yjs/src/types/YXmlText.js","../node_modules/yjs/src/structs/AbstractStruct.js","../node_modules/yjs/src/structs/GC.js","../node_modules/yjs/src/structs/ContentBinary.js","../node_modules/yjs/src/structs/ContentDeleted.js","../node_modules/yjs/src/structs/ContentDoc.js","../node_modules/yjs/src/structs/ContentEmbed.js","../node_modules/yjs/src/structs/ContentFormat.js","../node_modules/yjs/src/structs/ContentJSON.js","../node_modules/yjs/src/structs/ContentAny.js","../node_modules/yjs/src/structs/ContentString.js","../node_modules/yjs/src/structs/ContentType.js","../node_modules/yjs/src/structs/Item.js","../node_modules/y-protocols/sync.js","../node_modules/yjs/tests/testHelper.js","../src/plugins/keys.js","../src/plugins/sync-plugin.js","../src/lib.js","../test/complexSchema.js","../test/y-prosemirror.test.js","../test/index.node.js"],"sourcesContent":["\nimport { Observable } from 'lib0/observable.js'\n\nimport {\n Doc // eslint-disable-line\n} from '../internals.js'\n\n/**\n * This is an abstract interface that all Connectors should implement to keep them interchangeable.\n *\n * @note This interface is experimental and it is not advised to actually inherit this class.\n * It just serves as typing information.\n *\n * @extends {Observable}\n */\nexport class AbstractConnector extends Observable {\n /**\n * @param {Doc} ydoc\n * @param {any} awareness\n */\n constructor (ydoc, awareness) {\n super()\n this.doc = ydoc\n this.awareness = awareness\n }\n}\n","\nimport {\n findIndexSS,\n getState,\n splitItem,\n iterateStructs,\n AbstractUpdateDecoder, AbstractDSDecoder, AbstractDSEncoder, DSDecoderV2, DSEncoderV2, Item, GC, StructStore, Transaction, ID // eslint-disable-line\n} from '../internals.js'\n\nimport * as array from 'lib0/array.js'\nimport * as math from 'lib0/math.js'\nimport * as map from 'lib0/map.js'\nimport * as encoding from 'lib0/encoding.js'\nimport * as decoding from 'lib0/decoding.js'\n\nexport class DeleteItem {\n /**\n * @param {number} clock\n * @param {number} len\n */\n constructor (clock, len) {\n /**\n * @type {number}\n */\n this.clock = clock\n /**\n * @type {number}\n */\n this.len = len\n }\n}\n\n/**\n * We no longer maintain a DeleteStore. DeleteSet is a temporary object that is created when needed.\n * - When created in a transaction, it must only be accessed after sorting, and merging\n * - This DeleteSet is send to other clients\n * - We do not create a DeleteSet when we send a sync message. The DeleteSet message is created directly from StructStore\n * - We read a DeleteSet as part of a sync/update message. In this case the DeleteSet is already sorted and merged.\n */\nexport class DeleteSet {\n constructor () {\n /**\n * @type {Map>}\n */\n this.clients = new Map()\n }\n}\n\n/**\n * Iterate over all structs that the DeleteSet gc's.\n *\n * @param {Transaction} transaction\n * @param {DeleteSet} ds\n * @param {function(GC|Item):void} f\n *\n * @function\n */\nexport const iterateDeletedStructs = (transaction, ds, f) =>\n ds.clients.forEach((deletes, clientid) => {\n const structs = /** @type {Array} */ (transaction.doc.store.clients.get(clientid))\n for (let i = 0; i < deletes.length; i++) {\n const del = deletes[i]\n iterateStructs(transaction, structs, del.clock, del.len, f)\n }\n })\n\n/**\n * @param {Array} dis\n * @param {number} clock\n * @return {number|null}\n *\n * @private\n * @function\n */\nexport const findIndexDS = (dis, clock) => {\n let left = 0\n let right = dis.length - 1\n while (left <= right) {\n const midindex = math.floor((left + right) / 2)\n const mid = dis[midindex]\n const midclock = mid.clock\n if (midclock <= clock) {\n if (clock < midclock + mid.len) {\n return midindex\n }\n left = midindex + 1\n } else {\n right = midindex - 1\n }\n }\n return null\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {ID} id\n * @return {boolean}\n *\n * @private\n * @function\n */\nexport const isDeleted = (ds, id) => {\n const dis = ds.clients.get(id.client)\n return dis !== undefined && findIndexDS(dis, id.clock) !== null\n}\n\n/**\n * @param {DeleteSet} ds\n *\n * @private\n * @function\n */\nexport const sortAndMergeDeleteSet = ds => {\n ds.clients.forEach(dels => {\n dels.sort((a, b) => a.clock - b.clock)\n // merge items without filtering or splicing the array\n // i is the current pointer\n // j refers to the current insert position for the pointed item\n // try to merge dels[i] into dels[j-1] or set dels[j]=dels[i]\n let i, j\n for (i = 1, j = 1; i < dels.length; i++) {\n const left = dels[j - 1]\n const right = dels[i]\n if (left.clock + left.len === right.clock) {\n left.len += right.len\n } else {\n if (j < i) {\n dels[j] = right\n }\n j++\n }\n }\n dels.length = j\n })\n}\n\n/**\n * @param {Array} dss\n * @return {DeleteSet} A fresh DeleteSet\n */\nexport const mergeDeleteSets = dss => {\n const merged = new DeleteSet()\n for (let dssI = 0; dssI < dss.length; dssI++) {\n dss[dssI].clients.forEach((delsLeft, client) => {\n if (!merged.clients.has(client)) {\n // Write all missing keys from current ds and all following.\n // If merged already contains `client` current ds has already been added.\n /**\n * @type {Array}\n */\n const dels = delsLeft.slice()\n for (let i = dssI + 1; i < dss.length; i++) {\n array.appendTo(dels, dss[i].clients.get(client) || [])\n }\n merged.clients.set(client, dels)\n }\n })\n }\n sortAndMergeDeleteSet(merged)\n return merged\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {number} client\n * @param {number} clock\n * @param {number} length\n *\n * @private\n * @function\n */\nexport const addToDeleteSet = (ds, client, clock, length) => {\n map.setIfUndefined(ds.clients, client, () => []).push(new DeleteItem(clock, length))\n}\n\nexport const createDeleteSet = () => new DeleteSet()\n\n/**\n * @param {StructStore} ss\n * @return {DeleteSet} Merged and sorted DeleteSet\n *\n * @private\n * @function\n */\nexport const createDeleteSetFromStructStore = ss => {\n const ds = createDeleteSet()\n ss.clients.forEach((structs, client) => {\n /**\n * @type {Array}\n */\n const dsitems = []\n for (let i = 0; i < structs.length; i++) {\n const struct = structs[i]\n if (struct.deleted) {\n const clock = struct.id.clock\n let len = struct.length\n if (i + 1 < structs.length) {\n for (let next = structs[i + 1]; i + 1 < structs.length && next.id.clock === clock + len && next.deleted; next = structs[++i + 1]) {\n len += next.length\n }\n }\n dsitems.push(new DeleteItem(clock, len))\n }\n }\n if (dsitems.length > 0) {\n ds.clients.set(client, dsitems)\n }\n })\n return ds\n}\n\n/**\n * @param {AbstractDSEncoder} encoder\n * @param {DeleteSet} ds\n *\n * @private\n * @function\n */\nexport const writeDeleteSet = (encoder, ds) => {\n encoding.writeVarUint(encoder.restEncoder, ds.clients.size)\n ds.clients.forEach((dsitems, client) => {\n encoder.resetDsCurVal()\n encoding.writeVarUint(encoder.restEncoder, client)\n const len = dsitems.length\n encoding.writeVarUint(encoder.restEncoder, len)\n for (let i = 0; i < len; i++) {\n const item = dsitems[i]\n encoder.writeDsClock(item.clock)\n encoder.writeDsLen(item.len)\n }\n })\n}\n\n/**\n * @param {AbstractDSDecoder} decoder\n * @return {DeleteSet}\n *\n * @private\n * @function\n */\nexport const readDeleteSet = decoder => {\n const ds = new DeleteSet()\n const numClients = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numClients; i++) {\n decoder.resetDsCurVal()\n const client = decoding.readVarUint(decoder.restDecoder)\n const numberOfDeletes = decoding.readVarUint(decoder.restDecoder)\n if (numberOfDeletes > 0) {\n const dsField = map.setIfUndefined(ds.clients, client, () => [])\n for (let i = 0; i < numberOfDeletes; i++) {\n dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen()))\n }\n }\n }\n return ds\n}\n\n/**\n * @todo YDecoder also contains references to String and other Decoders. Would make sense to exchange YDecoder.toUint8Array for YDecoder.DsToUint8Array()..\n */\n\n/**\n * @param {AbstractDSDecoder} decoder\n * @param {Transaction} transaction\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nexport const readAndApplyDeleteSet = (decoder, transaction, store) => {\n const unappliedDS = new DeleteSet()\n const numClients = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numClients; i++) {\n decoder.resetDsCurVal()\n const client = decoding.readVarUint(decoder.restDecoder)\n const numberOfDeletes = decoding.readVarUint(decoder.restDecoder)\n const structs = store.clients.get(client) || []\n const state = getState(store, client)\n for (let i = 0; i < numberOfDeletes; i++) {\n const clock = decoder.readDsClock()\n const clockEnd = clock + decoder.readDsLen()\n if (clock < state) {\n if (state < clockEnd) {\n addToDeleteSet(unappliedDS, client, state, clockEnd - state)\n }\n let index = findIndexSS(structs, clock)\n /**\n * We can ignore the case of GC and Delete structs, because we are going to skip them\n * @type {Item}\n */\n // @ts-ignore\n let struct = structs[index]\n // split the first item if necessary\n if (!struct.deleted && struct.id.clock < clock) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock))\n index++ // increase we now want to use the next struct\n }\n while (index < structs.length) {\n // @ts-ignore\n struct = structs[index++]\n if (struct.id.clock < clockEnd) {\n if (!struct.deleted) {\n if (clockEnd < struct.id.clock + struct.length) {\n structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock))\n }\n struct.delete(transaction)\n }\n } else {\n break\n }\n }\n } else {\n addToDeleteSet(unappliedDS, client, clock, clockEnd - clock)\n }\n }\n }\n if (unappliedDS.clients.size > 0) {\n // TODO: no need for encoding+decoding ds anymore\n const unappliedDSEncoder = new DSEncoderV2()\n writeDeleteSet(unappliedDSEncoder, unappliedDS)\n store.pendingDeleteReaders.push(new DSDecoderV2(decoding.createDecoder((unappliedDSEncoder.toUint8Array()))))\n }\n}\n","/**\n * @module Y\n */\n\nimport {\n StructStore,\n AbstractType,\n YArray,\n YText,\n YMap,\n YXmlFragment,\n transact,\n ContentDoc, Item, Transaction, YEvent // eslint-disable-line\n} from '../internals.js'\n\nimport { Observable } from 'lib0/observable.js'\nimport * as random from 'lib0/random.js'\nimport * as map from 'lib0/map.js'\nimport * as array from 'lib0/array.js'\n\nexport const generateNewClientId = random.uint32\n\n/**\n * @typedef {Object} DocOpts\n * @property {boolean} [DocOpts.gc=true] Disable garbage collection (default: gc=true)\n * @property {function(Item):boolean} [DocOpts.gcFilter] Will be called before an Item is garbage collected. Return false to keep the Item.\n * @property {string} [DocOpts.guid] Define a globally unique identifier for this document\n * @property {any} [DocOpts.meta] Any kind of meta information you want to associate with this document. If this is a subdocument, remote peers will store the meta information as well.\n * @property {boolean} [DocOpts.autoLoad] If a subdocument, automatically load document. If this is a subdocument, remote peers will load the document as well automatically.\n */\n\n/**\n * A Yjs instance handles the state of shared data.\n * @extends Observable\n */\nexport class Doc extends Observable {\n /**\n * @param {DocOpts} [opts] configuration\n */\n constructor ({ guid = random.uuidv4(), gc = true, gcFilter = () => true, meta = null, autoLoad = false } = {}) {\n super()\n this.gc = gc\n this.gcFilter = gcFilter\n this.clientID = generateNewClientId()\n this.guid = guid\n /**\n * @type {Map>}\n */\n this.share = new Map()\n this.store = new StructStore()\n /**\n * @type {Transaction | null}\n */\n this._transaction = null\n /**\n * @type {Array}\n */\n this._transactionCleanups = []\n /**\n * @type {Set}\n */\n this.subdocs = new Set()\n /**\n * If this document is a subdocument - a document integrated into another document - then _item is defined.\n * @type {Item?}\n */\n this._item = null\n this.shouldLoad = autoLoad\n this.autoLoad = autoLoad\n this.meta = meta\n }\n\n /**\n * Notify the parent document that you request to load data into this subdocument (if it is a subdocument).\n *\n * `load()` might be used in the future to request any provider to load the most current data.\n *\n * It is safe to call `load()` multiple times.\n */\n load () {\n const item = this._item\n if (item !== null && !this.shouldLoad) {\n transact(/** @type {any} */ (item.parent).doc, transaction => {\n transaction.subdocsLoaded.add(this)\n }, null, true)\n }\n this.shouldLoad = true\n }\n\n getSubdocs () {\n return this.subdocs\n }\n\n getSubdocGuids () {\n return new Set(Array.from(this.subdocs).map(doc => doc.guid))\n }\n\n /**\n * Changes that happen inside of a transaction are bundled. This means that\n * the observer fires _after_ the transaction is finished and that all changes\n * that happened inside of the transaction are sent as one message to the\n * other peers.\n *\n * @param {function(Transaction):void} f The function that should be executed as a transaction\n * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin\n *\n * @public\n */\n transact (f, origin = null) {\n transact(this, f, origin)\n }\n\n /**\n * Define a shared data type.\n *\n * Multiple calls of `y.get(name, TypeConstructor)` yield the same result\n * and do not overwrite each other. I.e.\n * `y.define(name, Y.Array) === y.define(name, Y.Array)`\n *\n * After this method is called, the type is also available on `y.share.get(name)`.\n *\n * *Best Practices:*\n * Define all types right after the Yjs instance is created and store them in a separate object.\n * Also use the typed methods `getText(name)`, `getArray(name)`, ..\n *\n * @example\n * const y = new Y(..)\n * const appState = {\n * document: y.getText('document')\n * comments: y.getArray('comments')\n * }\n *\n * @param {string} name\n * @param {Function} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ...\n * @return {AbstractType} The created type. Constructed with TypeConstructor\n *\n * @public\n */\n get (name, TypeConstructor = AbstractType) {\n const type = map.setIfUndefined(this.share, name, () => {\n // @ts-ignore\n const t = new TypeConstructor()\n t._integrate(this, null)\n return t\n })\n const Constr = type.constructor\n if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) {\n if (Constr === AbstractType) {\n // @ts-ignore\n const t = new TypeConstructor()\n t._map = type._map\n type._map.forEach(/** @param {Item?} n */ n => {\n for (; n !== null; n = n.left) {\n // @ts-ignore\n n.parent = t\n }\n })\n t._start = type._start\n for (let n = t._start; n !== null; n = n.right) {\n n.parent = t\n }\n t._length = type._length\n this.share.set(name, t)\n t._integrate(this, null)\n return t\n } else {\n throw new Error(`Type with the name ${name} has already been defined with a different constructor`)\n }\n }\n return type\n }\n\n /**\n * @template T\n * @param {string} [name]\n * @return {YArray}\n *\n * @public\n */\n getArray (name = '') {\n // @ts-ignore\n return this.get(name, YArray)\n }\n\n /**\n * @param {string} [name]\n * @return {YText}\n *\n * @public\n */\n getText (name = '') {\n // @ts-ignore\n return this.get(name, YText)\n }\n\n /**\n * @param {string} [name]\n * @return {YMap}\n *\n * @public\n */\n getMap (name = '') {\n // @ts-ignore\n return this.get(name, YMap)\n }\n\n /**\n * @param {string} [name]\n * @return {YXmlFragment}\n *\n * @public\n */\n getXmlFragment (name = '') {\n // @ts-ignore\n return this.get(name, YXmlFragment)\n }\n\n /**\n * Converts the entire document into a js object, recursively traversing each yjs type\n *\n * @return {Object}\n */\n toJSON () {\n /**\n * @type {Object}\n */\n const doc = {}\n\n this.share.forEach((value, key) => {\n doc[key] = value.toJSON()\n })\n\n return doc\n }\n\n /**\n * Emit `destroy` event and unregister all event handlers.\n */\n destroy () {\n array.from(this.subdocs).forEach(subdoc => subdoc.destroy())\n const item = this._item\n if (item !== null) {\n this._item = null\n const content = /** @type {ContentDoc} */ (item.content)\n if (item.deleted) {\n // @ts-ignore\n content.doc = null\n } else {\n content.doc = new Doc({ guid: this.guid, ...content.opts })\n content.doc._item = item\n }\n transact(/** @type {any} */ (item).parent.doc, transaction => {\n if (!item.deleted) {\n transaction.subdocsAdded.add(content.doc)\n }\n transaction.subdocsRemoved.add(this)\n }, null, true)\n }\n this.emit('destroyed', [true])\n super.destroy()\n }\n\n /**\n * @param {string} eventName\n * @param {function(...any):any} f\n */\n on (eventName, f) {\n super.on(eventName, f)\n }\n\n /**\n * @param {string} eventName\n * @param {function} f\n */\n off (eventName, f) {\n super.off(eventName, f)\n }\n}\n","import * as buffer from 'lib0/buffer.js'\nimport * as error from 'lib0/error.js'\nimport * as decoding from 'lib0/decoding.js'\nimport {\n ID, createID\n} from '../internals.js'\n\nexport class AbstractDSDecoder {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n this.restDecoder = decoder\n error.methodUnimplemented()\n }\n\n resetDsCurVal () { }\n\n /**\n * @return {number}\n */\n readDsClock () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {number}\n */\n readDsLen () {\n error.methodUnimplemented()\n }\n}\n\nexport class AbstractUpdateDecoder extends AbstractDSDecoder {\n /**\n * @return {ID}\n */\n readLeftID () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n error.methodUnimplemented()\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n *\n * @return {number}\n */\n readClient () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {string}\n */\n readString () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {boolean} isKey\n */\n readParentInfo () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readTypeRef () {\n error.methodUnimplemented()\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number} len\n */\n readLen () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {any}\n */\n readAny () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n error.methodUnimplemented()\n }\n\n /**\n * Legacy implementation uses JSON parse. We use any-decoding in v2.\n *\n * @return {any}\n */\n readJSON () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {string}\n */\n readKey () {\n error.methodUnimplemented()\n }\n}\n\nexport class DSDecoderV1 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n this.restDecoder = decoder\n }\n\n resetDsCurVal () {\n // nop\n }\n\n /**\n * @return {number}\n */\n readDsClock () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {number}\n */\n readDsLen () {\n return decoding.readVarUint(this.restDecoder)\n }\n}\n\nexport class UpdateDecoderV1 extends DSDecoderV1 {\n /**\n * @return {ID}\n */\n readLeftID () {\n return createID(decoding.readVarUint(this.restDecoder), decoding.readVarUint(this.restDecoder))\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n return createID(decoding.readVarUint(this.restDecoder), decoding.readVarUint(this.restDecoder))\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n */\n readClient () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n return decoding.readUint8(this.restDecoder)\n }\n\n /**\n * @return {string}\n */\n readString () {\n return decoding.readVarString(this.restDecoder)\n }\n\n /**\n * @return {boolean} isKey\n */\n readParentInfo () {\n return decoding.readVarUint(this.restDecoder) === 1\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readTypeRef () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number} len\n */\n readLen () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {any}\n */\n readAny () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n return buffer.copyUint8Array(decoding.readVarUint8Array(this.restDecoder))\n }\n\n /**\n * Legacy implementation uses JSON parse. We use any-decoding in v2.\n *\n * @return {any}\n */\n readJSON () {\n return JSON.parse(decoding.readVarString(this.restDecoder))\n }\n\n /**\n * @return {string}\n */\n readKey () {\n return decoding.readVarString(this.restDecoder)\n }\n}\n\nexport class DSDecoderV2 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n this.dsCurrVal = 0\n this.restDecoder = decoder\n }\n\n resetDsCurVal () {\n this.dsCurrVal = 0\n }\n\n readDsClock () {\n this.dsCurrVal += decoding.readVarUint(this.restDecoder)\n return this.dsCurrVal\n }\n\n readDsLen () {\n const diff = decoding.readVarUint(this.restDecoder) + 1\n this.dsCurrVal += diff\n return diff\n }\n}\n\nexport class UpdateDecoderV2 extends DSDecoderV2 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n super(decoder)\n /**\n * List of cached keys. If the keys[id] does not exist, we read a new key\n * from stringEncoder and push it to keys.\n *\n * @type {Array}\n */\n this.keys = []\n decoding.readUint8(decoder) // read feature flag - currently unused\n this.keyClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.clientDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.leftClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.rightClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.infoDecoder = new decoding.RleDecoder(decoding.readVarUint8Array(decoder), decoding.readUint8)\n this.stringDecoder = new decoding.StringDecoder(decoding.readVarUint8Array(decoder))\n this.parentInfoDecoder = new decoding.RleDecoder(decoding.readVarUint8Array(decoder), decoding.readUint8)\n this.typeRefDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.lenDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder))\n }\n\n /**\n * @return {ID}\n */\n readLeftID () {\n return new ID(this.clientDecoder.read(), this.leftClockDecoder.read())\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n return new ID(this.clientDecoder.read(), this.rightClockDecoder.read())\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n */\n readClient () {\n return this.clientDecoder.read()\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n return /** @type {number} */ (this.infoDecoder.read())\n }\n\n /**\n * @return {string}\n */\n readString () {\n return this.stringDecoder.read()\n }\n\n /**\n * @return {boolean}\n */\n readParentInfo () {\n return this.parentInfoDecoder.read() === 1\n }\n\n /**\n * @return {number} An unsigned 8-bit integer\n */\n readTypeRef () {\n return this.typeRefDecoder.read()\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number}\n */\n readLen () {\n return this.lenDecoder.read()\n }\n\n /**\n * @return {any}\n */\n readAny () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n return decoding.readVarUint8Array(this.restDecoder)\n }\n\n /**\n * This is mainly here for legacy purposes.\n *\n * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.\n *\n * @return {any}\n */\n readJSON () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {string}\n */\n readKey () {\n const keyClock = this.keyClockDecoder.read()\n if (keyClock < this.keys.length) {\n return this.keys[keyClock]\n } else {\n const key = this.stringDecoder.read()\n this.keys.push(key)\n return key\n }\n }\n}\n","\nimport * as error from 'lib0/error.js'\nimport * as encoding from 'lib0/encoding.js'\n\nimport {\n ID // eslint-disable-line\n} from '../internals.js'\n\nexport class AbstractDSEncoder {\n constructor () {\n this.restEncoder = encoding.createEncoder()\n }\n\n /**\n * @return {Uint8Array}\n */\n toUint8Array () {\n error.methodUnimplemented()\n }\n\n /**\n * Resets the ds value to 0.\n * The v2 encoder uses this information to reset the initial diff value.\n */\n resetDsCurVal () { }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) { }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) { }\n}\n\nexport class AbstractUpdateEncoder extends AbstractDSEncoder {\n /**\n * @return {Uint8Array}\n */\n toUint8Array () {\n error.methodUnimplemented()\n }\n\n /**\n * @param {ID} id\n */\n writeLeftID (id) { }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) { }\n\n /**\n * Use writeClient and writeClock instead of writeID if possible.\n * @param {number} client\n */\n writeClient (client) { }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) { }\n\n /**\n * @param {string} s\n */\n writeString (s) { }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) { }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) { }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) { }\n\n /**\n * @param {any} any\n */\n writeAny (any) { }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) { }\n\n /**\n * @param {any} embed\n */\n writeJSON (embed) { }\n\n /**\n * @param {string} key\n */\n writeKey (key) { }\n}\n\nexport class DSEncoderV1 {\n constructor () {\n this.restEncoder = new encoding.Encoder()\n }\n\n toUint8Array () {\n return encoding.toUint8Array(this.restEncoder)\n }\n\n resetDsCurVal () {\n // nop\n }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) {\n encoding.writeVarUint(this.restEncoder, clock)\n }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) {\n encoding.writeVarUint(this.restEncoder, len)\n }\n}\n\nexport class UpdateEncoderV1 extends DSEncoderV1 {\n /**\n * @param {ID} id\n */\n writeLeftID (id) {\n encoding.writeVarUint(this.restEncoder, id.client)\n encoding.writeVarUint(this.restEncoder, id.clock)\n }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) {\n encoding.writeVarUint(this.restEncoder, id.client)\n encoding.writeVarUint(this.restEncoder, id.clock)\n }\n\n /**\n * Use writeClient and writeClock instead of writeID if possible.\n * @param {number} client\n */\n writeClient (client) {\n encoding.writeVarUint(this.restEncoder, client)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) {\n encoding.writeUint8(this.restEncoder, info)\n }\n\n /**\n * @param {string} s\n */\n writeString (s) {\n encoding.writeVarString(this.restEncoder, s)\n }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) {\n encoding.writeVarUint(this.restEncoder, isYKey ? 1 : 0)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) {\n encoding.writeVarUint(this.restEncoder, info)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) {\n encoding.writeVarUint(this.restEncoder, len)\n }\n\n /**\n * @param {any} any\n */\n writeAny (any) {\n encoding.writeAny(this.restEncoder, any)\n }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) {\n encoding.writeVarUint8Array(this.restEncoder, buf)\n }\n\n /**\n * @param {any} embed\n */\n writeJSON (embed) {\n encoding.writeVarString(this.restEncoder, JSON.stringify(embed))\n }\n\n /**\n * @param {string} key\n */\n writeKey (key) {\n encoding.writeVarString(this.restEncoder, key)\n }\n}\n\nexport class DSEncoderV2 {\n constructor () {\n this.restEncoder = new encoding.Encoder() // encodes all the rest / non-optimized\n this.dsCurrVal = 0\n }\n\n toUint8Array () {\n return encoding.toUint8Array(this.restEncoder)\n }\n\n resetDsCurVal () {\n this.dsCurrVal = 0\n }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) {\n const diff = clock - this.dsCurrVal\n this.dsCurrVal = clock\n encoding.writeVarUint(this.restEncoder, diff)\n }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) {\n if (len === 0) {\n error.unexpectedCase()\n }\n encoding.writeVarUint(this.restEncoder, len - 1)\n this.dsCurrVal += len\n }\n}\n\nexport class UpdateEncoderV2 extends DSEncoderV2 {\n constructor () {\n super()\n /**\n * @type {Map}\n */\n this.keyMap = new Map()\n /**\n * Refers to the next uniqe key-identifier to me used.\n * See writeKey method for more information.\n *\n * @type {number}\n */\n this.keyClock = 0\n this.keyClockEncoder = new encoding.IntDiffOptRleEncoder()\n this.clientEncoder = new encoding.UintOptRleEncoder()\n this.leftClockEncoder = new encoding.IntDiffOptRleEncoder()\n this.rightClockEncoder = new encoding.IntDiffOptRleEncoder()\n this.infoEncoder = new encoding.RleEncoder(encoding.writeUint8)\n this.stringEncoder = new encoding.StringEncoder()\n this.parentInfoEncoder = new encoding.RleEncoder(encoding.writeUint8)\n this.typeRefEncoder = new encoding.UintOptRleEncoder()\n this.lenEncoder = new encoding.UintOptRleEncoder()\n }\n\n toUint8Array () {\n const encoder = encoding.createEncoder()\n encoding.writeUint8(encoder, 0) // this is a feature flag that we might use in the future\n encoding.writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.clientEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, encoding.toUint8Array(this.infoEncoder))\n encoding.writeVarUint8Array(encoder, this.stringEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, encoding.toUint8Array(this.parentInfoEncoder))\n encoding.writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.lenEncoder.toUint8Array())\n // @note The rest encoder is appended! (note the missing var)\n encoding.writeUint8Array(encoder, encoding.toUint8Array(this.restEncoder))\n return encoding.toUint8Array(encoder)\n }\n\n /**\n * @param {ID} id\n */\n writeLeftID (id) {\n this.clientEncoder.write(id.client)\n this.leftClockEncoder.write(id.clock)\n }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) {\n this.clientEncoder.write(id.client)\n this.rightClockEncoder.write(id.clock)\n }\n\n /**\n * @param {number} client\n */\n writeClient (client) {\n this.clientEncoder.write(client)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) {\n this.infoEncoder.write(info)\n }\n\n /**\n * @param {string} s\n */\n writeString (s) {\n this.stringEncoder.write(s)\n }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) {\n this.parentInfoEncoder.write(isYKey ? 1 : 0)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) {\n this.typeRefEncoder.write(info)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) {\n this.lenEncoder.write(len)\n }\n\n /**\n * @param {any} any\n */\n writeAny (any) {\n encoding.writeAny(this.restEncoder, any)\n }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) {\n encoding.writeVarUint8Array(this.restEncoder, buf)\n }\n\n /**\n * This is mainly here for legacy purposes.\n *\n * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.\n *\n * @param {any} embed\n */\n writeJSON (embed) {\n encoding.writeAny(this.restEncoder, embed)\n }\n\n /**\n * Property keys are often reused. For example, in y-prosemirror the key `bold` might\n * occur very often. For a 3d application, the key `position` might occur very often.\n *\n * We cache these keys in a Map and refer to them via a unique number.\n *\n * @param {string} key\n */\n writeKey (key) {\n const clock = this.keyMap.get(key)\n if (clock === undefined) {\n this.keyClockEncoder.write(this.keyClock++)\n this.stringEncoder.write(key)\n } else {\n this.keyClockEncoder.write(this.keyClock++)\n }\n }\n}\n","\n/**\n * @module encoding\n */\n/*\n * We use the first five bits in the info flag for determining the type of the struct.\n *\n * 0: GC\n * 1: Item with Deleted content\n * 2: Item with JSON content\n * 3: Item with Binary content\n * 4: Item with String content\n * 5: Item with Embed content (for richtext content)\n * 6: Item with Format content (a formatting marker for richtext content)\n * 7: Item with Type\n */\n\nimport {\n findIndexSS,\n getState,\n createID,\n getStateVector,\n readAndApplyDeleteSet,\n writeDeleteSet,\n createDeleteSetFromStructStore,\n transact,\n readItemContent,\n UpdateDecoderV1,\n UpdateDecoderV2,\n UpdateEncoderV1,\n UpdateEncoderV2,\n DSDecoderV2,\n DSEncoderV2,\n DSDecoderV1,\n DSEncoderV1,\n AbstractDSEncoder, AbstractDSDecoder, AbstractUpdateEncoder, AbstractUpdateDecoder, AbstractContent, Doc, Transaction, GC, Item, StructStore, ID // eslint-disable-line\n} from '../internals.js'\n\nimport * as encoding from 'lib0/encoding.js'\nimport * as decoding from 'lib0/decoding.js'\nimport * as binary from 'lib0/binary.js'\nimport * as map from 'lib0/map.js'\n\nexport let DefaultDSEncoder = DSEncoderV1\nexport let DefaultDSDecoder = DSDecoderV1\nexport let DefaultUpdateEncoder = UpdateEncoderV1\nexport let DefaultUpdateDecoder = UpdateDecoderV1\n\nexport const useV1Encoding = () => {\n DefaultDSEncoder = DSEncoderV1\n DefaultDSDecoder = DSDecoderV1\n DefaultUpdateEncoder = UpdateEncoderV1\n DefaultUpdateDecoder = UpdateDecoderV1\n}\n\nexport const useV2Encoding = () => {\n DefaultDSEncoder = DSEncoderV2\n DefaultDSDecoder = DSDecoderV2\n DefaultUpdateEncoder = UpdateEncoderV2\n DefaultUpdateDecoder = UpdateDecoderV2\n}\n\n/**\n * @param {AbstractUpdateEncoder} encoder\n * @param {Array} structs All structs by `client`\n * @param {number} client\n * @param {number} clock write structs starting with `ID(client,clock)`\n *\n * @function\n */\nconst writeStructs = (encoder, structs, client, clock) => {\n // write first id\n const startNewStructs = findIndexSS(structs, clock)\n // write # encoded structs\n encoding.writeVarUint(encoder.restEncoder, structs.length - startNewStructs)\n encoder.writeClient(client)\n encoding.writeVarUint(encoder.restEncoder, clock)\n const firstStruct = structs[startNewStructs]\n // write first struct with an offset\n firstStruct.write(encoder, clock - firstStruct.id.clock)\n for (let i = startNewStructs + 1; i < structs.length; i++) {\n structs[i].write(encoder, 0)\n }\n}\n\n/**\n * @param {AbstractUpdateEncoder} encoder\n * @param {StructStore} store\n * @param {Map} _sm\n *\n * @private\n * @function\n */\nexport const writeClientsStructs = (encoder, store, _sm) => {\n // we filter all valid _sm entries into sm\n const sm = new Map()\n _sm.forEach((clock, client) => {\n // only write if new structs are available\n if (getState(store, client) > clock) {\n sm.set(client, clock)\n }\n })\n getStateVector(store).forEach((clock, client) => {\n if (!_sm.has(client)) {\n sm.set(client, 0)\n }\n })\n // write # states that were updated\n encoding.writeVarUint(encoder.restEncoder, sm.size)\n // Write items with higher client ids first\n // This heavily improves the conflict algorithm.\n Array.from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {\n // @ts-ignore\n writeStructs(encoder, store.clients.get(client), client, clock)\n })\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder The decoder object to read data from.\n * @param {Map>} clientRefs\n * @param {Doc} doc\n * @return {Map>}\n *\n * @private\n * @function\n */\nexport const readClientsStructRefs = (decoder, clientRefs, doc) => {\n const numOfStateUpdates = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numOfStateUpdates; i++) {\n const numberOfStructs = decoding.readVarUint(decoder.restDecoder)\n /**\n * @type {Array}\n */\n const refs = new Array(numberOfStructs)\n const client = decoder.readClient()\n let clock = decoding.readVarUint(decoder.restDecoder)\n // const start = performance.now()\n clientRefs.set(client, refs)\n for (let i = 0; i < numberOfStructs; i++) {\n const info = decoder.readInfo()\n if ((binary.BITS5 & info) !== 0) {\n /**\n * The optimized implementation doesn't use any variables because inlining variables is faster.\n * Below a non-optimized version is shown that implements the basic algorithm with\n * a few comments\n */\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const struct = new Item(\n createID(client, clock),\n null, // leftd\n (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null, // origin\n null, // right\n (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null, // right origin\n cantCopyParentInfo ? (decoder.readParentInfo() ? doc.get(decoder.readString()) : decoder.readLeftID()) : null, // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n )\n /* A non-optimized implementation of the above algorithm:\n\n // The item that was originally to the left of this item.\n const origin = (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null\n // The item that was originally to the right of this item.\n const rightOrigin = (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0\n const hasParentYKey = cantCopyParentInfo ? decoder.readParentInfo() : false\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const parentYKey = cantCopyParentInfo && hasParentYKey ? decoder.readString() : null\n\n const struct = new Item(\n createID(client, clock),\n null, // leftd\n origin, // origin\n null, // right\n rightOrigin, // right origin\n cantCopyParentInfo && !hasParentYKey ? decoder.readLeftID() : (parentYKey !== null ? doc.get(parentYKey) : null), // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n )\n */\n refs[i] = struct\n clock += struct.length\n } else {\n const len = decoder.readLen()\n refs[i] = new GC(createID(client, clock), len)\n clock += len\n }\n }\n // console.log('time to read: ', performance.now() - start) // @todo remove\n }\n return clientRefs\n}\n\n/**\n * Resume computing structs generated by struct readers.\n *\n * While there is something to do, we integrate structs in this order\n * 1. top element on stack, if stack is not empty\n * 2. next element from current struct reader (if empty, use next struct reader)\n *\n * If struct causally depends on another struct (ref.missing), we put next reader of\n * `ref.id.client` on top of stack.\n *\n * At some point we find a struct that has no causal dependencies,\n * then we start emptying the stack.\n *\n * It is not possible to have circles: i.e. struct1 (from client1) depends on struct2 (from client2)\n * depends on struct3 (from client1). Therefore the max stack size is eqaul to `structReaders.length`.\n *\n * This method is implemented in a way so that we can resume computation if this update\n * causally depends on another update.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nconst resumeStructIntegration = (transaction, store) => {\n const stack = store.pendingStack // @todo don't forget to append stackhead at the end\n const clientsStructRefs = store.pendingClientsStructRefs\n // sort them so that we take the higher id first, in case of conflicts the lower id will probably not conflict with the id from the higher user.\n const clientsStructRefsIds = Array.from(clientsStructRefs.keys()).sort((a, b) => a - b)\n if (clientsStructRefsIds.length === 0) {\n return\n }\n const getNextStructTarget = () => {\n let nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]))\n while (nextStructsTarget.refs.length === nextStructsTarget.i) {\n clientsStructRefsIds.pop()\n if (clientsStructRefsIds.length > 0) {\n nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]))\n } else {\n store.pendingClientsStructRefs.clear()\n return null\n }\n }\n return nextStructsTarget\n }\n let curStructsTarget = getNextStructTarget()\n if (curStructsTarget === null && stack.length === 0) {\n return\n }\n /**\n * @type {GC|Item}\n */\n let stackHead = stack.length > 0\n ? /** @type {GC|Item} */ (stack.pop())\n : /** @type {any} */ (curStructsTarget).refs[/** @type {any} */ (curStructsTarget).i++]\n // caching the state because it is used very often\n const state = new Map()\n // iterate over all struct readers until we are done\n while (true) {\n const localClock = map.setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client))\n const offset = stackHead.id.clock < localClock ? localClock - stackHead.id.clock : 0\n if (stackHead.id.clock + offset !== localClock) {\n // A previous message from this client is missing\n // check if there is a pending structRef with a smaller clock and switch them\n /**\n * @type {{ refs: Array, i: number }}\n */\n const structRefs = clientsStructRefs.get(stackHead.id.client) || { refs: [], i: 0 }\n if (structRefs.refs.length !== structRefs.i) {\n const r = structRefs.refs[structRefs.i]\n if (r.id.clock < stackHead.id.clock) {\n // put ref with smaller clock on stack instead and continue\n structRefs.refs[structRefs.i] = stackHead\n stackHead = r\n // sort the set because this approach might bring the list out of order\n structRefs.refs = structRefs.refs.slice(structRefs.i).sort((r1, r2) => r1.id.clock - r2.id.clock)\n structRefs.i = 0\n continue\n }\n }\n // wait until missing struct is available\n stack.push(stackHead)\n return\n }\n const missing = stackHead.getMissing(transaction, store)\n if (missing === null) {\n if (offset === 0 || offset < stackHead.length) {\n stackHead.integrate(transaction, offset)\n state.set(stackHead.id.client, stackHead.id.clock + stackHead.length)\n }\n // iterate to next stackHead\n if (stack.length > 0) {\n stackHead = /** @type {GC|Item} */ (stack.pop())\n } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) {\n stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++])\n } else {\n curStructsTarget = getNextStructTarget()\n if (curStructsTarget === null) {\n // we are done!\n break\n } else {\n stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++])\n }\n }\n } else {\n // get the struct reader that has the missing struct\n /**\n * @type {{ refs: Array, i: number }}\n */\n const structRefs = clientsStructRefs.get(missing) || { refs: [], i: 0 }\n if (structRefs.refs.length === structRefs.i) {\n // This update message causally depends on another update message.\n stack.push(stackHead)\n return\n }\n stack.push(stackHead)\n stackHead = structRefs.refs[structRefs.i++]\n }\n }\n store.pendingClientsStructRefs.clear()\n}\n\n/**\n * @param {Transaction} transaction\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nexport const tryResumePendingDeleteReaders = (transaction, store) => {\n const pendingReaders = store.pendingDeleteReaders\n store.pendingDeleteReaders = []\n for (let i = 0; i < pendingReaders.length; i++) {\n readAndApplyDeleteSet(pendingReaders[i], transaction, store)\n }\n}\n\n/**\n * @param {AbstractUpdateEncoder} encoder\n * @param {Transaction} transaction\n *\n * @private\n * @function\n */\nexport const writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState)\n\n/**\n * @param {StructStore} store\n * @param {Map>} clientsStructsRefs\n *\n * @private\n * @function\n */\nconst mergeReadStructsIntoPendingReads = (store, clientsStructsRefs) => {\n const pendingClientsStructRefs = store.pendingClientsStructRefs\n clientsStructsRefs.forEach((structRefs, client) => {\n const pendingStructRefs = pendingClientsStructRefs.get(client)\n if (pendingStructRefs === undefined) {\n pendingClientsStructRefs.set(client, { refs: structRefs, i: 0 })\n } else {\n // merge into existing structRefs\n const merged = pendingStructRefs.i > 0 ? pendingStructRefs.refs.slice(pendingStructRefs.i) : pendingStructRefs.refs\n for (let i = 0; i < structRefs.length; i++) {\n merged.push(structRefs[i])\n }\n pendingStructRefs.i = 0\n pendingStructRefs.refs = merged.sort((r1, r2) => r1.id.clock - r2.id.clock)\n }\n })\n}\n\n/**\n * @param {Map,i:number}>} pendingClientsStructRefs\n */\nconst cleanupPendingStructs = pendingClientsStructRefs => {\n // cleanup pendingClientsStructs if not fully finished\n pendingClientsStructRefs.forEach((refs, client) => {\n if (refs.i === refs.refs.length) {\n pendingClientsStructRefs.delete(client)\n } else {\n refs.refs.splice(0, refs.i)\n refs.i = 0\n }\n })\n}\n\n/**\n * Read the next Item in a Decoder and fill this Item with the read data.\n *\n * This is called when data is received from a remote peer.\n *\n * @param {AbstractUpdateDecoder} decoder The decoder object to read data from.\n * @param {Transaction} transaction\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nexport const readStructs = (decoder, transaction, store) => {\n const clientsStructRefs = new Map()\n // let start = performance.now()\n readClientsStructRefs(decoder, clientsStructRefs, transaction.doc)\n // console.log('time to read structs: ', performance.now() - start) // @todo remove\n // start = performance.now()\n mergeReadStructsIntoPendingReads(store, clientsStructRefs)\n // console.log('time to merge: ', performance.now() - start) // @todo remove\n // start = performance.now()\n resumeStructIntegration(transaction, store)\n // console.log('time to integrate: ', performance.now() - start) // @todo remove\n // start = performance.now()\n cleanupPendingStructs(store.pendingClientsStructRefs)\n // console.log('time to cleanup: ', performance.now() - start) // @todo remove\n // start = performance.now()\n tryResumePendingDeleteReaders(transaction, store)\n // console.log('time to resume delete readers: ', performance.now() - start) // @todo remove\n // start = performance.now()\n}\n\n/**\n * Read and apply a document update.\n *\n * This function has the same effect as `applyUpdate` but accepts an decoder.\n *\n * @param {decoding.Decoder} decoder\n * @param {Doc} ydoc\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n * @param {AbstractUpdateDecoder} [structDecoder]\n *\n * @function\n */\nexport const readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) =>\n transact(ydoc, transaction => {\n readStructs(structDecoder, transaction, ydoc.store)\n readAndApplyDeleteSet(structDecoder, transaction, ydoc.store)\n }, transactionOrigin, false)\n\n/**\n * Read and apply a document update.\n *\n * This function has the same effect as `applyUpdate` but accepts an decoder.\n *\n * @param {decoding.Decoder} decoder\n * @param {Doc} ydoc\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n *\n * @function\n */\nexport const readUpdate = (decoder, ydoc, transactionOrigin) => readUpdateV2(decoder, ydoc, transactionOrigin, new DefaultUpdateDecoder(decoder))\n\n/**\n * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.\n *\n * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.\n *\n * @param {Doc} ydoc\n * @param {Uint8Array} update\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder]\n *\n * @function\n */\nexport const applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => {\n const decoder = decoding.createDecoder(update)\n readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder))\n}\n\n/**\n * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.\n *\n * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.\n *\n * @param {Doc} ydoc\n * @param {Uint8Array} update\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n *\n * @function\n */\nexport const applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, DefaultUpdateDecoder)\n\n/**\n * Write all the document as a single update message. If you specify the state of the remote client (`targetStateVector`) it will\n * only write the operations that are missing.\n *\n * @param {AbstractUpdateEncoder} encoder\n * @param {Doc} doc\n * @param {Map} [targetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n *\n * @function\n */\nexport const writeStateAsUpdate = (encoder, doc, targetStateVector = new Map()) => {\n writeClientsStructs(encoder, doc.store, targetStateVector)\n writeDeleteSet(encoder, createDeleteSetFromStructStore(doc.store))\n}\n\n/**\n * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will\n * only write the operations that are missing.\n *\n * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder\n *\n * @param {Doc} doc\n * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n * @param {AbstractUpdateEncoder} [encoder]\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateAsUpdateV2 = (doc, encodedTargetStateVector, encoder = new UpdateEncoderV2()) => {\n const targetStateVector = encodedTargetStateVector == null ? new Map() : decodeStateVector(encodedTargetStateVector)\n writeStateAsUpdate(encoder, doc, targetStateVector)\n return encoder.toUint8Array()\n}\n\n/**\n * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will\n * only write the operations that are missing.\n *\n * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder\n *\n * @param {Doc} doc\n * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateAsUpdate = (doc, encodedTargetStateVector) => encodeStateAsUpdateV2(doc, encodedTargetStateVector, new DefaultUpdateEncoder())\n\n/**\n * Read state vector from Decoder and return as Map\n *\n * @param {AbstractDSDecoder} decoder\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nexport const readStateVector = decoder => {\n const ss = new Map()\n const ssLength = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < ssLength; i++) {\n const client = decoding.readVarUint(decoder.restDecoder)\n const clock = decoding.readVarUint(decoder.restDecoder)\n ss.set(client, clock)\n }\n return ss\n}\n\n/**\n * Read decodedState and return State as Map.\n *\n * @param {Uint8Array} decodedState\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nexport const decodeStateVectorV2 = decodedState => readStateVector(new DSDecoderV2(decoding.createDecoder(decodedState)))\n\n/**\n * Read decodedState and return State as Map.\n *\n * @param {Uint8Array} decodedState\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nexport const decodeStateVector = decodedState => readStateVector(new DefaultDSDecoder(decoding.createDecoder(decodedState)))\n\n/**\n * @param {AbstractDSEncoder} encoder\n * @param {Map} sv\n * @function\n */\nexport const writeStateVector = (encoder, sv) => {\n encoding.writeVarUint(encoder.restEncoder, sv.size)\n sv.forEach((clock, client) => {\n encoding.writeVarUint(encoder.restEncoder, client) // @todo use a special client decoder that is based on mapping\n encoding.writeVarUint(encoder.restEncoder, clock)\n })\n return encoder\n}\n\n/**\n * @param {AbstractDSEncoder} encoder\n * @param {Doc} doc\n *\n * @function\n */\nexport const writeDocumentStateVector = (encoder, doc) => writeStateVector(encoder, getStateVector(doc.store))\n\n/**\n * Encode State as Uint8Array.\n *\n * @param {Doc} doc\n * @param {AbstractDSEncoder} [encoder]\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateVectorV2 = (doc, encoder = new DSEncoderV2()) => {\n writeDocumentStateVector(encoder, doc)\n return encoder.toUint8Array()\n}\n\n/**\n * Encode State as Uint8Array.\n *\n * @param {Doc} doc\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateVector = doc => encodeStateVectorV2(doc, new DefaultDSEncoder())\n","import * as f from 'lib0/function.js'\n\n/**\n * General event handler implementation.\n *\n * @template ARG0, ARG1\n *\n * @private\n */\nexport class EventHandler {\n constructor () {\n /**\n * @type {Array}\n */\n this.l = []\n }\n}\n\n/**\n * @template ARG0,ARG1\n * @returns {EventHandler}\n *\n * @private\n * @function\n */\nexport const createEventHandler = () => new EventHandler()\n\n/**\n * Adds an event listener that is called when\n * {@link EventHandler#callEventListeners} is called.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {function(ARG0,ARG1):void} f The event handler.\n *\n * @private\n * @function\n */\nexport const addEventHandlerListener = (eventHandler, f) =>\n eventHandler.l.push(f)\n\n/**\n * Removes an event listener.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {function(ARG0,ARG1):void} f The event handler that was added with\n * {@link EventHandler#addEventListener}\n *\n * @private\n * @function\n */\nexport const removeEventHandlerListener = (eventHandler, f) => {\n const l = eventHandler.l\n const len = l.length\n eventHandler.l = l.filter(g => f !== g)\n if (len === eventHandler.l.length) {\n console.error('[yjs] Tried to remove event handler that doesn\\'t exist.')\n }\n}\n\n/**\n * Removes all event listeners.\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n *\n * @private\n * @function\n */\nexport const removeAllEventHandlerListeners = eventHandler => {\n eventHandler.l.length = 0\n}\n\n/**\n * Call all event listeners that were added via\n * {@link EventHandler#addEventListener}.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {ARG0} arg0\n * @param {ARG1} arg1\n *\n * @private\n * @function\n */\nexport const callEventHandlerListeners = (eventHandler, arg0, arg1) =>\n f.callAll(eventHandler.l, [arg0, arg1])\n","\nimport { AbstractType } from '../internals.js' // eslint-disable-line\n\nimport * as decoding from 'lib0/decoding.js'\nimport * as encoding from 'lib0/encoding.js'\nimport * as error from 'lib0/error.js'\n\nexport class ID {\n /**\n * @param {number} client client id\n * @param {number} clock unique per client id, continuous number\n */\n constructor (client, clock) {\n /**\n * Client id\n * @type {number}\n */\n this.client = client\n /**\n * unique per client id, continuous number\n * @type {number}\n */\n this.clock = clock\n }\n}\n\n/**\n * @param {ID | null} a\n * @param {ID | null} b\n * @return {boolean}\n *\n * @function\n */\nexport const compareIDs = (a, b) => a === b || (a !== null && b !== null && a.client === b.client && a.clock === b.clock)\n\n/**\n * @param {number} client\n * @param {number} clock\n *\n * @private\n * @function\n */\nexport const createID = (client, clock) => new ID(client, clock)\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {ID} id\n *\n * @private\n * @function\n */\nexport const writeID = (encoder, id) => {\n encoding.writeVarUint(encoder, id.client)\n encoding.writeVarUint(encoder, id.clock)\n}\n\n/**\n * Read ID.\n * * If first varUint read is 0xFFFFFF a RootID is returned.\n * * Otherwise an ID is returned\n *\n * @param {decoding.Decoder} decoder\n * @return {ID}\n *\n * @private\n * @function\n */\nexport const readID = decoder =>\n createID(decoding.readVarUint(decoder), decoding.readVarUint(decoder))\n\n/**\n * The top types are mapped from y.share.get(keyname) => type.\n * `type` does not store any information about the `keyname`.\n * This function finds the correct `keyname` for `type` and throws otherwise.\n *\n * @param {AbstractType} type\n * @return {string}\n *\n * @private\n * @function\n */\nexport const findRootTypeKey = type => {\n // @ts-ignore _y must be defined, otherwise unexpected case\n for (const [key, value] of type.doc.share.entries()) {\n if (value === type) {\n return key\n }\n }\n throw error.unexpectedCase()\n}\n","\nimport { AbstractType, Item } from '../internals.js' // eslint-disable-line\n\n/**\n * Check if `parent` is a parent of `child`.\n *\n * @param {AbstractType} parent\n * @param {Item|null} child\n * @return {Boolean} Whether `parent` is a parent of `child`.\n *\n * @private\n * @function\n */\nexport const isParentOf = (parent, child) => {\n while (child !== null) {\n if (child.parent === parent) {\n return true\n }\n child = /** @type {AbstractType} */ (child.parent)._item\n }\n return false\n}\n","\nimport {\n AbstractType // eslint-disable-line\n} from '../internals.js'\n\n/**\n * Convenient helper to log type information.\n *\n * Do not use in productive systems as the output can be immense!\n *\n * @param {AbstractType} type\n */\nexport const logType = type => {\n const res = []\n let n = type._start\n while (n) {\n res.push(n)\n n = n.right\n }\n console.log('Children: ', res)\n console.log('Children content: ', res.filter(m => !m.deleted).map(m => m.content))\n}\n","\nimport {\n YArray,\n YMap,\n readDeleteSet,\n writeDeleteSet,\n createDeleteSet,\n DSEncoderV1, DSDecoderV1, ID, DeleteSet, YArrayEvent, Transaction, Doc // eslint-disable-line\n} from '../internals.js'\n\nimport * as decoding from 'lib0/decoding.js'\n\nimport { mergeDeleteSets, isDeleted } from './DeleteSet.js'\n\nexport class PermanentUserData {\n /**\n * @param {Doc} doc\n * @param {YMap} [storeType]\n */\n constructor (doc, storeType = doc.getMap('users')) {\n /**\n * @type {Map}\n */\n const dss = new Map()\n this.yusers = storeType\n this.doc = doc\n /**\n * Maps from clientid to userDescription\n *\n * @type {Map}\n */\n this.clients = new Map()\n this.dss = dss\n /**\n * @param {YMap} user\n * @param {string} userDescription\n */\n const initUser = (user, userDescription) => {\n /**\n * @type {YArray}\n */\n const ds = user.get('ds')\n const ids = user.get('ids')\n const addClientId = /** @param {number} clientid */ clientid => this.clients.set(clientid, userDescription)\n ds.observe(/** @param {YArrayEvent} event */ event => {\n event.changes.added.forEach(item => {\n item.content.getContent().forEach(encodedDs => {\n if (encodedDs instanceof Uint8Array) {\n this.dss.set(userDescription, mergeDeleteSets([this.dss.get(userDescription) || createDeleteSet(), readDeleteSet(new DSDecoderV1(decoding.createDecoder(encodedDs)))]))\n }\n })\n })\n })\n this.dss.set(userDescription, mergeDeleteSets(ds.map(encodedDs => readDeleteSet(new DSDecoderV1(decoding.createDecoder(encodedDs))))))\n ids.observe(/** @param {YArrayEvent} event */ event =>\n event.changes.added.forEach(item => item.content.getContent().forEach(addClientId))\n )\n ids.forEach(addClientId)\n }\n // observe users\n storeType.observe(event => {\n event.keysChanged.forEach(userDescription =>\n initUser(storeType.get(userDescription), userDescription)\n )\n })\n // add intial data\n storeType.forEach(initUser)\n }\n\n /**\n * @param {Doc} doc\n * @param {number} clientid\n * @param {string} userDescription\n * @param {Object} [conf]\n * @param {function(Transaction, DeleteSet):boolean} [conf.filter]\n */\n setUserMapping (doc, clientid, userDescription, { filter = () => true } = {}) {\n const users = this.yusers\n let user = users.get(userDescription)\n if (!user) {\n user = new YMap()\n user.set('ids', new YArray())\n user.set('ds', new YArray())\n users.set(userDescription, user)\n }\n user.get('ids').push([clientid])\n users.observe(event => {\n setTimeout(() => {\n const userOverwrite = users.get(userDescription)\n if (userOverwrite !== user) {\n // user was overwritten, port all data over to the next user object\n // @todo Experiment with Y.Sets here\n user = userOverwrite\n // @todo iterate over old type\n this.clients.forEach((_userDescription, clientid) => {\n if (userDescription === _userDescription) {\n user.get('ids').push([clientid])\n }\n })\n const encoder = new DSEncoderV1()\n const ds = this.dss.get(userDescription)\n if (ds) {\n writeDeleteSet(encoder, ds)\n user.get('ds').push([encoder.toUint8Array()])\n }\n }\n }, 0)\n })\n doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => {\n setTimeout(() => {\n const yds = user.get('ds')\n const ds = transaction.deleteSet\n if (transaction.local && ds.clients.size > 0 && filter(transaction, ds)) {\n const encoder = new DSEncoderV1()\n writeDeleteSet(encoder, ds)\n yds.push([encoder.toUint8Array()])\n }\n })\n })\n }\n\n /**\n * @param {number} clientid\n * @return {any}\n */\n getUserByClientId (clientid) {\n return this.clients.get(clientid) || null\n }\n\n /**\n * @param {ID} id\n * @return {string | null}\n */\n getUserByDeletedId (id) {\n for (const [userDescription, ds] of this.dss.entries()) {\n if (isDeleted(ds, id)) {\n return userDescription\n }\n }\n return null\n }\n}\n","\nimport {\n writeID,\n readID,\n compareIDs,\n getState,\n findRootTypeKey,\n Item,\n createID,\n ContentType,\n followRedone,\n ID, Doc, AbstractType // eslint-disable-line\n} from '../internals.js'\n\nimport * as encoding from 'lib0/encoding.js'\nimport * as decoding from 'lib0/decoding.js'\nimport * as error from 'lib0/error.js'\n\n/**\n * A relative position is based on the Yjs model and is not affected by document changes.\n * E.g. If you place a relative position before a certain character, it will always point to this character.\n * If you place a relative position at the end of a type, it will always point to the end of the type.\n *\n * A numeric position is often unsuited for user selections, because it does not change when content is inserted\n * before or after.\n *\n * ```Insert(0, 'x')('a|bc') = 'xa|bc'``` Where | is the relative position.\n *\n * One of the properties must be defined.\n *\n * @example\n * // Current cursor position is at position 10\n * const relativePosition = createRelativePositionFromIndex(yText, 10)\n * // modify yText\n * yText.insert(0, 'abc')\n * yText.delete(3, 10)\n * // Compute the cursor position\n * const absolutePosition = createAbsolutePositionFromRelativePosition(y, relativePosition)\n * absolutePosition.type === yText // => true\n * console.log('cursor location is ' + absolutePosition.index) // => cursor location is 3\n *\n */\nexport class RelativePosition {\n /**\n * @param {ID|null} type\n * @param {string|null} tname\n * @param {ID|null} item\n */\n constructor (type, tname, item) {\n /**\n * @type {ID|null}\n */\n this.type = type\n /**\n * @type {string|null}\n */\n this.tname = tname\n /**\n * @type {ID | null}\n */\n this.item = item\n }\n}\n\n/**\n * @param {any} json\n * @return {RelativePosition}\n *\n * @function\n */\nexport const createRelativePositionFromJSON = json => new RelativePosition(json.type == null ? null : createID(json.type.client, json.type.clock), json.tname || null, json.item == null ? null : createID(json.item.client, json.item.clock))\n\nexport class AbsolutePosition {\n /**\n * @param {AbstractType} type\n * @param {number} index\n */\n constructor (type, index) {\n /**\n * @type {AbstractType}\n */\n this.type = type\n /**\n * @type {number}\n */\n this.index = index\n }\n}\n\n/**\n * @param {AbstractType} type\n * @param {number} index\n *\n * @function\n */\nexport const createAbsolutePosition = (type, index) => new AbsolutePosition(type, index)\n\n/**\n * @param {AbstractType} type\n * @param {ID|null} item\n *\n * @function\n */\nexport const createRelativePosition = (type, item) => {\n let typeid = null\n let tname = null\n if (type._item === null) {\n tname = findRootTypeKey(type)\n } else {\n typeid = createID(type._item.id.client, type._item.id.clock)\n }\n return new RelativePosition(typeid, tname, item)\n}\n\n/**\n * Create a relativePosition based on a absolute position.\n *\n * @param {AbstractType} type The base type (e.g. YText or YArray).\n * @param {number} index The absolute position.\n * @return {RelativePosition}\n *\n * @function\n */\nexport const createRelativePositionFromTypeIndex = (type, index) => {\n let t = type._start\n while (t !== null) {\n if (!t.deleted && t.countable) {\n if (t.length > index) {\n // case 1: found position somewhere in the linked list\n return createRelativePosition(type, createID(t.id.client, t.id.clock + index))\n }\n index -= t.length\n }\n t = t.right\n }\n return createRelativePosition(type, null)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {RelativePosition} rpos\n *\n * @function\n */\nexport const writeRelativePosition = (encoder, rpos) => {\n const { type, tname, item } = rpos\n if (item !== null) {\n encoding.writeVarUint(encoder, 0)\n writeID(encoder, item)\n } else if (tname !== null) {\n // case 2: found position at the end of the list and type is stored in y.share\n encoding.writeUint8(encoder, 1)\n encoding.writeVarString(encoder, tname)\n } else if (type !== null) {\n // case 3: found position at the end of the list and type is attached to an item\n encoding.writeUint8(encoder, 2)\n writeID(encoder, type)\n } else {\n throw error.unexpectedCase()\n }\n return encoder\n}\n\n/**\n * @param {RelativePosition} rpos\n * @return {Uint8Array}\n */\nexport const encodeRelativePosition = rpos => {\n const encoder = encoding.createEncoder()\n writeRelativePosition(encoder, rpos)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {decoding.Decoder} decoder\n * @return {RelativePosition|null}\n *\n * @function\n */\nexport const readRelativePosition = decoder => {\n let type = null\n let tname = null\n let itemID = null\n switch (decoding.readVarUint(decoder)) {\n case 0:\n // case 1: found position somewhere in the linked list\n itemID = readID(decoder)\n break\n case 1:\n // case 2: found position at the end of the list and type is stored in y.share\n tname = decoding.readVarString(decoder)\n break\n case 2: {\n // case 3: found position at the end of the list and type is attached to an item\n type = readID(decoder)\n }\n }\n return new RelativePosition(type, tname, itemID)\n}\n\n/**\n * @param {Uint8Array} uint8Array\n * @return {RelativePosition|null}\n */\nexport const decodeRelativePosition = uint8Array => readRelativePosition(decoding.createDecoder(uint8Array))\n\n/**\n * @param {RelativePosition} rpos\n * @param {Doc} doc\n * @return {AbsolutePosition|null}\n *\n * @function\n */\nexport const createAbsolutePositionFromRelativePosition = (rpos, doc) => {\n const store = doc.store\n const rightID = rpos.item\n const typeID = rpos.type\n const tname = rpos.tname\n let type = null\n let index = 0\n if (rightID !== null) {\n if (getState(store, rightID.client) <= rightID.clock) {\n return null\n }\n const res = followRedone(store, rightID)\n const right = res.item\n if (!(right instanceof Item)) {\n return null\n }\n type = /** @type {AbstractType} */ (right.parent)\n if (type._item === null || !type._item.deleted) {\n index = right.deleted || !right.countable ? 0 : res.diff\n let n = right.left\n while (n !== null) {\n if (!n.deleted && n.countable) {\n index += n.length\n }\n n = n.left\n }\n }\n } else {\n if (tname !== null) {\n type = doc.get(tname)\n } else if (typeID !== null) {\n if (getState(store, typeID.client) <= typeID.clock) {\n // type does not exist yet\n return null\n }\n const { item } = followRedone(store, typeID)\n if (item instanceof Item && item.content instanceof ContentType) {\n type = item.content.type\n } else {\n // struct is garbage collected\n return null\n }\n } else {\n throw error.unexpectedCase()\n }\n index = type._length\n }\n return createAbsolutePosition(type, index)\n}\n\n/**\n * @param {RelativePosition|null} a\n * @param {RelativePosition|null} b\n *\n * @function\n */\nexport const compareRelativePositions = (a, b) => a === b || (\n a !== null && b !== null && a.tname === b.tname && compareIDs(a.item, b.item) && compareIDs(a.type, b.type)\n)\n","\nimport {\n isDeleted,\n createDeleteSetFromStructStore,\n getStateVector,\n getItemCleanStart,\n iterateDeletedStructs,\n writeDeleteSet,\n writeStateVector,\n readDeleteSet,\n readStateVector,\n createDeleteSet,\n createID,\n getState,\n findIndexSS,\n UpdateEncoderV2,\n DefaultDSEncoder,\n applyUpdateV2,\n AbstractDSDecoder, AbstractDSEncoder, DSEncoderV2, DSDecoderV1, DSDecoderV2, Transaction, Doc, DeleteSet, Item // eslint-disable-line\n} from '../internals.js'\n\nimport * as map from 'lib0/map.js'\nimport * as set from 'lib0/set.js'\nimport * as decoding from 'lib0/decoding.js'\nimport * as encoding from 'lib0/encoding.js'\n\nexport class Snapshot {\n /**\n * @param {DeleteSet} ds\n * @param {Map} sv state map\n */\n constructor (ds, sv) {\n /**\n * @type {DeleteSet}\n */\n this.ds = ds\n /**\n * State Map\n * @type {Map}\n */\n this.sv = sv\n }\n}\n\n/**\n * @param {Snapshot} snap1\n * @param {Snapshot} snap2\n * @return {boolean}\n */\nexport const equalSnapshots = (snap1, snap2) => {\n const ds1 = snap1.ds.clients\n const ds2 = snap2.ds.clients\n const sv1 = snap1.sv\n const sv2 = snap2.sv\n if (sv1.size !== sv2.size || ds1.size !== ds2.size) {\n return false\n }\n for (const [key, value] of sv1.entries()) {\n if (sv2.get(key) !== value) {\n return false\n }\n }\n for (const [client, dsitems1] of ds1.entries()) {\n const dsitems2 = ds2.get(client) || []\n if (dsitems1.length !== dsitems2.length) {\n return false\n }\n for (let i = 0; i < dsitems1.length; i++) {\n const dsitem1 = dsitems1[i]\n const dsitem2 = dsitems2[i]\n if (dsitem1.clock !== dsitem2.clock || dsitem1.len !== dsitem2.len) {\n return false\n }\n }\n }\n return true\n}\n\n/**\n * @param {Snapshot} snapshot\n * @param {AbstractDSEncoder} [encoder]\n * @return {Uint8Array}\n */\nexport const encodeSnapshotV2 = (snapshot, encoder = new DSEncoderV2()) => {\n writeDeleteSet(encoder, snapshot.ds)\n writeStateVector(encoder, snapshot.sv)\n return encoder.toUint8Array()\n}\n\n/**\n * @param {Snapshot} snapshot\n * @return {Uint8Array}\n */\nexport const encodeSnapshot = snapshot => encodeSnapshotV2(snapshot, new DefaultDSEncoder())\n\n/**\n * @param {Uint8Array} buf\n * @param {AbstractDSDecoder} [decoder]\n * @return {Snapshot}\n */\nexport const decodeSnapshotV2 = (buf, decoder = new DSDecoderV2(decoding.createDecoder(buf))) => {\n return new Snapshot(readDeleteSet(decoder), readStateVector(decoder))\n}\n\n/**\n * @param {Uint8Array} buf\n * @return {Snapshot}\n */\nexport const decodeSnapshot = buf => decodeSnapshotV2(buf, new DSDecoderV1(decoding.createDecoder(buf)))\n\n/**\n * @param {DeleteSet} ds\n * @param {Map} sm\n * @return {Snapshot}\n */\nexport const createSnapshot = (ds, sm) => new Snapshot(ds, sm)\n\nexport const emptySnapshot = createSnapshot(createDeleteSet(), new Map())\n\n/**\n * @param {Doc} doc\n * @return {Snapshot}\n */\nexport const snapshot = doc => createSnapshot(createDeleteSetFromStructStore(doc.store), getStateVector(doc.store))\n\n/**\n * @param {Item} item\n * @param {Snapshot|undefined} snapshot\n *\n * @protected\n * @function\n */\nexport const isVisible = (item, snapshot) => snapshot === undefined ? !item.deleted : (\n snapshot.sv.has(item.id.client) && (snapshot.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot.ds, item.id)\n)\n\n/**\n * @param {Transaction} transaction\n * @param {Snapshot} snapshot\n */\nexport const splitSnapshotAffectedStructs = (transaction, snapshot) => {\n const meta = map.setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, set.create)\n const store = transaction.doc.store\n // check if we already split for this snapshot\n if (!meta.has(snapshot)) {\n snapshot.sv.forEach((clock, client) => {\n if (clock < getState(store, client)) {\n getItemCleanStart(transaction, createID(client, clock))\n }\n })\n iterateDeletedStructs(transaction, snapshot.ds, item => {})\n meta.add(snapshot)\n }\n}\n\n/**\n * @param {Doc} originDoc\n * @param {Snapshot} snapshot\n * @param {Doc} [newDoc] Optionally, you may define the Yjs document that receives the data from originDoc\n * @return {Doc}\n */\nexport const createDocFromSnapshot = (originDoc, snapshot, newDoc = new Doc()) => {\n if (originDoc.gc) {\n // we should not try to restore a GC-ed document, because some of the restored items might have their content deleted\n throw new Error('originDoc must not be garbage collected')\n }\n const { sv, ds } = snapshot\n\n const encoder = new UpdateEncoderV2()\n originDoc.transact(transaction => {\n let size = 0\n sv.forEach(clock => {\n if (clock > 0) {\n size++\n }\n })\n encoding.writeVarUint(encoder.restEncoder, size)\n // splitting the structs before writing them to the encoder\n for (const [client, clock] of sv) {\n if (clock === 0) {\n continue\n }\n if (clock < getState(originDoc.store, client)) {\n getItemCleanStart(transaction, createID(client, clock))\n }\n const structs = originDoc.store.clients.get(client) || []\n const lastStructIndex = findIndexSS(structs, clock - 1)\n // write # encoded structs\n encoding.writeVarUint(encoder.restEncoder, lastStructIndex + 1)\n encoder.writeClient(client)\n // first clock written is 0\n encoding.writeVarUint(encoder.restEncoder, 0)\n for (let i = 0; i <= lastStructIndex; i++) {\n structs[i].write(encoder, 0)\n }\n }\n writeDeleteSet(encoder, ds)\n })\n\n applyUpdateV2(newDoc, encoder.toUint8Array(), 'snapshot')\n return newDoc\n}\n","\nimport {\n GC,\n splitItem,\n Transaction, ID, Item, DSDecoderV2 // eslint-disable-line\n} from '../internals.js'\n\nimport * as math from 'lib0/math.js'\nimport * as error from 'lib0/error.js'\n\nexport class StructStore {\n constructor () {\n /**\n * @type {Map>}\n */\n this.clients = new Map()\n /**\n * Store incompleted struct reads here\n * `i` denotes to the next read operation\n * We could shift the array of refs instead, but shift is incredible\n * slow in Chrome for arrays with more than 100k elements\n * @see tryResumePendingStructRefs\n * @type {Map}>}\n */\n this.pendingClientsStructRefs = new Map()\n /**\n * Stack of pending structs waiting for struct dependencies\n * Maximum length of stack is structReaders.size\n * @type {Array}\n */\n this.pendingStack = []\n /**\n * @type {Array}\n */\n this.pendingDeleteReaders = []\n }\n}\n\n/**\n * Return the states as a Map.\n * Note that clock refers to the next expected clock id.\n *\n * @param {StructStore} store\n * @return {Map}\n *\n * @public\n * @function\n */\nexport const getStateVector = store => {\n const sm = new Map()\n store.clients.forEach((structs, client) => {\n const struct = structs[structs.length - 1]\n sm.set(client, struct.id.clock + struct.length)\n })\n return sm\n}\n\n/**\n * @param {StructStore} store\n * @param {number} client\n * @return {number}\n *\n * @public\n * @function\n */\nexport const getState = (store, client) => {\n const structs = store.clients.get(client)\n if (structs === undefined) {\n return 0\n }\n const lastStruct = structs[structs.length - 1]\n return lastStruct.id.clock + lastStruct.length\n}\n\n/**\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nexport const integretyCheck = store => {\n store.clients.forEach(structs => {\n for (let i = 1; i < structs.length; i++) {\n const l = structs[i - 1]\n const r = structs[i]\n if (l.id.clock + l.length !== r.id.clock) {\n throw new Error('StructStore failed integrety check')\n }\n }\n })\n}\n\n/**\n * @param {StructStore} store\n * @param {GC|Item} struct\n *\n * @private\n * @function\n */\nexport const addStruct = (store, struct) => {\n let structs = store.clients.get(struct.id.client)\n if (structs === undefined) {\n structs = []\n store.clients.set(struct.id.client, structs)\n } else {\n const lastStruct = structs[structs.length - 1]\n if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) {\n throw error.unexpectedCase()\n }\n }\n structs.push(struct)\n}\n\n/**\n * Perform a binary search on a sorted array\n * @param {Array} structs\n * @param {number} clock\n * @return {number}\n *\n * @private\n * @function\n */\nexport const findIndexSS = (structs, clock) => {\n let left = 0\n let right = structs.length - 1\n let mid = structs[right]\n let midclock = mid.id.clock\n if (midclock === clock) {\n return right\n }\n // @todo does it even make sense to pivot the search?\n // If a good split misses, it might actually increase the time to find the correct item.\n // Currently, the only advantage is that search with pivoting might find the item on the first try.\n let midindex = math.floor((clock / (midclock + mid.length - 1)) * right) // pivoting the search\n while (left <= right) {\n mid = structs[midindex]\n midclock = mid.id.clock\n if (midclock <= clock) {\n if (clock < midclock + mid.length) {\n return midindex\n }\n left = midindex + 1\n } else {\n right = midindex - 1\n }\n midindex = math.floor((left + right) / 2)\n }\n // Always check state before looking for a struct in StructStore\n // Therefore the case of not finding a struct is unexpected\n throw error.unexpectedCase()\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {StructStore} store\n * @param {ID} id\n * @return {GC|Item}\n *\n * @private\n * @function\n */\nexport const find = (store, id) => {\n /**\n * @type {Array}\n */\n // @ts-ignore\n const structs = store.clients.get(id.client)\n return structs[findIndexSS(structs, id.clock)]\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n * @private\n * @function\n */\nexport const getItem = /** @type {function(StructStore,ID):Item} */ (find)\n\n/**\n * @param {Transaction} transaction\n * @param {Array} structs\n * @param {number} clock\n */\nexport const findIndexCleanStart = (transaction, structs, clock) => {\n const index = findIndexSS(structs, clock)\n const struct = structs[index]\n if (struct.id.clock < clock && struct instanceof Item) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock))\n return index + 1\n }\n return index\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {Transaction} transaction\n * @param {ID} id\n * @return {Item}\n *\n * @private\n * @function\n */\nexport const getItemCleanStart = (transaction, id) => {\n const structs = /** @type {Array} */ (transaction.doc.store.clients.get(id.client))\n return structs[findIndexCleanStart(transaction, structs, id.clock)]\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @param {ID} id\n * @return {Item}\n *\n * @private\n * @function\n */\nexport const getItemCleanEnd = (transaction, store, id) => {\n /**\n * @type {Array}\n */\n // @ts-ignore\n const structs = store.clients.get(id.client)\n const index = findIndexSS(structs, id.clock)\n const struct = structs[index]\n if (id.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, id.clock - struct.id.clock + 1))\n }\n return struct\n}\n\n/**\n * Replace `item` with `newitem` in store\n * @param {StructStore} store\n * @param {GC|Item} struct\n * @param {GC|Item} newStruct\n *\n * @private\n * @function\n */\nexport const replaceStruct = (store, struct, newStruct) => {\n const structs = /** @type {Array} */ (store.clients.get(struct.id.client))\n structs[findIndexSS(structs, struct.id.clock)] = newStruct\n}\n\n/**\n * Iterate over a range of structs\n *\n * @param {Transaction} transaction\n * @param {Array} structs\n * @param {number} clockStart Inclusive start\n * @param {number} len\n * @param {function(GC|Item):void} f\n *\n * @function\n */\nexport const iterateStructs = (transaction, structs, clockStart, len, f) => {\n if (len === 0) {\n return\n }\n const clockEnd = clockStart + len\n let index = findIndexCleanStart(transaction, structs, clockStart)\n let struct\n do {\n struct = structs[index++]\n if (clockEnd < struct.id.clock + struct.length) {\n findIndexCleanStart(transaction, structs, clockEnd)\n }\n f(struct)\n } while (index < structs.length && structs[index].id.clock < clockEnd)\n}\n","\nimport {\n getState,\n writeStructsFromTransaction,\n writeDeleteSet,\n DeleteSet,\n sortAndMergeDeleteSet,\n getStateVector,\n findIndexSS,\n callEventHandlerListeners,\n Item,\n generateNewClientId,\n createID,\n AbstractUpdateEncoder, GC, StructStore, UpdateEncoderV2, DefaultUpdateEncoder, AbstractType, AbstractStruct, YEvent, Doc // eslint-disable-line\n} from '../internals.js'\n\nimport * as map from 'lib0/map.js'\nimport * as math from 'lib0/math.js'\nimport * as set from 'lib0/set.js'\nimport * as logging from 'lib0/logging.js'\nimport { callAll } from 'lib0/function.js'\n\n/**\n * A transaction is created for every change on the Yjs model. It is possible\n * to bundle changes on the Yjs model in a single transaction to\n * minimize the number on messages sent and the number of observer calls.\n * If possible the user of this library should bundle as many changes as\n * possible. Here is an example to illustrate the advantages of bundling:\n *\n * @example\n * const map = y.define('map', YMap)\n * // Log content when change is triggered\n * map.observe(() => {\n * console.log('change triggered')\n * })\n * // Each change on the map type triggers a log message:\n * map.set('a', 0) // => \"change triggered\"\n * map.set('b', 0) // => \"change triggered\"\n * // When put in a transaction, it will trigger the log after the transaction:\n * y.transact(() => {\n * map.set('a', 1)\n * map.set('b', 1)\n * }) // => \"change triggered\"\n *\n * @public\n */\nexport class Transaction {\n /**\n * @param {Doc} doc\n * @param {any} origin\n * @param {boolean} local\n */\n constructor (doc, origin, local) {\n /**\n * The Yjs instance.\n * @type {Doc}\n */\n this.doc = doc\n /**\n * Describes the set of deleted items by ids\n * @type {DeleteSet}\n */\n this.deleteSet = new DeleteSet()\n /**\n * Holds the state before the transaction started.\n * @type {Map}\n */\n this.beforeState = getStateVector(doc.store)\n /**\n * Holds the state after the transaction.\n * @type {Map}\n */\n this.afterState = new Map()\n /**\n * All types that were directly modified (property added or child\n * inserted/deleted). New types are not included in this Set.\n * Maps from type to parentSubs (`item.parentSub = null` for YArray)\n * @type {Map,Set>}\n */\n this.changed = new Map()\n /**\n * Stores the events for the types that observe also child elements.\n * It is mainly used by `observeDeep`.\n * @type {Map,Array>}\n */\n this.changedParentTypes = new Map()\n /**\n * @type {Array}\n */\n this._mergeStructs = []\n /**\n * @type {any}\n */\n this.origin = origin\n /**\n * Stores meta information on the transaction\n * @type {Map}\n */\n this.meta = new Map()\n /**\n * Whether this change originates from this doc.\n * @type {boolean}\n */\n this.local = local\n /**\n * @type {Set}\n */\n this.subdocsAdded = new Set()\n /**\n * @type {Set}\n */\n this.subdocsRemoved = new Set()\n /**\n * @type {Set}\n */\n this.subdocsLoaded = new Set()\n }\n}\n\n/**\n * @param {AbstractUpdateEncoder} encoder\n * @param {Transaction} transaction\n * @return {boolean} Whether data was written.\n */\nexport const writeUpdateMessageFromTransaction = (encoder, transaction) => {\n if (transaction.deleteSet.clients.size === 0 && !map.any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) {\n return false\n }\n sortAndMergeDeleteSet(transaction.deleteSet)\n writeStructsFromTransaction(encoder, transaction)\n writeDeleteSet(encoder, transaction.deleteSet)\n return true\n}\n\n/**\n * @param {Transaction} transaction\n *\n * @private\n * @function\n */\nexport const nextID = transaction => {\n const y = transaction.doc\n return createID(y.clientID, getState(y.store, y.clientID))\n}\n\n/**\n * If `type.parent` was added in current transaction, `type` technically\n * did not change, it was just added and we should not fire events for `type`.\n *\n * @param {Transaction} transaction\n * @param {AbstractType} type\n * @param {string|null} parentSub\n */\nexport const addChangedTypeToTransaction = (transaction, type, parentSub) => {\n const item = type._item\n if (item === null || (item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted)) {\n map.setIfUndefined(transaction.changed, type, set.create).add(parentSub)\n }\n}\n\n/**\n * @param {Array} structs\n * @param {number} pos\n */\nconst tryToMergeWithLeft = (structs, pos) => {\n const left = structs[pos - 1]\n const right = structs[pos]\n if (left.deleted === right.deleted && left.constructor === right.constructor) {\n if (left.mergeWith(right)) {\n structs.splice(pos, 1)\n if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType} */ (right.parent)._map.get(right.parentSub) === right) {\n /** @type {AbstractType} */ (right.parent)._map.set(right.parentSub, /** @type {Item} */ (left))\n }\n }\n }\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n * @param {function(Item):boolean} gcFilter\n */\nconst tryGcDeleteSet = (ds, store, gcFilter) => {\n for (const [client, deleteItems] of ds.clients.entries()) {\n const structs = /** @type {Array} */ (store.clients.get(client))\n for (let di = deleteItems.length - 1; di >= 0; di--) {\n const deleteItem = deleteItems[di]\n const endDeleteItemClock = deleteItem.clock + deleteItem.len\n for (\n let si = findIndexSS(structs, deleteItem.clock), struct = structs[si];\n si < structs.length && struct.id.clock < endDeleteItemClock;\n struct = structs[++si]\n ) {\n const struct = structs[si]\n if (deleteItem.clock + deleteItem.len <= struct.id.clock) {\n break\n }\n if (struct instanceof Item && struct.deleted && !struct.keep && gcFilter(struct)) {\n struct.gc(store, false)\n }\n }\n }\n }\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n */\nconst tryMergeDeleteSet = (ds, store) => {\n // try to merge deleted / gc'd items\n // merge from right to left for better efficiecy and so we don't miss any merge targets\n ds.clients.forEach((deleteItems, client) => {\n const structs = /** @type {Array} */ (store.clients.get(client))\n for (let di = deleteItems.length - 1; di >= 0; di--) {\n const deleteItem = deleteItems[di]\n // start with merging the item next to the last deleted item\n const mostRightIndexToCheck = math.min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1))\n for (\n let si = mostRightIndexToCheck, struct = structs[si];\n si > 0 && struct.id.clock >= deleteItem.clock;\n struct = structs[--si]\n ) {\n tryToMergeWithLeft(structs, si)\n }\n }\n })\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n * @param {function(Item):boolean} gcFilter\n */\nexport const tryGc = (ds, store, gcFilter) => {\n tryGcDeleteSet(ds, store, gcFilter)\n tryMergeDeleteSet(ds, store)\n}\n\n/**\n * @param {Array} transactionCleanups\n * @param {number} i\n */\nconst cleanupTransactions = (transactionCleanups, i) => {\n if (i < transactionCleanups.length) {\n const transaction = transactionCleanups[i]\n const doc = transaction.doc\n const store = doc.store\n const ds = transaction.deleteSet\n const mergeStructs = transaction._mergeStructs\n try {\n sortAndMergeDeleteSet(ds)\n transaction.afterState = getStateVector(transaction.doc.store)\n doc._transaction = null\n doc.emit('beforeObserverCalls', [transaction, doc])\n /**\n * An array of event callbacks.\n *\n * Each callback is called even if the other ones throw errors.\n *\n * @type {Array}\n */\n const fs = []\n // observe events on changed types\n transaction.changed.forEach((subs, itemtype) =>\n fs.push(() => {\n if (itemtype._item === null || !itemtype._item.deleted) {\n itemtype._callObserver(transaction, subs)\n }\n })\n )\n fs.push(() => {\n // deep observe events\n transaction.changedParentTypes.forEach((events, type) =>\n fs.push(() => {\n // We need to think about the possibility that the user transforms the\n // Y.Doc in the event.\n if (type._item === null || !type._item.deleted) {\n events = events\n .filter(event =>\n event.target._item === null || !event.target._item.deleted\n )\n events\n .forEach(event => {\n event.currentTarget = type\n })\n // sort events by path length so that top-level events are fired first.\n events\n .sort((event1, event2) => event1.path.length - event2.path.length)\n // We don't need to check for events.length\n // because we know it has at least one element\n callEventHandlerListeners(type._dEH, events, transaction)\n }\n })\n )\n fs.push(() => doc.emit('afterTransaction', [transaction, doc]))\n })\n callAll(fs, [])\n } finally {\n // Replace deleted items with ItemDeleted / GC.\n // This is where content is actually remove from the Yjs Doc.\n if (doc.gc) {\n tryGcDeleteSet(ds, store, doc.gcFilter)\n }\n tryMergeDeleteSet(ds, store)\n\n // on all affected store.clients props, try to merge\n transaction.afterState.forEach((clock, client) => {\n const beforeClock = transaction.beforeState.get(client) || 0\n if (beforeClock !== clock) {\n const structs = /** @type {Array} */ (store.clients.get(client))\n // we iterate from right to left so we can safely remove entries\n const firstChangePos = math.max(findIndexSS(structs, beforeClock), 1)\n for (let i = structs.length - 1; i >= firstChangePos; i--) {\n tryToMergeWithLeft(structs, i)\n }\n }\n })\n // try to merge mergeStructs\n // @todo: it makes more sense to transform mergeStructs to a DS, sort it, and merge from right to left\n // but at the moment DS does not handle duplicates\n for (let i = 0; i < mergeStructs.length; i++) {\n const { client, clock } = mergeStructs[i].id\n const structs = /** @type {Array} */ (store.clients.get(client))\n const replacedStructPos = findIndexSS(structs, clock)\n if (replacedStructPos + 1 < structs.length) {\n tryToMergeWithLeft(structs, replacedStructPos + 1)\n }\n if (replacedStructPos > 0) {\n tryToMergeWithLeft(structs, replacedStructPos)\n }\n }\n if (!transaction.local && transaction.afterState.get(doc.clientID) !== transaction.beforeState.get(doc.clientID)) {\n doc.clientID = generateNewClientId()\n logging.print(logging.ORANGE, logging.BOLD, '[yjs] ', logging.UNBOLD, logging.RED, 'Changed the client-id because another client seems to be using it.')\n }\n // @todo Merge all the transactions into one and provide send the data as a single update message\n doc.emit('afterTransactionCleanup', [transaction, doc])\n if (doc._observers.has('update')) {\n const encoder = new DefaultUpdateEncoder()\n const hasContent = writeUpdateMessageFromTransaction(encoder, transaction)\n if (hasContent) {\n doc.emit('update', [encoder.toUint8Array(), transaction.origin, doc])\n }\n }\n if (doc._observers.has('updateV2')) {\n const encoder = new UpdateEncoderV2()\n const hasContent = writeUpdateMessageFromTransaction(encoder, transaction)\n if (hasContent) {\n doc.emit('updateV2', [encoder.toUint8Array(), transaction.origin, doc])\n }\n }\n transaction.subdocsAdded.forEach(subdoc => doc.subdocs.add(subdoc))\n transaction.subdocsRemoved.forEach(subdoc => doc.subdocs.delete(subdoc))\n\n doc.emit('subdocs', [{ loaded: transaction.subdocsLoaded, added: transaction.subdocsAdded, removed: transaction.subdocsRemoved }])\n transaction.subdocsRemoved.forEach(subdoc => subdoc.destroy())\n\n if (transactionCleanups.length <= i + 1) {\n doc._transactionCleanups = []\n doc.emit('afterAllTransactions', [doc, transactionCleanups])\n } else {\n cleanupTransactions(transactionCleanups, i + 1)\n }\n }\n }\n}\n\n/**\n * Implements the functionality of `y.transact(()=>{..})`\n *\n * @param {Doc} doc\n * @param {function(Transaction):void} f\n * @param {any} [origin=true]\n *\n * @function\n */\nexport const transact = (doc, f, origin = null, local = true) => {\n const transactionCleanups = doc._transactionCleanups\n let initialCall = false\n if (doc._transaction === null) {\n initialCall = true\n doc._transaction = new Transaction(doc, origin, local)\n transactionCleanups.push(doc._transaction)\n if (transactionCleanups.length === 1) {\n doc.emit('beforeAllTransactions', [doc])\n }\n doc.emit('beforeTransaction', [doc._transaction, doc])\n }\n try {\n f(doc._transaction)\n } finally {\n if (initialCall && transactionCleanups[0] === doc._transaction) {\n // The first transaction ended, now process observer calls.\n // Observer call may create new transactions for which we need to call the observers and do cleanup.\n // We don't want to nest these calls, so we execute these calls one after\n // another.\n // Also we need to ensure that all cleanups are called, even if the\n // observes throw errors.\n // This file is full of hacky try {} finally {} blocks to ensure that an\n // event can throw errors and also that the cleanup is called.\n cleanupTransactions(transactionCleanups, 0)\n }\n }\n}\n","import {\n mergeDeleteSets,\n iterateDeletedStructs,\n keepItem,\n transact,\n createID,\n redoItem,\n iterateStructs,\n isParentOf,\n followRedone,\n getItemCleanStart,\n getState,\n ID, Transaction, Doc, Item, GC, DeleteSet, AbstractType // eslint-disable-line\n} from '../internals.js'\n\nimport * as time from 'lib0/time.js'\nimport { Observable } from 'lib0/observable.js'\n\nclass StackItem {\n /**\n * @param {DeleteSet} ds\n * @param {Map} beforeState\n * @param {Map} afterState\n */\n constructor (ds, beforeState, afterState) {\n this.ds = ds\n this.beforeState = beforeState\n this.afterState = afterState\n /**\n * Use this to save and restore metadata like selection range\n */\n this.meta = new Map()\n }\n}\n\n/**\n * @param {UndoManager} undoManager\n * @param {Array} stack\n * @param {string} eventType\n * @return {StackItem?}\n */\nconst popStackItem = (undoManager, stack, eventType) => {\n /**\n * Whether a change happened\n * @type {StackItem?}\n */\n let result = null\n const doc = undoManager.doc\n const scope = undoManager.scope\n transact(doc, transaction => {\n while (stack.length > 0 && result === null) {\n const store = doc.store\n const stackItem = /** @type {StackItem} */ (stack.pop())\n /**\n * @type {Set}\n */\n const itemsToRedo = new Set()\n /**\n * @type {Array}\n */\n const itemsToDelete = []\n let performedChange = false\n stackItem.afterState.forEach((endClock, client) => {\n const startClock = stackItem.beforeState.get(client) || 0\n const len = endClock - startClock\n // @todo iterateStructs should not need the structs parameter\n const structs = /** @type {Array} */ (store.clients.get(client))\n if (startClock !== endClock) {\n // make sure structs don't overlap with the range of created operations [stackItem.start, stackItem.start + stackItem.end)\n // this must be executed before deleted structs are iterated.\n getItemCleanStart(transaction, createID(client, startClock))\n if (endClock < getState(doc.store, client)) {\n getItemCleanStart(transaction, createID(client, endClock))\n }\n iterateStructs(transaction, structs, startClock, len, struct => {\n if (struct instanceof Item) {\n if (struct.redone !== null) {\n let { item, diff } = followRedone(store, struct.id)\n if (diff > 0) {\n item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff))\n }\n if (item.length > len) {\n getItemCleanStart(transaction, createID(item.id.client, endClock))\n }\n struct = item\n }\n if (!struct.deleted && scope.some(type => isParentOf(type, /** @type {Item} */ (struct)))) {\n itemsToDelete.push(struct)\n }\n }\n })\n }\n })\n iterateDeletedStructs(transaction, stackItem.ds, struct => {\n const id = struct.id\n const clock = id.clock\n const client = id.client\n const startClock = stackItem.beforeState.get(client) || 0\n const endClock = stackItem.afterState.get(client) || 0\n if (\n struct instanceof Item &&\n scope.some(type => isParentOf(type, struct)) &&\n // Never redo structs in [stackItem.start, stackItem.start + stackItem.end) because they were created and deleted in the same capture interval.\n !(clock >= startClock && clock < endClock)\n ) {\n itemsToRedo.add(struct)\n }\n })\n itemsToRedo.forEach(struct => {\n performedChange = redoItem(transaction, struct, itemsToRedo) !== null || performedChange\n })\n // We want to delete in reverse order so that children are deleted before\n // parents, so we have more information available when items are filtered.\n for (let i = itemsToDelete.length - 1; i >= 0; i--) {\n const item = itemsToDelete[i]\n if (undoManager.deleteFilter(item)) {\n item.delete(transaction)\n performedChange = true\n }\n }\n result = stackItem\n if (result != null) {\n undoManager.emit('stack-item-popped', [{ stackItem: result, type: eventType }, undoManager])\n }\n }\n transaction.changed.forEach((subProps, type) => {\n // destroy search marker if necessary\n if (subProps.has(null) && type._searchMarker) {\n type._searchMarker.length = 0\n }\n })\n }, undoManager)\n return result\n}\n\n/**\n * @typedef {Object} UndoManagerOptions\n * @property {number} [UndoManagerOptions.captureTimeout=500]\n * @property {function(Item):boolean} [UndoManagerOptions.deleteFilter=()=>true] Sometimes\n * it is necessary to filter whan an Undo/Redo operation can delete. If this\n * filter returns false, the type/item won't be deleted even it is in the\n * undo/redo scope.\n * @property {Set} [UndoManagerOptions.trackedOrigins=new Set([null])]\n */\n\n/**\n * Fires 'stack-item-added' event when a stack item was added to either the undo- or\n * the redo-stack. You may store additional stack information via the\n * metadata property on `event.stackItem.meta` (it is a `Map` of metadata properties).\n * Fires 'stack-item-popped' event when a stack item was popped from either the\n * undo- or the redo-stack. You may restore the saved stack information from `event.stackItem.meta`.\n *\n * @extends {Observable<'stack-item-added'|'stack-item-popped'>}\n */\nexport class UndoManager extends Observable {\n /**\n * @param {AbstractType|Array>} typeScope Accepts either a single type, or an array of types\n * @param {UndoManagerOptions} options\n */\n constructor (typeScope, { captureTimeout = 500, deleteFilter = () => true, trackedOrigins = new Set([null]) } = {}) {\n super()\n this.scope = typeScope instanceof Array ? typeScope : [typeScope]\n this.deleteFilter = deleteFilter\n trackedOrigins.add(this)\n this.trackedOrigins = trackedOrigins\n /**\n * @type {Array}\n */\n this.undoStack = []\n /**\n * @type {Array}\n */\n this.redoStack = []\n /**\n * Whether the client is currently undoing (calling UndoManager.undo)\n *\n * @type {boolean}\n */\n this.undoing = false\n this.redoing = false\n this.doc = /** @type {Doc} */ (this.scope[0].doc)\n this.lastChange = 0\n this.doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => {\n // Only track certain transactions\n if (!this.scope.some(type => transaction.changedParentTypes.has(type)) || (!this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor)))) {\n return\n }\n const undoing = this.undoing\n const redoing = this.redoing\n const stack = undoing ? this.redoStack : this.undoStack\n if (undoing) {\n this.stopCapturing() // next undo should not be appended to last stack item\n } else if (!redoing) {\n // neither undoing nor redoing: delete redoStack\n this.redoStack = []\n }\n const beforeState = transaction.beforeState\n const afterState = transaction.afterState\n const now = time.getUnixTime()\n if (now - this.lastChange < captureTimeout && stack.length > 0 && !undoing && !redoing) {\n // append change to last stack op\n const lastOp = stack[stack.length - 1]\n lastOp.ds = mergeDeleteSets([lastOp.ds, transaction.deleteSet])\n lastOp.afterState = afterState\n } else {\n // create a new stack op\n stack.push(new StackItem(transaction.deleteSet, beforeState, afterState))\n }\n if (!undoing && !redoing) {\n this.lastChange = now\n }\n // make sure that deleted structs are not gc'd\n iterateDeletedStructs(transaction, transaction.deleteSet, /** @param {Item|GC} item */ item => {\n if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) {\n keepItem(item, true)\n }\n })\n this.emit('stack-item-added', [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? 'redo' : 'undo' }, this])\n })\n }\n\n clear () {\n this.doc.transact(transaction => {\n /**\n * @param {StackItem} stackItem\n */\n const clearItem = stackItem => {\n iterateDeletedStructs(transaction, stackItem.ds, item => {\n if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) {\n keepItem(item, false)\n }\n })\n }\n this.undoStack.forEach(clearItem)\n this.redoStack.forEach(clearItem)\n })\n this.undoStack = []\n this.redoStack = []\n }\n\n /**\n * UndoManager merges Undo-StackItem if they are created within time-gap\n * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next\n * StackItem won't be merged.\n *\n *\n * @example\n * // without stopCapturing\n * ytext.insert(0, 'a')\n * ytext.insert(1, 'b')\n * um.undo()\n * ytext.toString() // => '' (note that 'ab' was removed)\n * // with stopCapturing\n * ytext.insert(0, 'a')\n * um.stopCapturing()\n * ytext.insert(0, 'b')\n * um.undo()\n * ytext.toString() // => 'a' (note that only 'b' was removed)\n *\n */\n stopCapturing () {\n this.lastChange = 0\n }\n\n /**\n * Undo last changes on type.\n *\n * @return {StackItem?} Returns StackItem if a change was applied\n */\n undo () {\n this.undoing = true\n let res\n try {\n res = popStackItem(this, this.undoStack, 'undo')\n } finally {\n this.undoing = false\n }\n return res\n }\n\n /**\n * Redo last undo operation.\n *\n * @return {StackItem?} Returns StackItem if a change was applied\n */\n redo () {\n this.redoing = true\n let res\n try {\n res = popStackItem(this, this.redoStack, 'redo')\n } finally {\n this.redoing = false\n }\n return res\n }\n}\n","\nimport {\n isDeleted,\n Item, AbstractType, Transaction, AbstractStruct // eslint-disable-line\n} from '../internals.js'\n\nimport * as set from 'lib0/set.js'\nimport * as array from 'lib0/array.js'\n\n/**\n * YEvent describes the changes on a YType.\n */\nexport class YEvent {\n /**\n * @param {AbstractType} target The changed type.\n * @param {Transaction} transaction\n */\n constructor (target, transaction) {\n /**\n * The type on which this event was created on.\n * @type {AbstractType}\n */\n this.target = target\n /**\n * The current target on which the observe callback is called.\n * @type {AbstractType}\n */\n this.currentTarget = target\n /**\n * The transaction that triggered this event.\n * @type {Transaction}\n */\n this.transaction = transaction\n /**\n * @type {Object|null}\n */\n this._changes = null\n }\n\n /**\n * Computes the path from `y` to the changed type.\n *\n * The following property holds:\n * @example\n * let type = y\n * event.path.forEach(dir => {\n * type = type.get(dir)\n * })\n * type === event.target // => true\n */\n get path () {\n // @ts-ignore _item is defined because target is integrated\n return getPathTo(this.currentTarget, this.target)\n }\n\n /**\n * Check if a struct is deleted by this event.\n *\n * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.\n *\n * @param {AbstractStruct} struct\n * @return {boolean}\n */\n deletes (struct) {\n return isDeleted(this.transaction.deleteSet, struct.id)\n }\n\n /**\n * Check if a struct is added by this event.\n *\n * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.\n *\n * @param {AbstractStruct} struct\n * @return {boolean}\n */\n adds (struct) {\n return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0)\n }\n\n /**\n * @return {{added:Set,deleted:Set,keys:Map,delta:Array<{insert:Array}|{delete:number}|{retain:number}>}}\n */\n get changes () {\n let changes = this._changes\n if (changes === null) {\n const target = this.target\n const added = set.create()\n const deleted = set.create()\n /**\n * @type {Array<{insert:Array}|{delete:number}|{retain:number}>}\n */\n const delta = []\n /**\n * @type {Map}\n */\n const keys = new Map()\n changes = {\n added, deleted, delta, keys\n }\n const changed = /** @type Set */ (this.transaction.changed.get(target))\n if (changed.has(null)) {\n /**\n * @type {any}\n */\n let lastOp = null\n const packOp = () => {\n if (lastOp) {\n delta.push(lastOp)\n }\n }\n for (let item = target._start; item !== null; item = item.right) {\n if (item.deleted) {\n if (this.deletes(item) && !this.adds(item)) {\n if (lastOp === null || lastOp.delete === undefined) {\n packOp()\n lastOp = { delete: 0 }\n }\n lastOp.delete += item.length\n deleted.add(item)\n } // else nop\n } else {\n if (this.adds(item)) {\n if (lastOp === null || lastOp.insert === undefined) {\n packOp()\n lastOp = { insert: [] }\n }\n lastOp.insert = lastOp.insert.concat(item.content.getContent())\n added.add(item)\n } else {\n if (lastOp === null || lastOp.retain === undefined) {\n packOp()\n lastOp = { retain: 0 }\n }\n lastOp.retain += item.length\n }\n }\n }\n if (lastOp !== null && lastOp.retain === undefined) {\n packOp()\n }\n }\n changed.forEach(key => {\n if (key !== null) {\n const item = /** @type {Item} */ (target._map.get(key))\n /**\n * @type {'delete' | 'add' | 'update'}\n */\n let action\n let oldValue\n if (this.adds(item)) {\n let prev = item.left\n while (prev !== null && this.adds(prev)) {\n prev = prev.left\n }\n if (this.deletes(item)) {\n if (prev !== null && this.deletes(prev)) {\n action = 'delete'\n oldValue = array.last(prev.content.getContent())\n } else {\n return\n }\n } else {\n if (prev !== null && this.deletes(prev)) {\n action = 'update'\n oldValue = array.last(prev.content.getContent())\n } else {\n action = 'add'\n oldValue = undefined\n }\n }\n } else {\n if (this.deletes(item)) {\n action = 'delete'\n oldValue = array.last(/** @type {Item} */ item.content.getContent())\n } else {\n return // nop\n }\n }\n keys.set(key, { action, oldValue })\n }\n })\n this._changes = changes\n }\n return /** @type {any} */ (changes)\n }\n}\n\n/**\n * Compute the path from this type to the specified target.\n *\n * @example\n * // `child` should be accessible via `type.get(path[0]).get(path[1])..`\n * const path = type.getPathTo(child)\n * // assuming `type instanceof YArray`\n * console.log(path) // might look like => [2, 'key1']\n * child === type.get(path[0]).get(path[1])\n *\n * @param {AbstractType} parent\n * @param {AbstractType} child target\n * @return {Array} Path to the target\n *\n * @private\n * @function\n */\nconst getPathTo = (parent, child) => {\n const path = []\n while (child._item !== null && child !== parent) {\n if (child._item.parentSub !== null) {\n // parent is map-ish\n path.unshift(child._item.parentSub)\n } else {\n // parent is array-ish\n let i = 0\n let c = /** @type {AbstractType} */ (child._item.parent)._start\n while (c !== child._item && c !== null) {\n if (!c.deleted) {\n i++\n }\n c = c.right\n }\n path.unshift(i)\n }\n child = /** @type {AbstractType} */ (child._item.parent)\n }\n return path\n}\n","\nimport {\n removeEventHandlerListener,\n callEventHandlerListeners,\n addEventHandlerListener,\n createEventHandler,\n getState,\n isVisible,\n ContentType,\n createID,\n ContentAny,\n ContentBinary,\n getItemCleanStart,\n ContentDoc, YText, YArray, AbstractUpdateEncoder, Doc, Snapshot, Transaction, EventHandler, YEvent, Item, // eslint-disable-line\n} from '../internals.js'\n\nimport * as map from 'lib0/map.js'\nimport * as iterator from 'lib0/iterator.js'\nimport * as error from 'lib0/error.js'\nimport * as math from 'lib0/math.js'\n\nconst maxSearchMarker = 80\n\n/**\n * A unique timestamp that identifies each marker.\n *\n * Time is relative,.. this is more like an ever-increasing clock.\n *\n * @type {number}\n */\nlet globalSearchMarkerTimestamp = 0\n\nexport class ArraySearchMarker {\n /**\n * @param {Item} p\n * @param {number} index\n */\n constructor (p, index) {\n p.marker = true\n this.p = p\n this.index = index\n this.timestamp = globalSearchMarkerTimestamp++\n }\n}\n\n/**\n * @param {ArraySearchMarker} marker\n */\nconst refreshMarkerTimestamp = marker => { marker.timestamp = globalSearchMarkerTimestamp++ }\n\n/**\n * This is rather complex so this function is the only thing that should overwrite a marker\n *\n * @param {ArraySearchMarker} marker\n * @param {Item} p\n * @param {number} index\n */\nconst overwriteMarker = (marker, p, index) => {\n marker.p.marker = false\n marker.p = p\n p.marker = true\n marker.index = index\n marker.timestamp = globalSearchMarkerTimestamp++\n}\n\n/**\n * @param {Array} searchMarker\n * @param {Item} p\n * @param {number} index\n */\nconst markPosition = (searchMarker, p, index) => {\n if (searchMarker.length >= maxSearchMarker) {\n // override oldest marker (we don't want to create more objects)\n const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b)\n overwriteMarker(marker, p, index)\n return marker\n } else {\n // create new marker\n const pm = new ArraySearchMarker(p, index)\n searchMarker.push(pm)\n return pm\n }\n}\n\n/**\n * Search marker help us to find positions in the associative array faster.\n *\n * They speed up the process of finding a position without much bookkeeping.\n *\n * A maximum of `maxSearchMarker` objects are created.\n *\n * This function always returns a refreshed marker (updated timestamp)\n *\n * @param {AbstractType} yarray\n * @param {number} index\n */\nexport const findMarker = (yarray, index) => {\n if (yarray._start === null || index === 0 || yarray._searchMarker === null) {\n return null\n }\n const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => math.abs(index - a.index) < math.abs(index - b.index) ? a : b)\n let p = yarray._start\n let pindex = 0\n if (marker !== null) {\n p = marker.p\n pindex = marker.index\n refreshMarkerTimestamp(marker) // we used it, we might need to use it again\n }\n // iterate to right if possible\n while (p.right !== null && pindex < index) {\n if (!p.deleted && p.countable) {\n if (index < pindex + p.length) {\n break\n }\n pindex += p.length\n }\n p = p.right\n }\n // iterate to left if necessary (might be that pindex > index)\n while (p.left !== null && pindex > index) {\n p = p.left\n if (!p.deleted && p.countable) {\n pindex -= p.length\n }\n }\n // we want to make sure that p can't be merged with left, because that would screw up everything\n // in that cas just return what we have (it is most likely the best marker anyway)\n // iterate to left until p can't be merged with left\n while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) {\n p = p.left\n if (!p.deleted && p.countable) {\n pindex -= p.length\n }\n }\n\n // @todo remove!\n // assure position\n // {\n // let start = yarray._start\n // let pos = 0\n // while (start !== p) {\n // if (!start.deleted && start.countable) {\n // pos += start.length\n // }\n // start = /** @type {Item} */ (start.right)\n // }\n // if (pos !== pindex) {\n // debugger\n // throw new Error('Gotcha position fail!')\n // }\n // }\n // if (marker) {\n // if (window.lengthes == null) {\n // window.lengthes = []\n // window.getLengthes = () => window.lengthes.sort((a, b) => a - b)\n // }\n // window.lengthes.push(marker.index - pindex)\n // console.log('distance', marker.index - pindex, 'len', p && p.parent.length)\n // }\n if (marker !== null && math.abs(marker.index - pindex) < /** @type {YText|YArray} */ (p.parent).length / maxSearchMarker) {\n // adjust existing marker\n overwriteMarker(marker, p, pindex)\n return marker\n } else {\n // create new marker\n return markPosition(yarray._searchMarker, p, pindex)\n }\n}\n\n/**\n * Update markers when a change happened.\n *\n * This should be called before doing a deletion!\n *\n * @param {Array} searchMarker\n * @param {number} index\n * @param {number} len If insertion, len is positive. If deletion, len is negative.\n */\nexport const updateMarkerChanges = (searchMarker, index, len) => {\n for (let i = searchMarker.length - 1; i >= 0; i--) {\n const m = searchMarker[i]\n if (len > 0) {\n /**\n * @type {Item|null}\n */\n let p = m.p\n p.marker = false\n // Ideally we just want to do a simple position comparison, but this will only work if\n // search markers don't point to deleted items for formats.\n // Iterate marker to prev undeleted countable position so we know what to do when updating a position\n while (p && (p.deleted || !p.countable)) {\n p = p.left\n if (p && !p.deleted && p.countable) {\n // adjust position. the loop should break now\n m.index -= p.length\n }\n }\n if (p === null || p.marker === true) {\n // remove search marker if updated position is null or if position is already marked\n searchMarker.splice(i, 1)\n continue\n }\n m.p = p\n p.marker = true\n }\n if (index < m.index || (len > 0 && index === m.index)) { // a simple index <= m.index check would actually suffice\n m.index = math.max(index, m.index + len)\n }\n }\n}\n\n/**\n * Accumulate all (list) children of a type and return them as an Array.\n *\n * @param {AbstractType} t\n * @return {Array}\n */\nexport const getTypeChildren = t => {\n let s = t._start\n const arr = []\n while (s) {\n arr.push(s)\n s = s.right\n }\n return arr\n}\n\n/**\n * Call event listeners with an event. This will also add an event to all\n * parents (for `.observeDeep` handlers).\n *\n * @template EventType\n * @param {AbstractType} type\n * @param {Transaction} transaction\n * @param {EventType} event\n */\nexport const callTypeObservers = (type, transaction, event) => {\n const changedType = type\n const changedParentTypes = transaction.changedParentTypes\n while (true) {\n // @ts-ignore\n map.setIfUndefined(changedParentTypes, type, () => []).push(event)\n if (type._item === null) {\n break\n }\n type = /** @type {AbstractType} */ (type._item.parent)\n }\n callEventHandlerListeners(changedType._eH, event, transaction)\n}\n\n/**\n * @template EventType\n * Abstract Yjs Type class\n */\nexport class AbstractType {\n constructor () {\n /**\n * @type {Item|null}\n */\n this._item = null\n /**\n * @type {Map}\n */\n this._map = new Map()\n /**\n * @type {Item|null}\n */\n this._start = null\n /**\n * @type {Doc|null}\n */\n this.doc = null\n this._length = 0\n /**\n * Event handlers\n * @type {EventHandler}\n */\n this._eH = createEventHandler()\n /**\n * Deep event handlers\n * @type {EventHandler,Transaction>}\n */\n this._dEH = createEventHandler()\n /**\n * @type {null | Array}\n */\n this._searchMarker = null\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item|null} item\n */\n _integrate (y, item) {\n this.doc = y\n this._item = item\n }\n\n /**\n * @return {AbstractType}\n */\n _copy () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n */\n _write (encoder) { }\n\n /**\n * The first non-deleted item\n */\n get _first () {\n let n = this._start\n while (n !== null && n.deleted) {\n n = n.right\n }\n return n\n }\n\n /**\n * Creates YEvent and calls all type observers.\n * Must be implemented by each type.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n if (!transaction.local && this._searchMarker) {\n this._searchMarker.length = 0\n }\n }\n\n /**\n * Observe all events that are created on this type.\n *\n * @param {function(EventType, Transaction):void} f Observer function\n */\n observe (f) {\n addEventHandlerListener(this._eH, f)\n }\n\n /**\n * Observe all events that are created by this type and its children.\n *\n * @param {function(Array,Transaction):void} f Observer function\n */\n observeDeep (f) {\n addEventHandlerListener(this._dEH, f)\n }\n\n /**\n * Unregister an observer function.\n *\n * @param {function(EventType,Transaction):void} f Observer function\n */\n unobserve (f) {\n removeEventHandlerListener(this._eH, f)\n }\n\n /**\n * Unregister an observer function.\n *\n * @param {function(Array,Transaction):void} f Observer function\n */\n unobserveDeep (f) {\n removeEventHandlerListener(this._dEH, f)\n }\n\n /**\n * @abstract\n * @return {any}\n */\n toJSON () {}\n}\n\n/**\n * @param {AbstractType} type\n * @return {Array}\n *\n * @private\n * @function\n */\nexport const typeListToArray = type => {\n const cs = []\n let n = type._start\n while (n !== null) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n cs.push(c[i])\n }\n }\n n = n.right\n }\n return cs\n}\n\n/**\n * @param {AbstractType} type\n * @param {Snapshot} snapshot\n * @return {Array}\n *\n * @private\n * @function\n */\nexport const typeListToArraySnapshot = (type, snapshot) => {\n const cs = []\n let n = type._start\n while (n !== null) {\n if (n.countable && isVisible(n, snapshot)) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n cs.push(c[i])\n }\n }\n n = n.right\n }\n return cs\n}\n\n/**\n * Executes a provided function on once on overy element of this YArray.\n *\n * @param {AbstractType} type\n * @param {function(any,number,any):void} f A function to execute on every element of this YArray.\n *\n * @private\n * @function\n */\nexport const typeListForEach = (type, f) => {\n let index = 0\n let n = type._start\n while (n !== null) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n f(c[i], index++, type)\n }\n }\n n = n.right\n }\n}\n\n/**\n * @template C,R\n * @param {AbstractType} type\n * @param {function(C,number,AbstractType):R} f\n * @return {Array}\n *\n * @private\n * @function\n */\nexport const typeListMap = (type, f) => {\n /**\n * @type {Array}\n */\n const result = []\n typeListForEach(type, (c, i) => {\n result.push(f(c, i, type))\n })\n return result\n}\n\n/**\n * @param {AbstractType} type\n * @return {IterableIterator}\n *\n * @private\n * @function\n */\nexport const typeListCreateIterator = type => {\n let n = type._start\n /**\n * @type {Array|null}\n */\n let currentContent = null\n let currentContentIndex = 0\n return {\n [Symbol.iterator] () {\n return this\n },\n next: () => {\n // find some content\n if (currentContent === null) {\n while (n !== null && n.deleted) {\n n = n.right\n }\n // check if we reached the end, no need to check currentContent, because it does not exist\n if (n === null) {\n return {\n done: true,\n value: undefined\n }\n }\n // we found n, so we can set currentContent\n currentContent = n.content.getContent()\n currentContentIndex = 0\n n = n.right // we used the content of n, now iterate to next\n }\n const value = currentContent[currentContentIndex++]\n // check if we need to empty currentContent\n if (currentContent.length <= currentContentIndex) {\n currentContent = null\n }\n return {\n done: false,\n value\n }\n }\n }\n}\n\n/**\n * Executes a provided function on once on overy element of this YArray.\n * Operates on a snapshotted state of the document.\n *\n * @param {AbstractType} type\n * @param {function(any,number,AbstractType):void} f A function to execute on every element of this YArray.\n * @param {Snapshot} snapshot\n *\n * @private\n * @function\n */\nexport const typeListForEachSnapshot = (type, f, snapshot) => {\n let index = 0\n let n = type._start\n while (n !== null) {\n if (n.countable && isVisible(n, snapshot)) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n f(c[i], index++, type)\n }\n }\n n = n.right\n }\n}\n\n/**\n * @param {AbstractType} type\n * @param {number} index\n * @return {any}\n *\n * @private\n * @function\n */\nexport const typeListGet = (type, index) => {\n const marker = findMarker(type, index)\n let n = type._start\n if (marker !== null) {\n n = marker.p\n index -= marker.index\n }\n for (; n !== null; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index < n.length) {\n return n.content.getContent()[index]\n }\n index -= n.length\n }\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {Item?} referenceItem\n * @param {Array|Array|boolean|number|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nexport const typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => {\n let left = referenceItem\n const doc = transaction.doc\n const ownClientId = doc.clientID\n const store = doc.store\n const right = referenceItem === null ? parent._start : referenceItem.right\n /**\n * @type {Array|number>}\n */\n let jsonContent = []\n const packJsonContent = () => {\n if (jsonContent.length > 0) {\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent))\n left.integrate(transaction, 0)\n jsonContent = []\n }\n }\n content.forEach(c => {\n switch (c.constructor) {\n case Number:\n case Object:\n case Boolean:\n case Array:\n case String:\n jsonContent.push(c)\n break\n default:\n packJsonContent()\n switch (c.constructor) {\n case Uint8Array:\n case ArrayBuffer:\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array(/** @type {Uint8Array} */ (c))))\n left.integrate(transaction, 0)\n break\n case Doc:\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc(/** @type {Doc} */ (c)))\n left.integrate(transaction, 0)\n break\n default:\n if (c instanceof AbstractType) {\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c))\n left.integrate(transaction, 0)\n } else {\n throw new Error('Unexpected content type in insert operation')\n }\n }\n }\n })\n packJsonContent()\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @param {Array|Array|number|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nexport const typeListInsertGenerics = (transaction, parent, index, content) => {\n if (index === 0) {\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, index, content.length)\n }\n return typeListInsertGenericsAfter(transaction, parent, null, content)\n }\n const startIndex = index\n const marker = findMarker(parent, index)\n let n = parent._start\n if (marker !== null) {\n n = marker.p\n index -= marker.index\n // we need to iterate one to the left so that the algorithm works\n if (index === 0) {\n // @todo refactor this as it actually doesn't consider formats\n n = n.prev // important! get the left undeleted item so that we can actually decrease index\n index += (n && n.countable && !n.deleted) ? n.length : 0\n }\n }\n for (; n !== null; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index <= n.length) {\n if (index < n.length) {\n // insert in-between\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index))\n }\n break\n }\n index -= n.length\n }\n }\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, startIndex, content.length)\n }\n return typeListInsertGenericsAfter(transaction, parent, n, content)\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @param {number} length\n *\n * @private\n * @function\n */\nexport const typeListDelete = (transaction, parent, index, length) => {\n if (length === 0) { return }\n const startIndex = index\n const startLength = length\n const marker = findMarker(parent, index)\n let n = parent._start\n if (marker !== null) {\n n = marker.p\n index -= marker.index\n }\n // compute the first item to be deleted\n for (; n !== null && index > 0; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index < n.length) {\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index))\n }\n index -= n.length\n }\n }\n // delete all items until done\n while (length > 0 && n !== null) {\n if (!n.deleted) {\n if (length < n.length) {\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length))\n }\n n.delete(transaction)\n length -= n.length\n }\n n = n.right\n }\n if (length > 0) {\n throw error.create('array length exceeded')\n }\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, startIndex, -startLength + length /* in case we remove the above exception */)\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {string} key\n *\n * @private\n * @function\n */\nexport const typeMapDelete = (transaction, parent, key) => {\n const c = parent._map.get(key)\n if (c !== undefined) {\n c.delete(transaction)\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {string} key\n * @param {Object|number|Array|string|Uint8Array|AbstractType} value\n *\n * @private\n * @function\n */\nexport const typeMapSet = (transaction, parent, key, value) => {\n const left = parent._map.get(key) || null\n const doc = transaction.doc\n const ownClientId = doc.clientID\n let content\n if (value == null) {\n content = new ContentAny([value])\n } else {\n switch (value.constructor) {\n case Number:\n case Object:\n case Boolean:\n case Array:\n case String:\n content = new ContentAny([value])\n break\n case Uint8Array:\n content = new ContentBinary(/** @type {Uint8Array} */ (value))\n break\n case Doc:\n content = new ContentDoc(/** @type {Doc} */ (value))\n break\n default:\n if (value instanceof AbstractType) {\n content = new ContentType(value)\n } else {\n throw new Error('Unexpected content type')\n }\n }\n }\n new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0)\n}\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined}\n *\n * @private\n * @function\n */\nexport const typeMapGet = (parent, key) => {\n const val = parent._map.get(key)\n return val !== undefined && !val.deleted ? val.content.getContent()[val.length - 1] : undefined\n}\n\n/**\n * @param {AbstractType} parent\n * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined>}\n *\n * @private\n * @function\n */\nexport const typeMapGetAll = (parent) => {\n /**\n * @type {Object}\n */\n const res = {}\n parent._map.forEach((value, key) => {\n if (!value.deleted) {\n res[key] = value.content.getContent()[value.length - 1]\n }\n })\n return res\n}\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @return {boolean}\n *\n * @private\n * @function\n */\nexport const typeMapHas = (parent, key) => {\n const val = parent._map.get(key)\n return val !== undefined && !val.deleted\n}\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @param {Snapshot} snapshot\n * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined}\n *\n * @private\n * @function\n */\nexport const typeMapGetSnapshot = (parent, key, snapshot) => {\n let v = parent._map.get(key) || null\n while (v !== null && (!snapshot.sv.has(v.id.client) || v.id.clock >= (snapshot.sv.get(v.id.client) || 0))) {\n v = v.left\n }\n return v !== null && isVisible(v, snapshot) ? v.content.getContent()[v.length - 1] : undefined\n}\n\n/**\n * @param {Map} map\n * @return {IterableIterator>}\n *\n * @private\n * @function\n */\nexport const createMapIterator = map => iterator.iteratorFilter(map.entries(), /** @param {any} entry */ entry => !entry[1].deleted)\n","/**\n * @module YArray\n */\n\nimport {\n YEvent,\n AbstractType,\n typeListGet,\n typeListToArray,\n typeListForEach,\n typeListCreateIterator,\n typeListInsertGenerics,\n typeListDelete,\n typeListMap,\n YArrayRefID,\n callTypeObservers,\n transact,\n ArraySearchMarker, AbstractUpdateDecoder, AbstractUpdateEncoder, Doc, Transaction, Item // eslint-disable-line\n} from '../internals.js'\n\n/**\n * Event that describes the changes on a YArray\n * @template T\n */\nexport class YArrayEvent extends YEvent {\n /**\n * @param {YArray} yarray The changed type\n * @param {Transaction} transaction The transaction object\n */\n constructor (yarray, transaction) {\n super(yarray, transaction)\n this._transaction = transaction\n }\n}\n\n/**\n * A shared Array implementation.\n * @template T\n * @extends AbstractType>\n * @implements {Iterable}\n */\nexport class YArray extends AbstractType {\n constructor () {\n super()\n /**\n * @type {Array?}\n * @private\n */\n this._prelimContent = []\n /**\n * @type {Array}\n */\n this._searchMarker = []\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n this.insert(0, /** @type {Array} */ (this._prelimContent))\n this._prelimContent = null\n }\n\n _copy () {\n return new YArray()\n }\n\n get length () {\n return this._prelimContent === null ? this._length : this._prelimContent.length\n }\n\n /**\n * Creates YArrayEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n super._callObserver(transaction, parentSubs)\n callTypeObservers(this, transaction, new YArrayEvent(this, transaction))\n }\n\n /**\n * Inserts new content at an index.\n *\n * Important: This function expects an array of content. Not just a content\n * object. The reason for this \"weirdness\" is that inserting several elements\n * is very efficient when it is done as a single operation.\n *\n * @example\n * // Insert character 'a' at position 0\n * yarray.insert(0, ['a'])\n * // Insert numbers 1, 2 at position 1\n * yarray.insert(1, [1, 2])\n *\n * @param {number} index The index to insert content at.\n * @param {Array} content The array of content\n */\n insert (index, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListInsertGenerics(transaction, this, index, content)\n })\n } else {\n /** @type {Array} */ (this._prelimContent).splice(index, 0, ...content)\n }\n }\n\n /**\n * Appends content to this YArray.\n *\n * @param {Array} content Array of content to append.\n */\n push (content) {\n this.insert(this.length, content)\n }\n\n /**\n * Preppends content to this YArray.\n *\n * @param {Array} content Array of content to preppend.\n */\n unshift (content) {\n this.insert(0, content)\n }\n\n /**\n * Deletes elements starting from an index.\n *\n * @param {number} index Index at which to start deleting elements\n * @param {number} length The number of elements to remove. Defaults to 1.\n */\n delete (index, length = 1) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListDelete(transaction, this, index, length)\n })\n } else {\n /** @type {Array} */ (this._prelimContent).splice(index, length)\n }\n }\n\n /**\n * Returns the i-th element from a YArray.\n *\n * @param {number} index The index of the element to return from the YArray\n * @return {T}\n */\n get (index) {\n return typeListGet(this, index)\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @return {Array}\n */\n toArray () {\n return typeListToArray(this)\n }\n\n /**\n * Transforms this Shared Type to a JSON object.\n *\n * @return {Array}\n */\n toJSON () {\n return this.map(c => c instanceof AbstractType ? c.toJSON() : c)\n }\n\n /**\n * Returns an Array with the result of calling a provided function on every\n * element of this YArray.\n *\n * @template T,M\n * @param {function(T,number,YArray):M} f Function that produces an element of the new Array\n * @return {Array} A new array with each element being the result of the\n * callback function\n */\n map (f) {\n return typeListMap(this, /** @type {any} */ (f))\n }\n\n /**\n * Executes a provided function on once on overy element of this YArray.\n *\n * @param {function(T,number,YArray):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n typeListForEach(this, f)\n }\n\n /**\n * @return {IterableIterator}\n */\n [Symbol.iterator] () {\n return typeListCreateIterator(this)\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YArrayRefID)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n *\n * @private\n * @function\n */\nexport const readYArray = decoder => new YArray()\n","\n/**\n * @module YMap\n */\n\nimport {\n YEvent,\n AbstractType,\n typeMapDelete,\n typeMapSet,\n typeMapGet,\n typeMapHas,\n createMapIterator,\n YMapRefID,\n callTypeObservers,\n transact,\n AbstractUpdateDecoder, AbstractUpdateEncoder, Doc, Transaction, Item // eslint-disable-line\n} from '../internals.js'\n\nimport * as iterator from 'lib0/iterator.js'\n\n/**\n * @template T\n * Event that describes the changes on a YMap.\n */\nexport class YMapEvent extends YEvent {\n /**\n * @param {YMap} ymap The YArray that changed.\n * @param {Transaction} transaction\n * @param {Set} subs The keys that changed.\n */\n constructor (ymap, transaction, subs) {\n super(ymap, transaction)\n this.keysChanged = subs\n }\n}\n\n/**\n * @template T number|string|Object|Array|Uint8Array\n * A shared Map implementation.\n *\n * @extends AbstractType>\n * @implements {Iterable}\n */\nexport class YMap extends AbstractType {\n /**\n *\n * @param {Iterable=} entries - an optional iterable to initialize the YMap\n */\n constructor (entries) {\n super()\n /**\n * @type {Map?}\n * @private\n */\n this._prelimContent = null\n\n if (entries === undefined) {\n this._prelimContent = new Map()\n } else {\n this._prelimContent = new Map(entries)\n }\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n ;/** @type {Map} */ (this._prelimContent).forEach((value, key) => {\n this.set(key, value)\n })\n this._prelimContent = null\n }\n\n _copy () {\n return new YMap()\n }\n\n /**\n * Creates YMapEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs))\n }\n\n /**\n * Transforms this Shared Type to a JSON object.\n *\n * @return {Object}\n */\n toJSON () {\n /**\n * @type {Object}\n */\n const map = {}\n this._map.forEach((item, key) => {\n if (!item.deleted) {\n const v = item.content.getContent()[item.length - 1]\n map[key] = v instanceof AbstractType ? v.toJSON() : v\n }\n })\n return map\n }\n\n /**\n * Returns the size of the YMap (count of key/value pairs)\n *\n * @return {number}\n */\n get size () {\n return [...createMapIterator(this._map)].length\n }\n\n /**\n * Returns the keys for each element in the YMap Type.\n *\n * @return {IterableIterator}\n */\n keys () {\n return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[0])\n }\n\n /**\n * Returns the values for each element in the YMap Type.\n *\n * @return {IterableIterator}\n */\n values () {\n return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[1].content.getContent()[v[1].length - 1])\n }\n\n /**\n * Returns an Iterator of [key, value] pairs\n *\n * @return {IterableIterator}\n */\n entries () {\n return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => [v[0], v[1].content.getContent()[v[1].length - 1]])\n }\n\n /**\n * Executes a provided function on once on every key-value pair.\n *\n * @param {function(T,string,YMap):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n /**\n * @type {Object}\n */\n const map = {}\n this._map.forEach((item, key) => {\n if (!item.deleted) {\n f(item.content.getContent()[item.length - 1], key, this)\n }\n })\n return map\n }\n\n /**\n * @return {IterableIterator}\n */\n [Symbol.iterator] () {\n return this.entries()\n }\n\n /**\n * Remove a specified element from this YMap.\n *\n * @param {string} key The key of the element to remove.\n */\n delete (key) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, key)\n })\n } else {\n /** @type {Map} */ (this._prelimContent).delete(key)\n }\n }\n\n /**\n * Adds or updates an element with a specified key and value.\n *\n * @param {string} key The key of the element to add to this YMap\n * @param {T} value The value of the element to add\n */\n set (key, value) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, key, value)\n })\n } else {\n /** @type {Map} */ (this._prelimContent).set(key, value)\n }\n return value\n }\n\n /**\n * Returns a specified element from this YMap.\n *\n * @param {string} key\n * @return {T|undefined}\n */\n get (key) {\n return /** @type {any} */ (typeMapGet(this, key))\n }\n\n /**\n * Returns a boolean indicating whether the specified key exists or not.\n *\n * @param {string} key The key to test.\n * @return {boolean}\n */\n has (key) {\n return typeMapHas(this, key)\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YMapRefID)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n *\n * @private\n * @function\n */\nexport const readYMap = decoder => new YMap()\n","\n/**\n * @module YText\n */\n\nimport {\n YEvent,\n AbstractType,\n getItemCleanStart,\n getState,\n isVisible,\n createID,\n YTextRefID,\n callTypeObservers,\n transact,\n ContentEmbed,\n GC,\n ContentFormat,\n ContentString,\n splitSnapshotAffectedStructs,\n iterateDeletedStructs,\n iterateStructs,\n findMarker,\n updateMarkerChanges,\n ArraySearchMarker, AbstractUpdateDecoder, AbstractUpdateEncoder, ID, Doc, Item, Snapshot, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as object from 'lib0/object.js'\nimport * as map from 'lib0/map.js'\nimport * as error from 'lib0/error.js'\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nconst equalAttrs = (a, b) => a === b || (typeof a === 'object' && typeof b === 'object' && a && b && object.equalFlat(a, b))\n\nexport class ItemTextListPosition {\n /**\n * @param {Item|null} left\n * @param {Item|null} right\n * @param {number} index\n * @param {Map} currentAttributes\n */\n constructor (left, right, index, currentAttributes) {\n this.left = left\n this.right = right\n this.index = index\n this.currentAttributes = currentAttributes\n }\n\n /**\n * Only call this if you know that this.right is defined\n */\n forward () {\n if (this.right === null) {\n error.unexpectedCase()\n }\n switch (this.right.content.constructor) {\n case ContentEmbed:\n case ContentString:\n if (!this.right.deleted) {\n this.index += this.right.length\n }\n break\n case ContentFormat:\n if (!this.right.deleted) {\n updateCurrentAttributes(this.currentAttributes, /** @type {ContentFormat} */ (this.right.content))\n }\n break\n }\n this.left = this.right\n this.right = this.right.right\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {ItemTextListPosition} pos\n * @param {number} count steps to move forward\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst findNextPosition = (transaction, pos, count) => {\n while (pos.right !== null && count > 0) {\n switch (pos.right.content.constructor) {\n case ContentEmbed:\n case ContentString:\n if (!pos.right.deleted) {\n if (count < pos.right.length) {\n // split right\n getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count))\n }\n pos.index += pos.right.length\n count -= pos.right.length\n }\n break\n case ContentFormat:\n if (!pos.right.deleted) {\n updateCurrentAttributes(pos.currentAttributes, /** @type {ContentFormat} */ (pos.right.content))\n }\n break\n }\n pos.left = pos.right\n pos.right = pos.right.right\n // pos.forward() - we don't forward because that would halve the performance because we already do the checks above\n }\n return pos\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst findPosition = (transaction, parent, index) => {\n const currentAttributes = new Map()\n const marker = findMarker(parent, index)\n if (marker) {\n const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes)\n return findNextPosition(transaction, pos, index - marker.index)\n } else {\n const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes)\n return findNextPosition(transaction, pos, index)\n }\n}\n\n/**\n * Negate applied formats\n *\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {Map} negatedAttributes\n *\n * @private\n * @function\n */\nconst insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => {\n // check if we really need to remove attributes\n while (\n currPos.right !== null && (\n currPos.right.deleted === true || (\n currPos.right.content.constructor === ContentFormat &&\n equalAttrs(negatedAttributes.get(/** @type {ContentFormat} */ (currPos.right.content).key), /** @type {ContentFormat} */ (currPos.right.content).value)\n )\n )\n ) {\n if (!currPos.right.deleted) {\n negatedAttributes.delete(/** @type {ContentFormat} */ (currPos.right.content).key)\n }\n currPos.forward()\n }\n const doc = transaction.doc\n const ownClientId = doc.clientID\n let left = currPos.left\n const right = currPos.right\n negatedAttributes.forEach((val, key) => {\n left = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val))\n left.integrate(transaction, 0)\n })\n}\n\n/**\n * @param {Map} currentAttributes\n * @param {ContentFormat} format\n *\n * @private\n * @function\n */\nconst updateCurrentAttributes = (currentAttributes, format) => {\n const { key, value } = format\n if (value === null) {\n currentAttributes.delete(key)\n } else {\n currentAttributes.set(key, value)\n }\n}\n\n/**\n * @param {ItemTextListPosition} currPos\n * @param {Object} attributes\n *\n * @private\n * @function\n */\nconst minimizeAttributeChanges = (currPos, attributes) => {\n // go right while attributes[right.key] === right.value (or right is deleted)\n while (true) {\n if (currPos.right === null) {\n break\n } else if (currPos.right.deleted || (currPos.right.content.constructor === ContentFormat && equalAttrs(attributes[(/** @type {ContentFormat} */ (currPos.right.content)).key] || null, /** @type {ContentFormat} */ (currPos.right.content).value))) {\n //\n } else {\n break\n }\n currPos.forward()\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {Object} attributes\n * @return {Map}\n *\n * @private\n * @function\n **/\nconst insertAttributes = (transaction, parent, currPos, attributes) => {\n const doc = transaction.doc\n const ownClientId = doc.clientID\n const negatedAttributes = new Map()\n // insert format-start items\n for (const key in attributes) {\n const val = attributes[key]\n const currentVal = currPos.currentAttributes.get(key) || null\n if (!equalAttrs(currentVal, val)) {\n // save negated attribute (set null if currentVal undefined)\n negatedAttributes.set(key, currentVal)\n const { left, right } = currPos\n currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val))\n currPos.right.integrate(transaction, 0)\n currPos.forward()\n }\n }\n return negatedAttributes\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {string|object} text\n * @param {Object} attributes\n *\n * @private\n * @function\n **/\nconst insertText = (transaction, parent, currPos, text, attributes) => {\n currPos.currentAttributes.forEach((val, key) => {\n if (attributes[key] === undefined) {\n attributes[key] = null\n }\n })\n const doc = transaction.doc\n const ownClientId = doc.clientID\n minimizeAttributeChanges(currPos, attributes)\n const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes)\n // insert content\n const content = text.constructor === String ? new ContentString(/** @type {string} */ (text)) : new ContentEmbed(text)\n let { left, right, index } = currPos\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength())\n }\n right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content)\n right.integrate(transaction, 0)\n currPos.right = right\n currPos.index = index\n currPos.forward()\n insertNegatedAttributes(transaction, parent, currPos, negatedAttributes)\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {number} length\n * @param {Object} attributes\n *\n * @private\n * @function\n */\nconst formatText = (transaction, parent, currPos, length, attributes) => {\n const doc = transaction.doc\n const ownClientId = doc.clientID\n minimizeAttributeChanges(currPos, attributes)\n const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes)\n // iterate until first non-format or null is found\n // delete all formats with attributes[format.key] != null\n while (length > 0 && currPos.right !== null) {\n if (!currPos.right.deleted) {\n switch (currPos.right.content.constructor) {\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (currPos.right.content)\n const attr = attributes[key]\n if (attr !== undefined) {\n if (equalAttrs(attr, value)) {\n negatedAttributes.delete(key)\n } else {\n negatedAttributes.set(key, value)\n }\n currPos.right.delete(transaction)\n }\n break\n }\n case ContentEmbed:\n case ContentString:\n if (length < currPos.right.length) {\n getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length))\n }\n length -= currPos.right.length\n break\n }\n }\n currPos.forward()\n }\n // Quill just assumes that the editor starts with a newline and that it always\n // ends with a newline. We only insert that newline when a new newline is\n // inserted - i.e when length is bigger than type.length\n if (length > 0) {\n let newlines = ''\n for (; length > 0; length--) {\n newlines += '\\n'\n }\n currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines))\n currPos.right.integrate(transaction, 0)\n currPos.forward()\n }\n insertNegatedAttributes(transaction, parent, currPos, negatedAttributes)\n}\n\n/**\n * Call this function after string content has been deleted in order to\n * clean up formatting Items.\n *\n * @param {Transaction} transaction\n * @param {Item} start\n * @param {Item|null} end exclusive end, automatically iterates to the next Content Item\n * @param {Map} startAttributes\n * @param {Map} endAttributes This attribute is modified!\n * @return {number} The amount of formatting Items deleted.\n *\n * @function\n */\nconst cleanupFormattingGap = (transaction, start, end, startAttributes, endAttributes) => {\n while (end && end.content.constructor !== ContentString && end.content.constructor !== ContentEmbed) {\n if (!end.deleted && end.content.constructor === ContentFormat) {\n updateCurrentAttributes(endAttributes, /** @type {ContentFormat} */ (end.content))\n }\n end = end.right\n }\n let cleanups = 0\n while (start !== end) {\n if (!start.deleted) {\n const content = start.content\n switch (content.constructor) {\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (content)\n if ((endAttributes.get(key) || null) !== value || (startAttributes.get(key) || null) === value) {\n // Either this format is overwritten or it is not necessary because the attribute already existed.\n start.delete(transaction)\n cleanups++\n }\n break\n }\n }\n }\n start = /** @type {Item} */ (start.right)\n }\n return cleanups\n}\n\n/**\n * @param {Transaction} transaction\n * @param {Item | null} item\n */\nconst cleanupContextlessFormattingGap = (transaction, item) => {\n // iterate until item.right is null or content\n while (item && item.right && (item.right.deleted || (item.right.content.constructor !== ContentString && item.right.content.constructor !== ContentEmbed))) {\n item = item.right\n }\n const attrs = new Set()\n // iterate back until a content item is found\n while (item && (item.deleted || (item.content.constructor !== ContentString && item.content.constructor !== ContentEmbed))) {\n if (!item.deleted && item.content.constructor === ContentFormat) {\n const key = /** @type {ContentFormat} */ (item.content).key\n if (attrs.has(key)) {\n item.delete(transaction)\n } else {\n attrs.add(key)\n }\n }\n item = item.left\n }\n}\n\n/**\n * This function is experimental and subject to change / be removed.\n *\n * Ideally, we don't need this function at all. Formatting attributes should be cleaned up\n * automatically after each change. This function iterates twice over the complete YText type\n * and removes unnecessary formatting attributes. This is also helpful for testing.\n *\n * This function won't be exported anymore as soon as there is confidence that the YText type works as intended.\n *\n * @param {YText} type\n * @return {number} How many formatting attributes have been cleaned up.\n */\nexport const cleanupYTextFormatting = type => {\n let res = 0\n transact(/** @type {Doc} */ (type.doc), transaction => {\n let start = /** @type {Item} */ (type._start)\n let end = type._start\n let startAttributes = map.create()\n const currentAttributes = map.copy(startAttributes)\n while (end) {\n if (end.deleted === false) {\n switch (end.content.constructor) {\n case ContentFormat:\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (end.content))\n break\n case ContentEmbed:\n case ContentString:\n res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes)\n startAttributes = map.copy(currentAttributes)\n start = end\n break\n }\n }\n end = end.right\n }\n })\n return res\n}\n\n/**\n * @param {Transaction} transaction\n * @param {ItemTextListPosition} currPos\n * @param {number} length\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst deleteText = (transaction, currPos, length) => {\n const startLength = length\n const startAttrs = map.copy(currPos.currentAttributes)\n const start = currPos.right\n while (length > 0 && currPos.right !== null) {\n if (currPos.right.deleted === false) {\n switch (currPos.right.content.constructor) {\n case ContentEmbed:\n case ContentString:\n if (length < currPos.right.length) {\n getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length))\n }\n length -= currPos.right.length\n currPos.right.delete(transaction)\n break\n }\n }\n currPos.forward()\n }\n if (start) {\n cleanupFormattingGap(transaction, start, currPos.right, startAttrs, map.copy(currPos.currentAttributes))\n }\n const parent = /** @type {AbstractType} */ (/** @type {Item} */ (currPos.left || currPos.right).parent)\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length)\n }\n return currPos\n}\n\n/**\n * The Quill Delta format represents changes on a text document with\n * formatting information. For mor information visit {@link https://quilljs.com/docs/delta/|Quill Delta}\n *\n * @example\n * {\n * ops: [\n * { insert: 'Gandalf', attributes: { bold: true } },\n * { insert: ' the ' },\n * { insert: 'Grey', attributes: { color: '#cccccc' } }\n * ]\n * }\n *\n */\n\n/**\n * Attributes that can be assigned to a selection of text.\n *\n * @example\n * {\n * bold: true,\n * font-size: '40px'\n * }\n *\n * @typedef {Object} TextAttributes\n */\n\n/**\n * @typedef {Object} DeltaItem\n * @property {number|undefined} DeltaItem.delete\n * @property {number|undefined} DeltaItem.retain\n * @property {string|undefined} DeltaItem.insert\n * @property {Object} DeltaItem.attributes\n */\n\n/**\n * Event that describes the changes on a YText type.\n */\nexport class YTextEvent extends YEvent {\n /**\n * @param {YText} ytext\n * @param {Transaction} transaction\n */\n constructor (ytext, transaction) {\n super(ytext, transaction)\n /**\n * @type {Array|null}\n */\n this._delta = null\n }\n\n /**\n * Compute the changes in the delta format.\n * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document.\n *\n * @type {Array}\n *\n * @public\n */\n get delta () {\n if (this._delta === null) {\n const y = /** @type {Doc} */ (this.target.doc)\n this._delta = []\n transact(y, transaction => {\n const delta = /** @type {Array} */ (this._delta)\n const currentAttributes = new Map() // saves all current attributes for insert\n const oldAttributes = new Map()\n let item = this.target._start\n /**\n * @type {string?}\n */\n let action = null\n /**\n * @type {Object}\n */\n const attributes = {} // counts added or removed new attributes for retain\n /**\n * @type {string|object}\n */\n let insert = ''\n let retain = 0\n let deleteLen = 0\n const addOp = () => {\n if (action !== null) {\n /**\n * @type {any}\n */\n let op\n switch (action) {\n case 'delete':\n op = { delete: deleteLen }\n deleteLen = 0\n break\n case 'insert':\n op = { insert }\n if (currentAttributes.size > 0) {\n op.attributes = {}\n currentAttributes.forEach((value, key) => {\n if (value !== null) {\n op.attributes[key] = value\n }\n })\n }\n insert = ''\n break\n case 'retain':\n op = { retain }\n if (Object.keys(attributes).length > 0) {\n op.attributes = {}\n for (const key in attributes) {\n op.attributes[key] = attributes[key]\n }\n }\n retain = 0\n break\n }\n delta.push(op)\n action = null\n }\n }\n while (item !== null) {\n switch (item.content.constructor) {\n case ContentEmbed:\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n addOp()\n action = 'insert'\n insert = /** @type {ContentEmbed} */ (item.content).embed\n addOp()\n }\n } else if (this.deletes(item)) {\n if (action !== 'delete') {\n addOp()\n action = 'delete'\n }\n deleteLen += 1\n } else if (!item.deleted) {\n if (action !== 'retain') {\n addOp()\n action = 'retain'\n }\n retain += 1\n }\n break\n case ContentString:\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n if (action !== 'insert') {\n addOp()\n action = 'insert'\n }\n insert += /** @type {ContentString} */ (item.content).str\n }\n } else if (this.deletes(item)) {\n if (action !== 'delete') {\n addOp()\n action = 'delete'\n }\n deleteLen += item.length\n } else if (!item.deleted) {\n if (action !== 'retain') {\n addOp()\n action = 'retain'\n }\n retain += item.length\n }\n break\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (item.content)\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n const curVal = currentAttributes.get(key) || null\n if (!equalAttrs(curVal, value)) {\n if (action === 'retain') {\n addOp()\n }\n if (equalAttrs(value, (oldAttributes.get(key) || null))) {\n delete attributes[key]\n } else {\n attributes[key] = value\n }\n } else {\n item.delete(transaction)\n }\n }\n } else if (this.deletes(item)) {\n oldAttributes.set(key, value)\n const curVal = currentAttributes.get(key) || null\n if (!equalAttrs(curVal, value)) {\n if (action === 'retain') {\n addOp()\n }\n attributes[key] = curVal\n }\n } else if (!item.deleted) {\n oldAttributes.set(key, value)\n const attr = attributes[key]\n if (attr !== undefined) {\n if (!equalAttrs(attr, value)) {\n if (action === 'retain') {\n addOp()\n }\n if (value === null) {\n attributes[key] = value\n } else {\n delete attributes[key]\n }\n } else {\n item.delete(transaction)\n }\n }\n }\n if (!item.deleted) {\n if (action === 'insert') {\n addOp()\n }\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (item.content))\n }\n break\n }\n }\n item = item.right\n }\n addOp()\n while (delta.length > 0) {\n const lastOp = delta[delta.length - 1]\n if (lastOp.retain !== undefined && lastOp.attributes === undefined) {\n // retain delta's if they don't assign attributes\n delta.pop()\n } else {\n break\n }\n }\n })\n }\n return this._delta\n }\n}\n\n/**\n * Type that represents text with formatting information.\n *\n * This type replaces y-richtext as this implementation is able to handle\n * block formats (format information on a paragraph), embeds (complex elements\n * like pictures and videos), and text formats (**bold**, *italic*).\n *\n * @extends AbstractType\n */\nexport class YText extends AbstractType {\n /**\n * @param {String} [string] The initial value of the YText.\n */\n constructor (string) {\n super()\n /**\n * Array of pending operations on this type\n * @type {Array?}\n */\n this._pending = string !== undefined ? [() => this.insert(0, string)] : []\n /**\n * @type {Array}\n */\n this._searchMarker = []\n }\n\n /**\n * Number of characters of this text type.\n *\n * @type {number}\n */\n get length () {\n return this._length\n }\n\n /**\n * @param {Doc} y\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n try {\n /** @type {Array} */ (this._pending).forEach(f => f())\n } catch (e) {\n console.error(e)\n }\n this._pending = null\n }\n\n _copy () {\n return new YText()\n }\n\n /**\n * Creates YTextEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n super._callObserver(transaction, parentSubs)\n const event = new YTextEvent(this, transaction)\n const doc = transaction.doc\n // If a remote change happened, we try to cleanup potential formatting duplicates.\n if (!transaction.local) {\n // check if another formatting item was inserted\n let foundFormattingItem = false\n for (const [client, afterClock] of transaction.afterState.entries()) {\n const clock = transaction.beforeState.get(client) || 0\n if (afterClock === clock) {\n continue\n }\n iterateStructs(transaction, /** @type {Array} */ (doc.store.clients.get(client)), clock, afterClock, item => {\n if (!item.deleted && /** @type {Item} */ (item).content.constructor === ContentFormat) {\n foundFormattingItem = true\n }\n })\n if (foundFormattingItem) {\n break\n }\n }\n if (!foundFormattingItem) {\n iterateDeletedStructs(transaction, transaction.deleteSet, item => {\n if (item instanceof GC || foundFormattingItem) {\n return\n }\n if (item.parent === this && item.content.constructor === ContentFormat) {\n foundFormattingItem = true\n }\n })\n }\n transact(doc, (t) => {\n if (foundFormattingItem) {\n // If a formatting item was inserted, we simply clean the whole type.\n // We need to compute currentAttributes for the current position anyway.\n cleanupYTextFormatting(this)\n } else {\n // If no formatting attribute was inserted, we can make due with contextless\n // formatting cleanups.\n // Contextless: it is not necessary to compute currentAttributes for the affected position.\n iterateDeletedStructs(t, t.deleteSet, item => {\n if (item instanceof GC) {\n return\n }\n if (item.parent === this) {\n cleanupContextlessFormattingGap(t, item)\n }\n })\n }\n })\n }\n callTypeObservers(this, transaction, event)\n }\n\n /**\n * Returns the unformatted string representation of this YText type.\n *\n * @public\n */\n toString () {\n let str = ''\n /**\n * @type {Item|null}\n */\n let n = this._start\n while (n !== null) {\n if (!n.deleted && n.countable && n.content.constructor === ContentString) {\n str += /** @type {ContentString} */ (n.content).str\n }\n n = n.right\n }\n return str\n }\n\n /**\n * Returns the unformatted string representation of this YText type.\n *\n * @return {string}\n * @public\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * Apply a {@link Delta} on this shared YText type.\n *\n * @param {any} delta The changes to apply on this element.\n * @param {object} [opts]\n * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true.\n *\n *\n * @public\n */\n applyDelta (delta, { sanitize = true } = {}) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n const currPos = new ItemTextListPosition(null, this._start, 0, new Map())\n for (let i = 0; i < delta.length; i++) {\n const op = delta[i]\n if (op.insert !== undefined) {\n // Quill assumes that the content starts with an empty paragraph.\n // Yjs/Y.Text assumes that it starts empty. We always hide that\n // there is a newline at the end of the content.\n // If we omit this step, clients will see a different number of\n // paragraphs, but nothing bad will happen.\n const ins = (!sanitize && typeof op.insert === 'string' && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === '\\n') ? op.insert.slice(0, -1) : op.insert\n if (typeof ins !== 'string' || ins.length > 0) {\n insertText(transaction, this, currPos, ins, op.attributes || {})\n }\n } else if (op.retain !== undefined) {\n formatText(transaction, this, currPos, op.retain, op.attributes || {})\n } else if (op.delete !== undefined) {\n deleteText(transaction, currPos, op.delete)\n }\n }\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.applyDelta(delta))\n }\n }\n\n /**\n * Returns the Delta representation of this YText type.\n *\n * @param {Snapshot} [snapshot]\n * @param {Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', ID):any} [computeYChange]\n * @return {any} The Delta representation of this type.\n *\n * @public\n */\n toDelta (snapshot, prevSnapshot, computeYChange) {\n /**\n * @type{Array}\n */\n const ops = []\n const currentAttributes = new Map()\n const doc = /** @type {Doc} */ (this.doc)\n let str = ''\n let n = this._start\n function packStr () {\n if (str.length > 0) {\n // pack str with attributes to ops\n /**\n * @type {Object}\n */\n const attributes = {}\n let addAttributes = false\n currentAttributes.forEach((value, key) => {\n addAttributes = true\n attributes[key] = value\n })\n /**\n * @type {Object}\n */\n const op = { insert: str }\n if (addAttributes) {\n op.attributes = attributes\n }\n ops.push(op)\n str = ''\n }\n }\n // snapshots are merged again after the transaction, so we need to keep the\n // transalive until we are done\n transact(doc, transaction => {\n if (snapshot) {\n splitSnapshotAffectedStructs(transaction, snapshot)\n }\n if (prevSnapshot) {\n splitSnapshotAffectedStructs(transaction, prevSnapshot)\n }\n while (n !== null) {\n if (isVisible(n, snapshot) || (prevSnapshot !== undefined && isVisible(n, prevSnapshot))) {\n switch (n.content.constructor) {\n case ContentString: {\n const cur = currentAttributes.get('ychange')\n if (snapshot !== undefined && !isVisible(n, snapshot)) {\n if (cur === undefined || cur.user !== n.id.client || cur.state !== 'removed') {\n packStr()\n currentAttributes.set('ychange', computeYChange ? computeYChange('removed', n.id) : { type: 'removed' })\n }\n } else if (prevSnapshot !== undefined && !isVisible(n, prevSnapshot)) {\n if (cur === undefined || cur.user !== n.id.client || cur.state !== 'added') {\n packStr()\n currentAttributes.set('ychange', computeYChange ? computeYChange('added', n.id) : { type: 'added' })\n }\n } else if (cur !== undefined) {\n packStr()\n currentAttributes.delete('ychange')\n }\n str += /** @type {ContentString} */ (n.content).str\n break\n }\n case ContentEmbed: {\n packStr()\n /**\n * @type {Object}\n */\n const op = {\n insert: /** @type {ContentEmbed} */ (n.content).embed\n }\n if (currentAttributes.size > 0) {\n const attrs = /** @type {Object} */ ({})\n op.attributes = attrs\n currentAttributes.forEach((value, key) => {\n attrs[key] = value\n })\n }\n ops.push(op)\n break\n }\n case ContentFormat:\n if (isVisible(n, snapshot)) {\n packStr()\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (n.content))\n }\n break\n }\n }\n n = n.right\n }\n packStr()\n }, splitSnapshotAffectedStructs)\n return ops\n }\n\n /**\n * Insert text at a given index.\n *\n * @param {number} index The index at which to start inserting.\n * @param {String} text The text to insert at the specified position.\n * @param {TextAttributes} [attributes] Optionally define some formatting\n * information to apply on the inserted\n * Text.\n * @public\n */\n insert (index, text, attributes) {\n if (text.length <= 0) {\n return\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index)\n if (!attributes) {\n attributes = {}\n // @ts-ignore\n pos.currentAttributes.forEach((v, k) => { attributes[k] = v })\n }\n insertText(transaction, this, pos, text, attributes)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.insert(index, text, attributes))\n }\n }\n\n /**\n * Inserts an embed at a index.\n *\n * @param {number} index The index to insert the embed at.\n * @param {Object} embed The Object that represents the embed.\n * @param {TextAttributes} attributes Attribute information to apply on the\n * embed\n *\n * @public\n */\n insertEmbed (index, embed, attributes = {}) {\n if (embed.constructor !== Object) {\n throw new Error('Embed must be an Object')\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index)\n insertText(transaction, this, pos, embed, attributes)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.insertEmbed(index, embed, attributes))\n }\n }\n\n /**\n * Deletes text starting from an index.\n *\n * @param {number} index Index at which to start deleting.\n * @param {number} length The number of characters to remove. Defaults to 1.\n *\n * @public\n */\n delete (index, length) {\n if (length === 0) {\n return\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n deleteText(transaction, findPosition(transaction, this, index), length)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.delete(index, length))\n }\n }\n\n /**\n * Assigns properties to a range of text.\n *\n * @param {number} index The position where to start formatting.\n * @param {number} length The amount of characters to assign properties to.\n * @param {TextAttributes} attributes Attribute information to apply on the\n * text.\n *\n * @public\n */\n format (index, length, attributes) {\n if (length === 0) {\n return\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index)\n if (pos.right === null) {\n return\n }\n formatText(transaction, this, pos, length, attributes)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.format(index, length, attributes))\n }\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YTextRefID)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {YText}\n *\n * @private\n * @function\n */\nexport const readYText = decoder => new YText()\n","/**\n * @module YXml\n */\n\nimport {\n YXmlEvent,\n YXmlElement,\n AbstractType,\n typeListMap,\n typeListForEach,\n typeListInsertGenerics,\n typeListDelete,\n typeListToArray,\n YXmlFragmentRefID,\n callTypeObservers,\n transact,\n AbstractUpdateDecoder, AbstractUpdateEncoder, Doc, ContentType, Transaction, Item, YXmlText, YXmlHook, Snapshot // eslint-disable-line\n} from '../internals.js'\n\n/**\n * Define the elements to which a set of CSS queries apply.\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors|CSS_Selectors}\n *\n * @example\n * query = '.classSelector'\n * query = 'nodeSelector'\n * query = '#idSelector'\n *\n * @typedef {string} CSS_Selector\n */\n\n/**\n * Dom filter function.\n *\n * @callback domFilter\n * @param {string} nodeName The nodeName of the element\n * @param {Map} attributes The map of attributes.\n * @return {boolean} Whether to include the Dom node in the YXmlElement.\n */\n\n/**\n * Represents a subset of the nodes of a YXmlElement / YXmlFragment and a\n * position within them.\n *\n * Can be created with {@link YXmlFragment#createTreeWalker}\n *\n * @public\n * @implements {Iterable}\n */\nexport class YXmlTreeWalker {\n /**\n * @param {YXmlFragment | YXmlElement} root\n * @param {function(AbstractType):boolean} [f]\n */\n constructor (root, f = () => true) {\n this._filter = f\n this._root = root\n /**\n * @type {Item}\n */\n this._currentNode = /** @type {Item} */ (root._start)\n this._firstCall = true\n }\n\n [Symbol.iterator] () {\n return this\n }\n\n /**\n * Get the next node.\n *\n * @return {IteratorResult} The next node.\n *\n * @public\n */\n next () {\n /**\n * @type {Item|null}\n */\n let n = this._currentNode\n let type = /** @type {any} */ (n.content).type\n if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { // if first call, we check if we can use the first item\n do {\n type = /** @type {any} */ (n.content).type\n if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) {\n // walk down in the tree\n n = type._start\n } else {\n // walk right or up in the tree\n while (n !== null) {\n if (n.right !== null) {\n n = n.right\n break\n } else if (n.parent === this._root) {\n n = null\n } else {\n n = /** @type {AbstractType} */ (n.parent)._item\n }\n }\n }\n } while (n !== null && (n.deleted || !this._filter(/** @type {ContentType} */ (n.content).type)))\n }\n this._firstCall = false\n if (n === null) {\n // @ts-ignore\n return { value: undefined, done: true }\n }\n this._currentNode = n\n return { value: /** @type {any} */ (n.content).type, done: false }\n }\n}\n\n/**\n * Represents a list of {@link YXmlElement}.and {@link YXmlText} types.\n * A YxmlFragment is similar to a {@link YXmlElement}, but it does not have a\n * nodeName and it does not have attributes. Though it can be bound to a DOM\n * element - in this case the attributes and the nodeName are not shared.\n *\n * @public\n * @extends AbstractType\n */\nexport class YXmlFragment extends AbstractType {\n constructor () {\n super()\n /**\n * @type {Array|null}\n */\n this._prelimContent = []\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n this.insert(0, /** @type {Array} */ (this._prelimContent))\n this._prelimContent = null\n }\n\n _copy () {\n return new YXmlFragment()\n }\n\n get length () {\n return this._prelimContent === null ? this._length : this._prelimContent.length\n }\n\n /**\n * Create a subtree of childNodes.\n *\n * @example\n * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div')\n * for (let node in walker) {\n * // `node` is a div node\n * nop(node)\n * }\n *\n * @param {function(AbstractType):boolean} filter Function that is called on each child element and\n * returns a Boolean indicating whether the child\n * is to be included in the subtree.\n * @return {YXmlTreeWalker} A subtree and a position within it.\n *\n * @public\n */\n createTreeWalker (filter) {\n return new YXmlTreeWalker(this, filter)\n }\n\n /**\n * Returns the first YXmlElement that matches the query.\n * Similar to DOM's {@link querySelector}.\n *\n * Query support:\n * - tagname\n * TODO:\n * - id\n * - attribute\n *\n * @param {CSS_Selector} query The query on the children.\n * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null.\n *\n * @public\n */\n querySelector (query) {\n query = query.toUpperCase()\n // @ts-ignore\n const iterator = new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query)\n const next = iterator.next()\n if (next.done) {\n return null\n } else {\n return next.value\n }\n }\n\n /**\n * Returns all YXmlElements that match the query.\n * Similar to Dom's {@link querySelectorAll}.\n *\n * @todo Does not yet support all queries. Currently only query by tagName.\n *\n * @param {CSS_Selector} query The query on the children\n * @return {Array} The elements that match this query.\n *\n * @public\n */\n querySelectorAll (query) {\n query = query.toUpperCase()\n // @ts-ignore\n return Array.from(new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query))\n }\n\n /**\n * Creates YXmlEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction))\n }\n\n /**\n * Get the string representation of all the children of this YXmlFragment.\n *\n * @return {string} The string representation of all children.\n */\n toString () {\n return typeListMap(this, xml => xml.toString()).join('')\n }\n\n /**\n * @return {string}\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks={}] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const fragment = _document.createDocumentFragment()\n if (binding !== undefined) {\n binding._createAssociation(fragment, this)\n }\n typeListForEach(this, xmlType => {\n fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null)\n })\n return fragment\n }\n\n /**\n * Inserts new content at an index.\n *\n * @example\n * // Insert character 'a' at position 0\n * xml.insert(0, [new Y.XmlText('text')])\n *\n * @param {number} index The index to insert content at\n * @param {Array} content The array of content\n */\n insert (index, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListInsertGenerics(transaction, this, index, content)\n })\n } else {\n // @ts-ignore _prelimContent is defined because this is not yet integrated\n this._prelimContent.splice(index, 0, ...content)\n }\n }\n\n /**\n * Deletes elements starting from an index.\n *\n * @param {number} index Index at which to start deleting elements\n * @param {number} [length=1] The number of elements to remove. Defaults to 1.\n */\n delete (index, length = 1) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListDelete(transaction, this, index, length)\n })\n } else {\n // @ts-ignore _prelimContent is defined because this is not yet integrated\n this._prelimContent.splice(index, length)\n }\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @return {Array}\n */\n toArray () {\n return typeListToArray(this)\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {AbstractUpdateEncoder} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlFragmentRefID)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {YXmlFragment}\n *\n * @private\n * @function\n */\nexport const readYXmlFragment = decoder => new YXmlFragment()\n","\nimport {\n YXmlFragment,\n transact,\n typeMapDelete,\n typeMapSet,\n typeMapGet,\n typeMapGetAll,\n typeListForEach,\n YXmlElementRefID,\n AbstractUpdateDecoder, AbstractUpdateEncoder, Snapshot, Doc, Item // eslint-disable-line\n} from '../internals.js'\n\n/**\n * An YXmlElement imitates the behavior of a\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}.\n *\n * * An YXmlElement has attributes (key value pairs)\n * * An YXmlElement has childElements that must inherit from YXmlElement\n */\nexport class YXmlElement extends YXmlFragment {\n constructor (nodeName = 'UNDEFINED') {\n super()\n this.nodeName = nodeName\n /**\n * @type {Map|null}\n */\n this._prelimAttrs = new Map()\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n ;(/** @type {Map} */ (this._prelimAttrs)).forEach((value, key) => {\n this.setAttribute(key, value)\n })\n this._prelimAttrs = null\n }\n\n /**\n * Creates an Item with the same effect as this Item (without position effect)\n *\n * @return {YXmlElement}\n */\n _copy () {\n return new YXmlElement(this.nodeName)\n }\n\n /**\n * Returns the XML serialization of this YXmlElement.\n * The attributes are ordered by attribute-name, so you can easily use this\n * method to compare YXmlElements\n *\n * @return {string} The string representation of this type.\n *\n * @public\n */\n toString () {\n const attrs = this.getAttributes()\n const stringBuilder = []\n const keys = []\n for (const key in attrs) {\n keys.push(key)\n }\n keys.sort()\n const keysLen = keys.length\n for (let i = 0; i < keysLen; i++) {\n const key = keys[i]\n stringBuilder.push(key + '=\"' + attrs[key] + '\"')\n }\n const nodeName = this.nodeName.toLocaleLowerCase()\n const attrsString = stringBuilder.length > 0 ? ' ' + stringBuilder.join(' ') : ''\n return `<${nodeName}${attrsString}>${super.toString()}`\n }\n\n /**\n * Removes an attribute from this YXmlElement.\n *\n * @param {String} attributeName The attribute name that is to be removed.\n *\n * @public\n */\n removeAttribute (attributeName) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, attributeName)\n })\n } else {\n /** @type {Map} */ (this._prelimAttrs).delete(attributeName)\n }\n }\n\n /**\n * Sets or updates an attribute.\n *\n * @param {String} attributeName The attribute name that is to be set.\n * @param {String} attributeValue The attribute value that is to be set.\n *\n * @public\n */\n setAttribute (attributeName, attributeValue) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, attributeName, attributeValue)\n })\n } else {\n /** @type {Map} */ (this._prelimAttrs).set(attributeName, attributeValue)\n }\n }\n\n /**\n * Returns an attribute value that belongs to the attribute name.\n *\n * @param {String} attributeName The attribute name that identifies the\n * queried value.\n * @return {String} The queried attribute value.\n *\n * @public\n */\n getAttribute (attributeName) {\n return /** @type {any} */ (typeMapGet(this, attributeName))\n }\n\n /**\n * Returns all attribute name/value pairs in a JSON Object.\n *\n * @param {Snapshot} [snapshot]\n * @return {Object} A JSON Object that describes the attributes.\n *\n * @public\n */\n getAttributes (snapshot) {\n return typeMapGetAll(this)\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks={}] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const dom = _document.createElement(this.nodeName)\n const attrs = this.getAttributes()\n for (const key in attrs) {\n dom.setAttribute(key, attrs[key])\n }\n typeListForEach(this, yxml => {\n dom.appendChild(yxml.toDOM(_document, hooks, binding))\n })\n if (binding !== undefined) {\n binding._createAssociation(dom, this)\n }\n return dom\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {AbstractUpdateEncoder} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlElementRefID)\n encoder.writeKey(this.nodeName)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {YXmlElement}\n *\n * @function\n */\nexport const readYXmlElement = decoder => new YXmlElement(decoder.readKey())\n","\nimport {\n YEvent,\n YXmlElement, YXmlFragment, Transaction // eslint-disable-line\n} from '../internals.js'\n\n/**\n * An Event that describes changes on a YXml Element or Yxml Fragment\n */\nexport class YXmlEvent extends YEvent {\n /**\n * @param {YXmlElement|YXmlFragment} target The target on which the event is created.\n * @param {Set} subs The set of changed attributes. `null` is included if the\n * child list changed.\n * @param {Transaction} transaction The transaction instance with wich the\n * change was created.\n */\n constructor (target, subs, transaction) {\n super(target, transaction)\n /**\n * Whether the children changed.\n * @type {Boolean}\n * @private\n */\n this.childListChanged = false\n /**\n * Set of all changed attributes.\n * @type {Set}\n */\n this.attributesChanged = new Set()\n subs.forEach((sub) => {\n if (sub === null) {\n this.childListChanged = true\n } else {\n this.attributesChanged.add(sub)\n }\n })\n }\n}\n","\nimport {\n YMap,\n YXmlHookRefID,\n AbstractUpdateDecoder, AbstractUpdateEncoder // eslint-disable-line\n} from '../internals.js'\n\n/**\n * You can manage binding to a custom type with YXmlHook.\n *\n * @extends {YMap}\n */\nexport class YXmlHook extends YMap {\n /**\n * @param {string} hookName nodeName of the Dom Node.\n */\n constructor (hookName) {\n super()\n /**\n * @type {string}\n */\n this.hookName = hookName\n }\n\n /**\n * Creates an Item with the same effect as this Item (without position effect)\n */\n _copy () {\n return new YXmlHook(this.hookName)\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object.} [hooks] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type\n * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const hook = hooks[this.hookName]\n let dom\n if (hook !== undefined) {\n dom = hook.createDom(this)\n } else {\n dom = document.createElement(this.hookName)\n }\n dom.setAttribute('data-yjs-hook', this.hookName)\n if (binding !== undefined) {\n binding._createAssociation(dom, this)\n }\n return dom\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {AbstractUpdateEncoder} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlHookRefID)\n encoder.writeKey(this.hookName)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {YXmlHook}\n *\n * @private\n * @function\n */\nexport const readYXmlHook = decoder =>\n new YXmlHook(decoder.readKey())\n","\nimport {\n YText,\n YXmlTextRefID,\n AbstractUpdateDecoder, AbstractUpdateEncoder // eslint-disable-line\n} from '../internals.js'\n\n/**\n * Represents text in a Dom Element. In the future this type will also handle\n * simple formatting information like bold and italic.\n */\nexport class YXmlText extends YText {\n _copy () {\n return new YXmlText()\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlText.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks, binding) {\n const dom = _document.createTextNode(this.toString())\n if (binding !== undefined) {\n binding._createAssociation(dom, this)\n }\n return dom\n }\n\n toString () {\n // @ts-ignore\n return this.toDelta().map(delta => {\n const nestedNodes = []\n for (const nodeName in delta.attributes) {\n const attrs = []\n for (const key in delta.attributes[nodeName]) {\n attrs.push({ key, value: delta.attributes[nodeName][key] })\n }\n // sort attributes to get a unique order\n attrs.sort((a, b) => a.key < b.key ? -1 : 1)\n nestedNodes.push({ nodeName, attrs })\n }\n // sort node order to get a unique order\n nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1)\n // now convert to dom string\n let str = ''\n for (let i = 0; i < nestedNodes.length; i++) {\n const node = nestedNodes[i]\n str += `<${node.nodeName}`\n for (let j = 0; j < node.attrs.length; j++) {\n const attr = node.attrs[j]\n str += ` ${attr.key}=\"${attr.value}\"`\n }\n str += '>'\n }\n str += delta.insert\n for (let i = nestedNodes.length - 1; i >= 0; i--) {\n str += ``\n }\n return str\n }).join('')\n }\n\n /**\n * @return {string}\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlTextRefID)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {YXmlText}\n *\n * @private\n * @function\n */\nexport const readYXmlText = decoder => new YXmlText()\n","\nimport {\n AbstractUpdateEncoder, ID, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error.js'\n\nexport class AbstractStruct {\n /**\n * @param {ID} id\n * @param {number} length\n */\n constructor (id, length) {\n this.id = id\n this.length = length\n }\n\n /**\n * @type {boolean}\n */\n get deleted () {\n throw error.methodUnimplemented()\n }\n\n /**\n * Merge this struct with the item to the right.\n * This method is already assuming that `this.id.clock + this.length === this.id.clock`.\n * Also this method does *not* remove right from StructStore!\n * @param {AbstractStruct} right\n * @return {boolean} wether this merged with right\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder The encoder to write data to.\n * @param {number} offset\n * @param {number} encodingRef\n */\n write (encoder, offset, encodingRef) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n throw error.methodUnimplemented()\n }\n}\n","\nimport {\n AbstractStruct,\n addStruct,\n AbstractUpdateEncoder, StructStore, Transaction, ID // eslint-disable-line\n} from '../internals.js'\n\nexport const structGCRefNumber = 0\n\n/**\n * @private\n */\nexport class GC extends AbstractStruct {\n get deleted () {\n return true\n }\n\n delete () {}\n\n /**\n * @param {GC} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.length += right.length\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n if (offset > 0) {\n this.id.clock += offset\n this.length -= offset\n }\n addStruct(transaction.doc.store, this)\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeInfo(structGCRefNumber)\n encoder.writeLen(this.length - offset)\n }\n\n /**\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n return null\n }\n}\n","import {\n AbstractUpdateDecoder, AbstractUpdateEncoder, StructStore, Item, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error.js'\n\nexport class ContentBinary {\n /**\n * @param {Uint8Array} content\n */\n constructor (content) {\n this.content = content\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.content]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentBinary}\n */\n copy () {\n return new ContentBinary(this.content)\n }\n\n /**\n * @param {number} offset\n * @return {ContentBinary}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentBinary} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeBuf(this.content)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 3\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentBinary}\n */\nexport const readContentBinary = decoder => new ContentBinary(decoder.readBuf())\n","\nimport {\n addToDeleteSet,\n AbstractUpdateDecoder, AbstractUpdateEncoder, StructStore, Item, Transaction // eslint-disable-line\n} from '../internals.js'\n\nexport class ContentDeleted {\n /**\n * @param {number} len\n */\n constructor (len) {\n this.len = len\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.len\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return []\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return false\n }\n\n /**\n * @return {ContentDeleted}\n */\n copy () {\n return new ContentDeleted(this.len)\n }\n\n /**\n * @param {number} offset\n * @return {ContentDeleted}\n */\n splice (offset) {\n const right = new ContentDeleted(this.len - offset)\n this.len = offset\n return right\n }\n\n /**\n * @param {ContentDeleted} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.len += right.len\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len)\n item.markDeleted()\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeLen(this.len - offset)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 1\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentDeleted}\n */\nexport const readContentDeleted = decoder => new ContentDeleted(decoder.readLen())\n","\nimport {\n Doc, AbstractUpdateDecoder, AbstractUpdateEncoder, StructStore, Transaction, Item // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error.js'\n\n/**\n * @private\n */\nexport class ContentDoc {\n /**\n * @param {Doc} doc\n */\n constructor (doc) {\n if (doc._item) {\n console.error('This document was already integrated as a sub-document. You should create a second instance instead with the same guid.')\n }\n /**\n * @type {Doc}\n */\n this.doc = doc\n /**\n * @type {any}\n */\n const opts = {}\n this.opts = opts\n if (!doc.gc) {\n opts.gc = false\n }\n if (doc.autoLoad) {\n opts.autoLoad = true\n }\n if (doc.meta !== null) {\n opts.meta = doc.meta\n }\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.doc]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentDoc}\n */\n copy () {\n return new ContentDoc(this.doc)\n }\n\n /**\n * @param {number} offset\n * @return {ContentDoc}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentDoc} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n // this needs to be reflected in doc.destroy as well\n this.doc._item = item\n transaction.subdocsAdded.add(this.doc)\n if (this.doc.shouldLoad) {\n transaction.subdocsLoaded.add(this.doc)\n }\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n if (transaction.subdocsAdded.has(this.doc)) {\n transaction.subdocsAdded.delete(this.doc)\n } else {\n transaction.subdocsRemoved.add(this.doc)\n }\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) { }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeString(this.doc.guid)\n encoder.writeAny(this.opts)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 9\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentDoc}\n */\nexport const readContentDoc = decoder => new ContentDoc(new Doc({ guid: decoder.readString(), ...decoder.readAny() }))\n","\nimport {\n AbstractUpdateDecoder, AbstractUpdateEncoder, StructStore, Item, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error.js'\n\n/**\n * @private\n */\nexport class ContentEmbed {\n /**\n * @param {Object} embed\n */\n constructor (embed) {\n this.embed = embed\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.embed]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentEmbed}\n */\n copy () {\n return new ContentEmbed(this.embed)\n }\n\n /**\n * @param {number} offset\n * @return {ContentEmbed}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentEmbed} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeJSON(this.embed)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 5\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentEmbed}\n */\nexport const readContentEmbed = decoder => new ContentEmbed(decoder.readJSON())\n","\nimport {\n AbstractType, AbstractUpdateDecoder, AbstractUpdateEncoder, Item, StructStore, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error.js'\n\n/**\n * @private\n */\nexport class ContentFormat {\n /**\n * @param {string} key\n * @param {Object} value\n */\n constructor (key, value) {\n this.key = key\n this.value = value\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return []\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return false\n }\n\n /**\n * @return {ContentFormat}\n */\n copy () {\n return new ContentFormat(this.key, this.value)\n }\n\n /**\n * @param {number} offset\n * @return {ContentFormat}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentFormat} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n // @todo searchmarker are currently unsupported for rich text documents\n /** @type {AbstractType} */ (item.parent)._searchMarker = null\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeKey(this.key)\n encoder.writeJSON(this.value)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 6\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentFormat}\n */\nexport const readContentFormat = decoder => new ContentFormat(decoder.readString(), decoder.readJSON())\n","import {\n AbstractUpdateDecoder, AbstractUpdateEncoder, Transaction, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @private\n */\nexport class ContentJSON {\n /**\n * @param {Array} arr\n */\n constructor (arr) {\n /**\n * @type {Array}\n */\n this.arr = arr\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.arr.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.arr\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentJSON}\n */\n copy () {\n return new ContentJSON(this.arr)\n }\n\n /**\n * @param {number} offset\n * @return {ContentJSON}\n */\n splice (offset) {\n const right = new ContentJSON(this.arr.slice(offset))\n this.arr = this.arr.slice(0, offset)\n return right\n }\n\n /**\n * @param {ContentJSON} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.arr = this.arr.concat(right.arr)\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n const len = this.arr.length\n encoder.writeLen(len - offset)\n for (let i = offset; i < len; i++) {\n const c = this.arr[i]\n encoder.writeString(c === undefined ? 'undefined' : JSON.stringify(c))\n }\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 2\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentJSON}\n */\nexport const readContentJSON = decoder => {\n const len = decoder.readLen()\n const cs = []\n for (let i = 0; i < len; i++) {\n const c = decoder.readString()\n if (c === 'undefined') {\n cs.push(undefined)\n } else {\n cs.push(JSON.parse(c))\n }\n }\n return new ContentJSON(cs)\n}\n","import {\n AbstractUpdateDecoder, AbstractUpdateEncoder, Transaction, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\nexport class ContentAny {\n /**\n * @param {Array} arr\n */\n constructor (arr) {\n /**\n * @type {Array}\n */\n this.arr = arr\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.arr.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.arr\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentAny}\n */\n copy () {\n return new ContentAny(this.arr)\n }\n\n /**\n * @param {number} offset\n * @return {ContentAny}\n */\n splice (offset) {\n const right = new ContentAny(this.arr.slice(offset))\n this.arr = this.arr.slice(0, offset)\n return right\n }\n\n /**\n * @param {ContentAny} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.arr = this.arr.concat(right.arr)\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n const len = this.arr.length\n encoder.writeLen(len - offset)\n for (let i = offset; i < len; i++) {\n const c = this.arr[i]\n encoder.writeAny(c)\n }\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 8\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentAny}\n */\nexport const readContentAny = decoder => {\n const len = decoder.readLen()\n const cs = []\n for (let i = 0; i < len; i++) {\n cs.push(decoder.readAny())\n }\n return new ContentAny(cs)\n}\n","import {\n AbstractUpdateDecoder, AbstractUpdateEncoder, Transaction, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @private\n */\nexport class ContentString {\n /**\n * @param {string} str\n */\n constructor (str) {\n /**\n * @type {string}\n */\n this.str = str\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.str.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.str.split('')\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentString}\n */\n copy () {\n return new ContentString(this.str)\n }\n\n /**\n * @param {number} offset\n * @return {ContentString}\n */\n splice (offset) {\n const right = new ContentString(this.str.slice(offset))\n this.str = this.str.slice(0, offset)\n\n // Prevent encoding invalid documents because of splitting of surrogate pairs: https://github.com/yjs/yjs/issues/248\n const firstCharCode = this.str.charCodeAt(offset - 1)\n if (firstCharCode >= 0xD800 && firstCharCode <= 0xDBFF) {\n // Last character of the left split is the start of a surrogate utf16/ucs2 pair.\n // We don't support splitting of surrogate pairs because this may lead to invalid documents.\n // Replace the invalid character with a unicode replacement character (� / U+FFFD)\n this.str = this.str.slice(0, offset - 1) + '�'\n // replace right as well\n right.str = '�' + right.str.slice(1)\n }\n return right\n }\n\n /**\n * @param {ContentString} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.str += right.str\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeString(offset === 0 ? this.str : this.str.slice(offset))\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 4\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentString}\n */\nexport const readContentString = decoder => new ContentString(decoder.readString())\n","\nimport {\n readYArray,\n readYMap,\n readYText,\n readYXmlElement,\n readYXmlFragment,\n readYXmlHook,\n readYXmlText,\n AbstractUpdateDecoder, AbstractUpdateEncoder, StructStore, Transaction, Item, YEvent, AbstractType // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error.js'\n\n/**\n * @type {Array>}\n * @private\n */\nexport const typeRefs = [\n readYArray,\n readYMap,\n readYText,\n readYXmlElement,\n readYXmlFragment,\n readYXmlHook,\n readYXmlText\n]\n\nexport const YArrayRefID = 0\nexport const YMapRefID = 1\nexport const YTextRefID = 2\nexport const YXmlElementRefID = 3\nexport const YXmlFragmentRefID = 4\nexport const YXmlHookRefID = 5\nexport const YXmlTextRefID = 6\n\n/**\n * @private\n */\nexport class ContentType {\n /**\n * @param {AbstractType} type\n */\n constructor (type) {\n /**\n * @type {AbstractType}\n */\n this.type = type\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.type]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentType}\n */\n copy () {\n return new ContentType(this.type._copy())\n }\n\n /**\n * @param {number} offset\n * @return {ContentType}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentType} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n this.type._integrate(transaction.doc, item)\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n let item = this.type._start\n while (item !== null) {\n if (!item.deleted) {\n item.delete(transaction)\n } else {\n // Whis will be gc'd later and we want to merge it if possible\n // We try to merge all deleted items after each transaction,\n // but we have no knowledge about that this needs to be merged\n // since it is not in transaction.ds. Hence we add it to transaction._mergeStructs\n transaction._mergeStructs.push(item)\n }\n item = item.right\n }\n this.type._map.forEach(item => {\n if (!item.deleted) {\n item.delete(transaction)\n } else {\n // same as above\n transaction._mergeStructs.push(item)\n }\n })\n transaction.changed.delete(this.type)\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) {\n let item = this.type._start\n while (item !== null) {\n item.gc(store, true)\n item = item.right\n }\n this.type._start = null\n this.type._map.forEach(/** @param {Item | null} item */ (item) => {\n while (item !== null) {\n item.gc(store, true)\n item = item.left\n }\n })\n this.type._map = new Map()\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n this.type._write(encoder)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 7\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentType}\n */\nexport const readContentType = decoder => new ContentType(typeRefs[decoder.readTypeRef()](decoder))\n","\nimport {\n GC,\n getState,\n AbstractStruct,\n replaceStruct,\n addStruct,\n addToDeleteSet,\n findRootTypeKey,\n compareIDs,\n getItem,\n getItemCleanEnd,\n getItemCleanStart,\n readContentDeleted,\n readContentBinary,\n readContentJSON,\n readContentAny,\n readContentString,\n readContentEmbed,\n readContentDoc,\n createID,\n readContentFormat,\n readContentType,\n addChangedTypeToTransaction,\n AbstractUpdateDecoder, AbstractUpdateEncoder, ContentType, ContentDeleted, StructStore, ID, AbstractType, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error.js'\nimport * as binary from 'lib0/binary.js'\n\n/**\n * @todo This should return several items\n *\n * @param {StructStore} store\n * @param {ID} id\n * @return {{item:Item, diff:number}}\n */\nexport const followRedone = (store, id) => {\n /**\n * @type {ID|null}\n */\n let nextID = id\n let diff = 0\n let item\n do {\n if (diff > 0) {\n nextID = createID(nextID.client, nextID.clock + diff)\n }\n item = getItem(store, nextID)\n diff = nextID.clock - item.id.clock\n nextID = item.redone\n } while (nextID !== null && item instanceof Item)\n return {\n item, diff\n }\n}\n\n/**\n * Make sure that neither item nor any of its parents is ever deleted.\n *\n * This property does not persist when storing it into a database or when\n * sending it to other peers\n *\n * @param {Item|null} item\n * @param {boolean} keep\n */\nexport const keepItem = (item, keep) => {\n while (item !== null && item.keep !== keep) {\n item.keep = keep\n item = /** @type {AbstractType} */ (item.parent)._item\n }\n}\n\n/**\n * Split leftItem into two items\n * @param {Transaction} transaction\n * @param {Item} leftItem\n * @param {number} diff\n * @return {Item}\n *\n * @function\n * @private\n */\nexport const splitItem = (transaction, leftItem, diff) => {\n // create rightItem\n const { client, clock } = leftItem.id\n const rightItem = new Item(\n createID(client, clock + diff),\n leftItem,\n createID(client, clock + diff - 1),\n leftItem.right,\n leftItem.rightOrigin,\n leftItem.parent,\n leftItem.parentSub,\n leftItem.content.splice(diff)\n )\n if (leftItem.deleted) {\n rightItem.markDeleted()\n }\n if (leftItem.keep) {\n rightItem.keep = true\n }\n if (leftItem.redone !== null) {\n rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff)\n }\n // update left (do not set leftItem.rightOrigin as it will lead to problems when syncing)\n leftItem.right = rightItem\n // update right\n if (rightItem.right !== null) {\n rightItem.right.left = rightItem\n }\n // right is more specific.\n transaction._mergeStructs.push(rightItem)\n // update parent._map\n if (rightItem.parentSub !== null && rightItem.right === null) {\n /** @type {AbstractType} */ (rightItem.parent)._map.set(rightItem.parentSub, rightItem)\n }\n leftItem.length = diff\n return rightItem\n}\n\n/**\n * Redoes the effect of this operation.\n *\n * @param {Transaction} transaction The Yjs instance.\n * @param {Item} item\n * @param {Set} redoitems\n *\n * @return {Item|null}\n *\n * @private\n */\nexport const redoItem = (transaction, item, redoitems) => {\n const doc = transaction.doc\n const store = doc.store\n const ownClientID = doc.clientID\n const redone = item.redone\n if (redone !== null) {\n return getItemCleanStart(transaction, redone)\n }\n let parentItem = /** @type {AbstractType} */ (item.parent)._item\n /**\n * @type {Item|null}\n */\n let left\n /**\n * @type {Item|null}\n */\n let right\n if (item.parentSub === null) {\n // Is an array item. Insert at the old position\n left = item.left\n right = item\n } else {\n // Is a map item. Insert as current value\n left = item\n while (left.right !== null) {\n left = left.right\n if (left.id.client !== ownClientID) {\n // It is not possible to redo this item because it conflicts with a\n // change from another client\n return null\n }\n }\n if (left.right !== null) {\n left = /** @type {Item} */ (/** @type {AbstractType} */ (item.parent)._map.get(item.parentSub))\n }\n right = null\n }\n // make sure that parent is redone\n if (parentItem !== null && parentItem.deleted === true && parentItem.redone === null) {\n // try to undo parent if it will be undone anyway\n if (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems) === null) {\n return null\n }\n }\n if (parentItem !== null && parentItem.redone !== null) {\n while (parentItem.redone !== null) {\n parentItem = getItemCleanStart(transaction, parentItem.redone)\n }\n // find next cloned_redo items\n while (left !== null) {\n /**\n * @type {Item|null}\n */\n let leftTrace = left\n // trace redone until parent matches\n while (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item !== parentItem) {\n leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone)\n }\n if (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item === parentItem) {\n left = leftTrace\n break\n }\n left = left.left\n }\n while (right !== null) {\n /**\n * @type {Item|null}\n */\n let rightTrace = right\n // trace redone until parent matches\n while (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item !== parentItem) {\n rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone)\n }\n if (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item === parentItem) {\n right = rightTrace\n break\n }\n right = right.right\n }\n }\n const nextClock = getState(store, ownClientID)\n const nextId = createID(ownClientID, nextClock)\n const redoneItem = new Item(\n nextId,\n left, left && left.lastId,\n right, right && right.id,\n parentItem === null ? item.parent : /** @type {ContentType} */ (parentItem.content).type,\n item.parentSub,\n item.content.copy()\n )\n item.redone = nextId\n keepItem(redoneItem, true)\n redoneItem.integrate(transaction, 0)\n return redoneItem\n}\n\n/**\n * Abstract class that represents any content.\n */\nexport class Item extends AbstractStruct {\n /**\n * @param {ID} id\n * @param {Item | null} left\n * @param {ID | null} origin\n * @param {Item | null} right\n * @param {ID | null} rightOrigin\n * @param {AbstractType|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it.\n * @param {string | null} parentSub\n * @param {AbstractContent} content\n */\n constructor (id, left, origin, right, rightOrigin, parent, parentSub, content) {\n super(id, content.getLength())\n /**\n * The item that was originally to the left of this item.\n * @type {ID | null}\n */\n this.origin = origin\n /**\n * The item that is currently to the left of this item.\n * @type {Item | null}\n */\n this.left = left\n /**\n * The item that is currently to the right of this item.\n * @type {Item | null}\n */\n this.right = right\n /**\n * The item that was originally to the right of this item.\n * @type {ID | null}\n */\n this.rightOrigin = rightOrigin\n /**\n * @type {AbstractType|ID|null}\n */\n this.parent = parent\n /**\n * If the parent refers to this item with some kind of key (e.g. YMap, the\n * key is specified here. The key is then used to refer to the list in which\n * to insert this item. If `parentSub = null` type._start is the list in\n * which to insert to. Otherwise it is `parent._map`.\n * @type {String | null}\n */\n this.parentSub = parentSub\n /**\n * If this type's effect is reundone this type refers to the type that undid\n * this operation.\n * @type {ID | null}\n */\n this.redone = null\n /**\n * @type {AbstractContent}\n */\n this.content = content\n /**\n * bit1: keep\n * bit2: countable\n * bit3: deleted\n * bit4: mark - mark node as fast-search-marker\n * @type {number} byte\n */\n this.info = this.content.isCountable() ? binary.BIT2 : 0\n }\n\n /**\n * This is used to mark the item as an indexed fast-search marker\n *\n * @type {boolean}\n */\n set marker (isMarked) {\n if (((this.info & binary.BIT4) > 0) !== isMarked) {\n this.info ^= binary.BIT4\n }\n }\n\n get marker () {\n return (this.info & binary.BIT4) > 0\n }\n\n /**\n * If true, do not garbage collect this Item.\n */\n get keep () {\n return (this.info & binary.BIT1) > 0\n }\n\n set keep (doKeep) {\n if (this.keep !== doKeep) {\n this.info ^= binary.BIT1\n }\n }\n\n get countable () {\n return (this.info & binary.BIT2) > 0\n }\n\n /**\n * Whether this item was deleted or not.\n * @type {Boolean}\n */\n get deleted () {\n return (this.info & binary.BIT3) > 0\n }\n\n set deleted (doDelete) {\n if (this.deleted !== doDelete) {\n this.info ^= binary.BIT3\n }\n }\n\n markDeleted () {\n this.info |= binary.BIT3\n }\n\n /**\n * Return the creator clientID of the missing op or define missing items and return null.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) {\n return this.origin.client\n }\n if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) {\n return this.rightOrigin.client\n }\n if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) {\n return this.parent.client\n }\n\n // We have all missing ids, now find the items\n\n if (this.origin) {\n this.left = getItemCleanEnd(transaction, store, this.origin)\n this.origin = this.left.lastId\n }\n if (this.rightOrigin) {\n this.right = getItemCleanStart(transaction, this.rightOrigin)\n this.rightOrigin = this.right.id\n }\n if ((this.left && this.left.constructor === GC) || (this.right && this.right.constructor === GC)) {\n this.parent = null\n }\n // only set parent if this shouldn't be garbage collected\n if (!this.parent) {\n if (this.left && this.left.constructor === Item) {\n this.parent = this.left.parent\n this.parentSub = this.left.parentSub\n }\n if (this.right && this.right.constructor === Item) {\n this.parent = this.right.parent\n this.parentSub = this.right.parentSub\n }\n } else if (this.parent.constructor === ID) {\n const parentItem = getItem(store, this.parent)\n if (parentItem.constructor === GC) {\n this.parent = null\n } else {\n this.parent = /** @type {ContentType} */ (parentItem.content).type\n }\n }\n return null\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n if (offset > 0) {\n this.id.clock += offset\n this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1))\n this.origin = this.left.lastId\n this.content = this.content.splice(offset)\n this.length -= offset\n }\n\n if (this.parent) {\n if ((!this.left && (!this.right || this.right.left !== null)) || (this.left && this.left.right !== this.right)) {\n /**\n * @type {Item|null}\n */\n let left = this.left\n\n /**\n * @type {Item|null}\n */\n let o\n // set o to the first conflicting item\n if (left !== null) {\n o = left.right\n } else if (this.parentSub !== null) {\n o = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null\n while (o !== null && o.left !== null) {\n o = o.left\n }\n } else {\n o = /** @type {AbstractType} */ (this.parent)._start\n }\n // TODO: use something like DeleteSet here (a tree implementation would be best)\n // @todo use global set definitions\n /**\n * @type {Set}\n */\n const conflictingItems = new Set()\n /**\n * @type {Set}\n */\n const itemsBeforeOrigin = new Set()\n // Let c in conflictingItems, b in itemsBeforeOrigin\n // ***{origin}bbbb{this}{c,b}{c,b}{o}***\n // Note that conflictingItems is a subset of itemsBeforeOrigin\n while (o !== null && o !== this.right) {\n itemsBeforeOrigin.add(o)\n conflictingItems.add(o)\n if (compareIDs(this.origin, o.origin)) {\n // case 1\n if (o.id.client < this.id.client) {\n left = o\n conflictingItems.clear()\n } else if (compareIDs(this.rightOrigin, o.rightOrigin)) {\n // this and o are conflicting and point to the same integration points. The id decides which item comes first.\n // Since this is to the left of o, we can break here\n break\n } // else, o might be integrated before an item that this conflicts with. If so, we will find it in the next iterations\n } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) { // use getItem instead of getItemCleanEnd because we don't want / need to split items.\n // case 2\n if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) {\n left = o\n conflictingItems.clear()\n }\n } else {\n break\n }\n o = o.right\n }\n this.left = left\n }\n // reconnect left/right + update parent map/start if necessary\n if (this.left !== null) {\n const right = this.left.right\n this.right = right\n this.left.right = this\n } else {\n let r\n if (this.parentSub !== null) {\n r = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null\n while (r !== null && r.left !== null) {\n r = r.left\n }\n } else {\n r = /** @type {AbstractType} */ (this.parent)._start\n ;/** @type {AbstractType} */ (this.parent)._start = this\n }\n this.right = r\n }\n if (this.right !== null) {\n this.right.left = this\n } else if (this.parentSub !== null) {\n // set as current parent value if right === null and this is parentSub\n /** @type {AbstractType} */ (this.parent)._map.set(this.parentSub, this)\n if (this.left !== null) {\n // this is the current attribute value of parent. delete right\n this.left.delete(transaction)\n }\n }\n // adjust length of parent\n if (this.parentSub === null && this.countable && !this.deleted) {\n /** @type {AbstractType} */ (this.parent)._length += this.length\n }\n addStruct(transaction.doc.store, this)\n this.content.integrate(transaction, this)\n // add parent to transaction.changed\n addChangedTypeToTransaction(transaction, /** @type {AbstractType} */ (this.parent), this.parentSub)\n if ((/** @type {AbstractType} */ (this.parent)._item !== null && /** @type {AbstractType} */ (this.parent)._item.deleted) || (this.parentSub !== null && this.right !== null)) {\n // delete if parent is deleted or if this is not the current attribute value of parent\n this.delete(transaction)\n }\n } else {\n // parent is not defined. Integrate GC struct instead\n new GC(this.id, this.length).integrate(transaction, 0)\n }\n }\n\n /**\n * Returns the next non-deleted item\n */\n get next () {\n let n = this.right\n while (n !== null && n.deleted) {\n n = n.right\n }\n return n\n }\n\n /**\n * Returns the previous non-deleted item\n */\n get prev () {\n let n = this.left\n while (n !== null && n.deleted) {\n n = n.left\n }\n return n\n }\n\n /**\n * Computes the last content address of this Item.\n */\n get lastId () {\n // allocating ids is pretty costly because of the amount of ids created, so we try to reuse whenever possible\n return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1)\n }\n\n /**\n * Try to merge two items\n *\n * @param {Item} right\n * @return {boolean}\n */\n mergeWith (right) {\n if (\n compareIDs(right.origin, this.lastId) &&\n this.right === right &&\n compareIDs(this.rightOrigin, right.rightOrigin) &&\n this.id.client === right.id.client &&\n this.id.clock + this.length === right.id.clock &&\n this.deleted === right.deleted &&\n this.redone === null &&\n right.redone === null &&\n this.content.constructor === right.content.constructor &&\n this.content.mergeWith(right.content)\n ) {\n if (right.keep) {\n this.keep = true\n }\n this.right = right.right\n if (this.right !== null) {\n this.right.left = this\n }\n this.length += right.length\n return true\n }\n return false\n }\n\n /**\n * Mark this Item as deleted.\n *\n * @param {Transaction} transaction\n */\n delete (transaction) {\n if (!this.deleted) {\n const parent = /** @type {AbstractType} */ (this.parent)\n // adjust the length of parent\n if (this.countable && this.parentSub === null) {\n parent._length -= this.length\n }\n this.markDeleted()\n addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length)\n addChangedTypeToTransaction(transaction, parent, this.parentSub)\n this.content.delete(transaction)\n }\n }\n\n /**\n * @param {StructStore} store\n * @param {boolean} parentGCd\n */\n gc (store, parentGCd) {\n if (!this.deleted) {\n throw error.unexpectedCase()\n }\n this.content.gc(store)\n if (parentGCd) {\n replaceStruct(store, this, new GC(this.id, this.length))\n } else {\n this.content = new ContentDeleted(this.length)\n }\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {AbstractUpdateEncoder} encoder The encoder to write data to.\n * @param {number} offset\n */\n write (encoder, offset) {\n const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin\n const rightOrigin = this.rightOrigin\n const parentSub = this.parentSub\n const info = (this.content.getRef() & binary.BITS5) |\n (origin === null ? 0 : binary.BIT8) | // origin is defined\n (rightOrigin === null ? 0 : binary.BIT7) | // right origin is defined\n (parentSub === null ? 0 : binary.BIT6) // parentSub is non-null\n encoder.writeInfo(info)\n if (origin !== null) {\n encoder.writeLeftID(origin)\n }\n if (rightOrigin !== null) {\n encoder.writeRightID(rightOrigin)\n }\n if (origin === null && rightOrigin === null) {\n const parent = /** @type {AbstractType} */ (this.parent)\n const parentItem = parent._item\n if (parentItem === null) {\n // parent type on y._map\n // find the correct key\n const ykey = findRootTypeKey(parent)\n encoder.writeParentInfo(true) // write parentYKey\n encoder.writeString(ykey)\n } else {\n encoder.writeParentInfo(false) // write parent id\n encoder.writeLeftID(parentItem.id)\n }\n if (parentSub !== null) {\n encoder.writeString(parentSub)\n }\n }\n this.content.write(encoder, offset)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @param {number} info\n */\nexport const readItemContent = (decoder, info) => contentRefs[info & binary.BITS5](decoder)\n\n/**\n * A lookup map for reading Item content.\n *\n * @type {Array}\n */\nexport const contentRefs = [\n () => { throw error.unexpectedCase() }, // GC is not ItemContent\n readContentDeleted, // 1\n readContentJSON, // 2\n readContentBinary, // 3\n readContentString, // 4\n readContentEmbed, // 5\n readContentFormat, // 6\n readContentType, // 7\n readContentAny, // 8\n readContentDoc // 9\n]\n\n/**\n * Do not implement this class!\n */\nexport class AbstractContent {\n /**\n * @return {number}\n */\n getLength () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n throw error.methodUnimplemented()\n }\n\n /**\n * Should return false if this Item is some kind of meta information\n * (e.g. format information).\n *\n * * Whether this Item should be addressable via `yarray.get(i)`\n * * Whether this Item should be counted when computing yarray.length\n *\n * @return {boolean}\n */\n isCountable () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {AbstractContent}\n */\n copy () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {number} offset\n * @return {AbstractContent}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {AbstractContent} right\n * @return {boolean}\n */\n mergeWith (right) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {number}\n */\n getRef () {\n throw error.methodUnimplemented()\n }\n}\n","/**\n * @module sync-protocol\n */\n\nimport * as encoding from 'lib0/encoding.js'\nimport * as decoding from 'lib0/decoding.js'\nimport * as Y from 'yjs'\n\n/**\n * @typedef {Map} StateMap\n */\n\n/**\n * Core Yjs defines three message types:\n * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.\n * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the the client is assured that\n * it received all information from the remote client.\n *\n * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection\n * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both\n * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.\n *\n * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.\n * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies\n * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the\n * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can\n * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them.\n * Therefore it is necesarry that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep1)\n const sv = Y.encodeStateVector(doc)\n encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep2)\n encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin) => {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n encoding.writeVarUint(encoder, messageYjsUpdate)\n encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {\n const messageType = decoding.readVarUint(decoder)\n switch (messageType) {\n case messageYjsSyncStep1:\n readSyncStep1(decoder, encoder, doc)\n break\n case messageYjsSyncStep2:\n readSyncStep2(decoder, doc, transactionOrigin)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n","\nimport * as t from 'lib0/testing.js'\nimport * as prng from 'lib0/prng.js'\nimport * as encoding from 'lib0/encoding.js'\nimport * as decoding from 'lib0/decoding.js'\nimport * as syncProtocol from 'y-protocols/sync.js'\nimport * as object from 'lib0/object.js'\nimport * as Y from '../src/internals.js'\nexport * from '../src/internals.js'\n\nif (typeof window !== 'undefined') {\n // @ts-ignore\n window.Y = Y // eslint-disable-line\n}\n\n/**\n * @param {TestYInstance} y // publish message created by `y` to all other online clients\n * @param {Uint8Array} m\n */\nconst broadcastMessage = (y, m) => {\n if (y.tc.onlineConns.has(y)) {\n y.tc.onlineConns.forEach(remoteYInstance => {\n if (remoteYInstance !== y) {\n remoteYInstance._receive(m, y)\n }\n })\n }\n}\n\nexport class TestYInstance extends Y.Doc {\n /**\n * @param {TestConnector} testConnector\n * @param {number} clientID\n */\n constructor (testConnector, clientID) {\n super()\n this.userID = clientID // overwriting clientID\n /**\n * @type {TestConnector}\n */\n this.tc = testConnector\n /**\n * @type {Map>}\n */\n this.receiving = new Map()\n testConnector.allConns.add(this)\n // set up observe on local model\n this.on('update', /** @param {Uint8Array} update @param {any} origin */ (update, origin) => {\n if (origin !== testConnector) {\n const encoder = encoding.createEncoder()\n syncProtocol.writeUpdate(encoder, update)\n broadcastMessage(this, encoding.toUint8Array(encoder))\n }\n })\n this.connect()\n }\n\n /**\n * Disconnect from TestConnector.\n */\n disconnect () {\n this.receiving = new Map()\n this.tc.onlineConns.delete(this)\n }\n\n /**\n * Append yourself to the list of known Y instances in testconnector.\n * Also initiate sync with all clients.\n */\n connect () {\n if (!this.tc.onlineConns.has(this)) {\n this.tc.onlineConns.add(this)\n const encoder = encoding.createEncoder()\n syncProtocol.writeSyncStep1(encoder, this)\n // publish SyncStep1\n broadcastMessage(this, encoding.toUint8Array(encoder))\n this.tc.onlineConns.forEach(remoteYInstance => {\n if (remoteYInstance !== this) {\n // remote instance sends instance to this instance\n const encoder = encoding.createEncoder()\n syncProtocol.writeSyncStep1(encoder, remoteYInstance)\n this._receive(encoding.toUint8Array(encoder), remoteYInstance)\n }\n })\n }\n }\n\n /**\n * Receive a message from another client. This message is only appended to the list of receiving messages.\n * TestConnector decides when this client actually reads this message.\n *\n * @param {Uint8Array} message\n * @param {TestYInstance} remoteClient\n */\n _receive (message, remoteClient) {\n let messages = this.receiving.get(remoteClient)\n if (messages === undefined) {\n messages = []\n this.receiving.set(remoteClient, messages)\n }\n messages.push(message)\n }\n}\n\n/**\n * Keeps track of TestYInstances.\n *\n * The TestYInstances add/remove themselves from the list of connections maiained in this object.\n * I think it makes sense. Deal with it.\n */\nexport class TestConnector {\n /**\n * @param {prng.PRNG} gen\n */\n constructor (gen) {\n /**\n * @type {Set}\n */\n this.allConns = new Set()\n /**\n * @type {Set}\n */\n this.onlineConns = new Set()\n /**\n * @type {prng.PRNG}\n */\n this.prng = gen\n }\n\n /**\n * Create a new Y instance and add it to the list of connections\n * @param {number} clientID\n */\n createY (clientID) {\n return new TestYInstance(this, clientID)\n }\n\n /**\n * Choose random connection and flush a random message from a random sender.\n *\n * If this function was unable to flush a message, because there are no more messages to flush, it returns false. true otherwise.\n * @return {boolean}\n */\n flushRandomMessage () {\n const gen = this.prng\n const conns = Array.from(this.onlineConns).filter(conn => conn.receiving.size > 0)\n if (conns.length > 0) {\n const receiver = prng.oneOf(gen, conns)\n const [sender, messages] = prng.oneOf(gen, Array.from(receiver.receiving))\n const m = messages.shift()\n if (messages.length === 0) {\n receiver.receiving.delete(sender)\n }\n if (m === undefined) {\n return this.flushRandomMessage()\n }\n const encoder = encoding.createEncoder()\n // console.log('receive (' + sender.userID + '->' + receiver.userID + '):\\n', syncProtocol.stringifySyncMessage(decoding.createDecoder(m), receiver))\n // do not publish data created when this function is executed (could be ss2 or update message)\n syncProtocol.readSyncMessage(decoding.createDecoder(m), encoder, receiver, receiver.tc)\n if (encoding.length(encoder) > 0) {\n // send reply message\n sender._receive(encoding.toUint8Array(encoder), receiver)\n }\n return true\n }\n return false\n }\n\n /**\n * @return {boolean} True iff this function actually flushed something\n */\n flushAllMessages () {\n let didSomething = false\n while (this.flushRandomMessage()) {\n didSomething = true\n }\n return didSomething\n }\n\n reconnectAll () {\n this.allConns.forEach(conn => conn.connect())\n }\n\n disconnectAll () {\n this.allConns.forEach(conn => conn.disconnect())\n }\n\n syncAll () {\n this.reconnectAll()\n this.flushAllMessages()\n }\n\n /**\n * @return {boolean} Whether it was possible to disconnect a randon connection.\n */\n disconnectRandom () {\n if (this.onlineConns.size === 0) {\n return false\n }\n prng.oneOf(this.prng, Array.from(this.onlineConns)).disconnect()\n return true\n }\n\n /**\n * @return {boolean} Whether it was possible to reconnect a random connection.\n */\n reconnectRandom () {\n /**\n * @type {Array}\n */\n const reconnectable = []\n this.allConns.forEach(conn => {\n if (!this.onlineConns.has(conn)) {\n reconnectable.push(conn)\n }\n })\n if (reconnectable.length === 0) {\n return false\n }\n prng.oneOf(this.prng, reconnectable).connect()\n return true\n }\n}\n\n/**\n * @template T\n * @param {t.TestCase} tc\n * @param {{users?:number}} conf\n * @param {InitTestObjectCallback} [initTestObject]\n * @return {{testObjects:Array,testConnector:TestConnector,users:Array,array0:Y.YArray,array1:Y.YArray,array2:Y.YArray,map0:Y.YMap,map1:Y.YMap,map2:Y.YMap,map3:Y.YMap,text0:Y.YText,text1:Y.YText,text2:Y.YText,xml0:Y.YXmlElement,xml1:Y.YXmlElement,xml2:Y.YXmlElement}}\n */\nexport const init = (tc, { users = 5 } = {}, initTestObject) => {\n /**\n * @type {Object}\n */\n const result = {\n users: []\n }\n const gen = tc.prng\n // choose an encoding approach at random\n if (prng.bool(gen)) {\n Y.useV2Encoding()\n } else {\n Y.useV1Encoding()\n }\n\n const testConnector = new TestConnector(gen)\n result.testConnector = testConnector\n for (let i = 0; i < users; i++) {\n const y = testConnector.createY(i)\n y.clientID = i\n result.users.push(y)\n result['array' + i] = y.getArray('array')\n result['map' + i] = y.getMap('map')\n result['xml' + i] = y.get('xml', Y.YXmlElement)\n result['text' + i] = y.getText('text')\n }\n testConnector.syncAll()\n result.testObjects = result.users.map(initTestObject || (() => null))\n Y.useV1Encoding()\n return /** @type {any} */ (result)\n}\n\n/**\n * 1. reconnect and flush all\n * 2. user 0 gc\n * 3. get type content\n * 4. disconnect & reconnect all (so gc is propagated)\n * 5. compare os, ds, ss\n *\n * @param {Array} users\n */\nexport const compare = users => {\n users.forEach(u => u.connect())\n while (users[0].tc.flushAllMessages()) {}\n const userArrayValues = users.map(u => u.getArray('array').toJSON())\n const userMapValues = users.map(u => u.getMap('map').toJSON())\n const userXmlValues = users.map(u => u.get('xml', Y.YXmlElement).toString())\n const userTextValues = users.map(u => u.getText('text').toDelta())\n for (const u of users) {\n t.assert(u.store.pendingDeleteReaders.length === 0)\n t.assert(u.store.pendingStack.length === 0)\n t.assert(u.store.pendingClientsStructRefs.size === 0)\n }\n // Test Array iterator\n t.compare(users[0].getArray('array').toArray(), Array.from(users[0].getArray('array')))\n // Test Map iterator\n const ymapkeys = Array.from(users[0].getMap('map').keys())\n t.assert(ymapkeys.length === Object.keys(userMapValues[0]).length)\n ymapkeys.forEach(key => t.assert(object.hasProperty(userMapValues[0], key)))\n /**\n * @type {Object}\n */\n const mapRes = {}\n for (const [k, v] of users[0].getMap('map')) {\n mapRes[k] = v instanceof Y.AbstractType ? v.toJSON() : v\n }\n t.compare(userMapValues[0], mapRes)\n // Compare all users\n for (let i = 0; i < users.length - 1; i++) {\n t.compare(userArrayValues[i].length, users[i].getArray('array').length)\n t.compare(userArrayValues[i], userArrayValues[i + 1])\n t.compare(userMapValues[i], userMapValues[i + 1])\n t.compare(userXmlValues[i], userXmlValues[i + 1])\n t.compare(userTextValues[i].map(/** @param {any} a */ a => typeof a.insert === 'string' ? a.insert : ' ').join('').length, users[i].getText('text').length)\n t.compare(userTextValues[i], userTextValues[i + 1])\n t.compare(Y.getStateVector(users[i].store), Y.getStateVector(users[i + 1].store))\n compareDS(Y.createDeleteSetFromStructStore(users[i].store), Y.createDeleteSetFromStructStore(users[i + 1].store))\n compareStructStores(users[i].store, users[i + 1].store)\n }\n users.map(u => u.destroy())\n}\n\n/**\n * @param {Y.Item?} a\n * @param {Y.Item?} b\n * @return {boolean}\n */\nexport const compareItemIDs = (a, b) => a === b || (a !== null && b != null && Y.compareIDs(a.id, b.id))\n\n/**\n * @param {Y.StructStore} ss1\n * @param {Y.StructStore} ss2\n */\nexport const compareStructStores = (ss1, ss2) => {\n t.assert(ss1.clients.size === ss2.clients.size)\n for (const [client, structs1] of ss1.clients) {\n const structs2 = /** @type {Array} */ (ss2.clients.get(client))\n t.assert(structs2 !== undefined && structs1.length === structs2.length)\n for (let i = 0; i < structs1.length; i++) {\n const s1 = structs1[i]\n const s2 = structs2[i]\n // checks for abstract struct\n if (\n s1.constructor !== s2.constructor ||\n !Y.compareIDs(s1.id, s2.id) ||\n s1.deleted !== s2.deleted ||\n // @ts-ignore\n s1.length !== s2.length\n ) {\n t.fail('Structs dont match')\n }\n if (s1 instanceof Y.Item) {\n if (\n !(s2 instanceof Y.Item) ||\n !((s1.left === null && s2.left === null) || (s1.left !== null && s2.left !== null && Y.compareIDs(s1.left.lastId, s2.left.lastId))) ||\n !compareItemIDs(s1.right, s2.right) ||\n !Y.compareIDs(s1.origin, s2.origin) ||\n !Y.compareIDs(s1.rightOrigin, s2.rightOrigin) ||\n s1.parentSub !== s2.parentSub\n ) {\n return t.fail('Items dont match')\n }\n // make sure that items are connected correctly\n t.assert(s1.left === null || s1.left.right === s1)\n t.assert(s1.right === null || s1.right.left === s1)\n t.assert(s2.left === null || s2.left.right === s2)\n t.assert(s2.right === null || s2.right.left === s2)\n }\n }\n }\n}\n\n/**\n * @param {Y.DeleteSet} ds1\n * @param {Y.DeleteSet} ds2\n */\nexport const compareDS = (ds1, ds2) => {\n t.assert(ds1.clients.size === ds2.clients.size)\n ds1.clients.forEach((deleteItems1, client) => {\n const deleteItems2 = /** @type {Array} */ (ds2.clients.get(client))\n t.assert(deleteItems2 !== undefined && deleteItems1.length === deleteItems2.length)\n for (let i = 0; i < deleteItems1.length; i++) {\n const di1 = deleteItems1[i]\n const di2 = deleteItems2[i]\n if (di1.clock !== di2.clock || di1.len !== di2.len) {\n t.fail('DeleteSets dont match')\n }\n }\n })\n}\n\n/**\n * @template T\n * @callback InitTestObjectCallback\n * @param {TestYInstance} y\n * @return {T}\n */\n\n/**\n * @template T\n * @param {t.TestCase} tc\n * @param {Array} mods\n * @param {number} iterations\n * @param {InitTestObjectCallback} [initTestObject]\n */\nexport const applyRandomTests = (tc, mods, iterations, initTestObject) => {\n const gen = tc.prng\n const result = init(tc, { users: 5 }, initTestObject)\n const { testConnector, users } = result\n for (let i = 0; i < iterations; i++) {\n if (prng.int32(gen, 0, 100) <= 2) {\n // 2% chance to disconnect/reconnect a random user\n if (prng.bool(gen)) {\n testConnector.disconnectRandom()\n } else {\n testConnector.reconnectRandom()\n }\n } else if (prng.int32(gen, 0, 100) <= 1) {\n // 1% chance to flush all\n testConnector.flushAllMessages()\n } else if (prng.int32(gen, 0, 100) <= 50) {\n // 50% chance to flush a random message\n testConnector.flushRandomMessage()\n }\n const user = prng.int32(gen, 0, users.length - 1)\n const test = prng.oneOf(gen, mods)\n test(users[user], gen, result.testObjects[user])\n }\n compare(users)\n return result\n}\n","\nimport { PluginKey } from 'prosemirror-state' // eslint-disable-line\n\n/**\n * The unique prosemirror plugin key for syncPlugin\n *\n * @public\n */\nexport const ySyncPluginKey = new PluginKey('y-sync')\n\n/**\n * The unique prosemirror plugin key for undoPlugin\n *\n * @public\n */\nexport const yUndoPluginKey = new PluginKey('y-undo')\n\n/**\n * The unique prosemirror plugin key for cursorPlugin\n *\n * @public\n */\nexport const yCursorPluginKey = new PluginKey('yjs-cursor')\n","/**\n * @module bindings/prosemirror\n */\n\nimport { createMutex } from 'lib0/mutex.js'\nimport { Node as PMNode, Slice as PMSlice, Fragment as PMFragment, Schema as PMSchema } from 'prosemirror-model'\nimport { Plugin, TextSelection } from 'prosemirror-state' // eslint-disable-line\nimport { min } from 'lib0/math.js'\nimport { keys } from 'lib0/object.js'\nimport { simpleDiff } from 'lib0/diff.js'\nimport { methodUnimplemented } from 'lib0/error.js'\nimport { ySyncPluginKey } from './keys.js'\nimport * as Y from 'yjs'\nimport { absolutePositionToRelativePosition, relativePositionToAbsolutePosition } from '../lib.js'\nimport { isBrowser } from 'lib0/environment.js'\nimport { doc } from 'lib0/dom.js'\n\n/**\n * @param {Y.Item} item\n * @param {Y.Snapshot} [snapshot]\n */\nexport const isVisible = (item, snapshot) => snapshot === undefined ? !item.deleted : (snapshot.sv.has(item.id.client) && /** @type {number} */ (snapshot.sv.get(item.id.client)) > item.id.clock && !Y.isDeleted(snapshot.ds, item.id))\n\n/**\n * Either a node if type is YXmlElement or an Array of text nodes if YXmlText\n * @typedef {Map>} ProsemirrorMapping\n */\n\n/**\n * @typedef {Object} ColorDef\n * @property {string} ColorDef.light\n * @property {string} ColorDef.dark\n */\n\n/**\n * @typedef {Object} YSyncOpts\n * @property {Array} [YSyncOpts.colors]\n * @property {Map} [YSyncOpts.colorMapping]\n * @property {Y.PermanentUserData|null} [YSyncOpts.permanentUserData]\n */\n\n/**\n * @type {Array}\n */\nconst defaultColors = [{ light: '#ecd44433', dark: '#ecd444' }]\n\n/**\n * @param {Map} colorMapping\n * @param {Array} colors\n * @param {string} user\n * @return {ColorDef}\n */\nconst getUserColor = (colorMapping, colors, user) => {\n if (!colorMapping.has(user)) {\n colorMapping.set(user, colors[colorMapping.size % colors.length]);\n }\n return /** @type {ColorDef} */ (colorMapping.get(user));\n}\n\n/**\n * This plugin listens to changes in prosemirror view and keeps yXmlState and view in sync.\n *\n * This plugin also keeps references to the type and the shared document so other plugins can access it.\n * @param {Y.XmlFragment} yXmlFragment\n * @param {YSyncOpts} opts\n * @return {any} Returns a prosemirror plugin that binds to this type\n */\nexport const ySyncPlugin = (yXmlFragment, { colors = defaultColors, colorMapping = new Map(), permanentUserData = null } = {}) => {\n let changedInitialContent = false\n const plugin = new Plugin({\n props: {\n editable: (state) => {\n const syncState = ySyncPluginKey.getState(state)\n return syncState.snapshot == null && syncState.prevSnapshot == null\n }\n },\n key: ySyncPluginKey,\n state: {\n init: (initargs, state) => {\n return {\n type: yXmlFragment,\n doc: yXmlFragment.doc,\n binding: null,\n snapshot: null,\n prevSnapshot: null,\n isChangeOrigin: false,\n colors,\n colorMapping,\n permanentUserData\n }\n },\n apply: (tr, pluginState) => {\n const change = tr.getMeta(ySyncPluginKey)\n if (change !== undefined) {\n pluginState = Object.assign({}, pluginState)\n for (const key in change) {\n pluginState[key] = change[key]\n }\n }\n // always set isChangeOrigin. If undefined, this is not change origin.\n pluginState.isChangeOrigin = change !== undefined && !!change.isChangeOrigin\n if (pluginState.binding !== null) {\n if (change !== undefined && (change.snapshot != null || change.prevSnapshot != null)) {\n // snapshot changed, rerender next\n setTimeout(() => {\n if (change.restore == null) {\n pluginState.binding._renderSnapshot(change.snapshot, change.prevSnapshot, pluginState)\n } else {\n pluginState.binding._renderSnapshot(change.snapshot, change.snapshot, pluginState)\n // reset to current prosemirror state\n delete pluginState.restore\n delete pluginState.snapshot\n delete pluginState.prevSnapshot\n pluginState.binding._prosemirrorChanged(pluginState.binding.prosemirrorView.state.doc)\n }\n }, 0)\n }\n }\n return pluginState\n }\n },\n view: view => {\n\n const binding = new ProsemirrorBinding(yXmlFragment, view);\n binding._forceRerender();\n view.dispatch(view.state.tr.setMeta(ySyncPluginKey, { binding }));\n\n return {\n update: () => {\n const pluginState = plugin.getState(view.state)\n if (pluginState.snapshot == null && pluginState.prevSnapshot == null) {\n if (changedInitialContent || view.state.doc.content.findDiffStart(view.state.doc.type.createAndFill().content) != null) {\n changedInitialContent = true\n binding._prosemirrorChanged(view.state.doc)\n }\n }\n },\n destroy: () => {\n binding.destroy()\n }\n }\n }\n })\n return plugin\n}\n\n/**\n * @param {any} tr\n * @param {any} relSel\n * @param {ProsemirrorBinding} binding\n */\nconst restoreRelativeSelection = (tr, relSel, binding) => {\n if (relSel !== null && relSel.anchor !== null && relSel.head !== null) {\n const anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping)\n const head = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.head, binding.mapping)\n if (anchor !== null && head !== null) {\n tr = tr.setSelection(TextSelection.create(tr.doc, anchor, head))\n }\n }\n}\n\nexport const getRelativeSelection = (pmbinding, state) => ({\n anchor: absolutePositionToRelativePosition(state.selection.anchor, pmbinding.type, pmbinding.mapping),\n head: absolutePositionToRelativePosition(state.selection.head, pmbinding.type, pmbinding.mapping)\n})\n\n/**\n * Binding for prosemirror.\n *\n * @protected\n */\nexport class ProsemirrorBinding {\n /**\n * @param {Y.XmlFragment} yXmlFragment The bind source\n * @param {any} prosemirrorView The target binding\n */\n constructor (yXmlFragment, prosemirrorView) {\n this.type = yXmlFragment\n this.prosemirrorView = prosemirrorView\n this.mux = createMutex()\n /**\n * @type {ProsemirrorMapping}\n */\n this.mapping = new Map()\n this._observeFunction = this._typeChanged.bind(this)\n /**\n * @type {Y.Doc}\n */\n // @ts-ignore\n this.doc = yXmlFragment.doc\n /**\n * current selection as relative positions in the Yjs model\n */\n this.beforeTransactionSelection = null\n this.beforeAllTransactions = () => {\n if (this.beforeTransactionSelection === null) {\n this.beforeTransactionSelection = getRelativeSelection(this, prosemirrorView.state)\n }\n }\n this.afterAllTransactions = () => {\n this.beforeTransactionSelection = null\n }\n\n this.doc.on('beforeAllTransactions', this.beforeAllTransactions)\n this.doc.on('afterAllTransactions', this.afterAllTransactions)\n yXmlFragment.observeDeep(this._observeFunction)\n\n this._domSelectionInView = null\n }\n\n _isLocalCursorInView () {\n if (!this.prosemirrorView.hasFocus()) return false\n if (isBrowser && this._domSelectionInView === null) {\n // Calculate the domSelectionInView and clear by next tick after all events are finished\n setTimeout(() => {\n this._domSelectionInView = null\n }, 0)\n this._domSelectionInView = this._isDomSelectionInView()\n }\n return this._domSelectionInView\n }\n\n _isDomSelectionInView () {\n const selection = this.prosemirrorView._root.getSelection()\n\n const range = this.prosemirrorView._root.createRange()\n range.setStart(selection.anchorNode, selection.anchorOffset)\n range.setEnd(selection.focusNode, selection.focusOffset)\n\n // This is a workaround for an edgecase where getBoundingClientRect will\n // return zero values if the selection is collapsed at the start of a newline\n // see reference here: https://stackoverflow.com/a/59780954\n const rects = range.getClientRects()\n if (rects.length === 0) {\n // probably buggy newline behavior, explicitly select the node contents\n if (range.startContainer && range.collapsed) {\n range.selectNodeContents(range.startContainer)\n }\n }\n\n const bounding = range.getBoundingClientRect()\n const documentElement = doc.documentElement\n\n return bounding.bottom >= 0 && bounding.right >= 0 &&\n bounding.left <= (window.innerWidth || documentElement.clientWidth || 0) &&\n bounding.top <= (window.innerHeight || documentElement.clientHeight || 0)\n }\n\n renderSnapshot (snapshot, prevSnapshot) {\n if (!prevSnapshot) {\n prevSnapshot = Y.createSnapshot(Y.createDeleteSet(), new Map())\n }\n this.prosemirrorView.dispatch(this.prosemirrorView.state.tr.setMeta(ySyncPluginKey, { snapshot, prevSnapshot }))\n }\n\n unrenderSnapshot () {\n this.mapping = new Map()\n this.mux(() => {\n const fragmentContent = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null)\n // @ts-ignore\n const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new PMSlice(new PMFragment(fragmentContent), 0, 0))\n tr.setMeta(ySyncPluginKey, { snapshot: null, prevSnapshot: null })\n this.prosemirrorView.dispatch(tr)\n })\n }\n\n _forceRerender () {\n this.mapping = new Map()\n this.mux(() => {\n let content = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null);\n if (content.length) {\n // @ts-ignore\n const tr = this.prosemirrorView.state.tr.replaceWith(0, this.prosemirrorView.state.doc.content.size, new PMFragment(content));\n this.prosemirrorView.dispatch(tr);\n }\n })\n }\n\n /**\n * @param {Y.Snapshot} snapshot\n * @param {Y.Snapshot} prevSnapshot\n * @param {Object} pluginState\n */\n _renderSnapshot (snapshot, prevSnapshot, pluginState) {\n if (!snapshot) {\n snapshot = Y.snapshot(this.doc)\n }\n // clear mapping because we are going to rerender\n this.mapping = new Map()\n this.mux(() => {\n this.doc.transact(transaction => {\n // before rendering, we are going to sanitize ops and split deleted ops\n // if they were deleted by seperate users.\n const pud = pluginState.permanentUserData\n if (pud) {\n pud.dss.forEach(ds => {\n Y.iterateDeletedStructs(transaction, ds, item => {})\n })\n }\n const computeYChange = (type, id) => {\n const user = type === 'added' ? pud.getUserByClientId(id.client) : pud.getUserByDeletedId(id)\n return {\n user,\n type,\n color: getUserColor(pluginState.colorMapping, pluginState.colors, user)\n }\n }\n // Create document fragment and render\n const fragmentContent = Y.typeListToArraySnapshot(this.type, new Y.Snapshot(prevSnapshot.ds, snapshot.sv)).map(t => {\n if (!t._item.deleted || isVisible(t._item, snapshot) || isVisible(t._item, prevSnapshot)) {\n return createNodeFromYElement(t, this.prosemirrorView.state.schema, new Map(), snapshot, prevSnapshot, computeYChange)\n } else {\n // No need to render elements that are not visible by either snapshot.\n // If a client adds and deletes content in the same snapshot the element is not visible by either snapshot.\n return null\n }\n }).filter(n => n !== null)\n // @ts-ignore\n const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new PMSlice(new PMFragment(fragmentContent), 0, 0))\n this.prosemirrorView.dispatch(tr)\n }, ySyncPluginKey)\n })\n }\n\n /**\n * @param {Array} events\n * @param {Y.Transaction} transaction\n */\n _typeChanged (events, transaction) {\n const syncState = ySyncPluginKey.getState(this.prosemirrorView.state)\n if (events.length === 0 || syncState.snapshot != null || syncState.prevSnapshot != null) {\n // drop out if snapshot is active\n this.renderSnapshot(syncState.snapshot, syncState.prevSnapshot)\n return\n }\n this.mux(() => {\n /**\n * @param {any} _\n * @param {Y.AbstractType} type\n */\n const delType = (_, type) => this.mapping.delete(type)\n Y.iterateDeletedStructs(transaction, transaction.deleteSet, struct => struct.constructor === Y.Item && this.mapping.delete(/** @type {Y.ContentType} */ (/** @type {Y.Item} */ (struct).content).type))\n transaction.changed.forEach(delType)\n transaction.changedParentTypes.forEach(delType)\n const fragmentContent = this.type.toArray().map(t => createNodeIfNotExists(/** @type {Y.XmlElement | Y.XmlHook} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null)\n // @ts-ignore\n let tr = this.prosemirrorView.state.tr.replaceWith(0, this.prosemirrorView.state.doc.content.size, new PMFragment(fragmentContent));\n restoreRelativeSelection(tr, this.beforeTransactionSelection, this)\n tr = tr.setMeta(ySyncPluginKey, { isChangeOrigin: true })\n if (this.beforeTransactionSelection !== null && this._isLocalCursorInView()) {\n tr.scrollIntoView()\n }\n this.prosemirrorView.dispatch(tr)\n })\n }\n\n _prosemirrorChanged (doc) {\n this.mux(() => {\n this.doc.transact(() => {\n updateYFragment(this.doc, this.type, doc, this.mapping)\n this.beforeTransactionSelection = getRelativeSelection(this, this.prosemirrorView.state)\n }, ySyncPluginKey)\n })\n }\n\n destroy () {\n this.type.unobserveDeep(this._observeFunction)\n this.doc.off('beforeAllTransactions', this.beforeAllTransactions)\n this.doc.off('afterAllTransactions', this.afterAllTransactions)\n }\n}\n\n/**\n * @private\n * @param {Y.XmlElement | Y.XmlHook} el\n * @param {PMSchema} schema\n * @param {ProsemirrorMapping} mapping\n * @param {Y.Snapshot} [snapshot]\n * @param {Y.Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', Y.ID):any} [computeYChange]\n * @return {PMNode | null}\n */\nconst createNodeIfNotExists = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => {\n const node = /** @type {PMNode} */ (mapping.get(el))\n if (node === undefined) {\n if (el instanceof Y.XmlElement) {\n return createNodeFromYElement(el, schema, mapping, snapshot, prevSnapshot, computeYChange)\n } else {\n throw methodUnimplemented() // we are currently not handling hooks\n }\n }\n return node\n}\n\n/**\n * @private\n * @param {Y.XmlElement} el\n * @param {any} schema\n * @param {ProsemirrorMapping} mapping\n * @param {Y.Snapshot} [snapshot]\n * @param {Y.Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', Y.ID):any} [computeYChange]\n * @return {PMNode | null} Returns node if node could be created. Otherwise it deletes the yjs type and returns null\n */\nconst createNodeFromYElement = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => {\n const children = []\n const createChildren = type => {\n if (type.constructor === Y.XmlElement) {\n const n = createNodeIfNotExists(type, schema, mapping, snapshot, prevSnapshot, computeYChange)\n if (n !== null) {\n children.push(n)\n }\n } else {\n const ns = createTextNodesFromYText(type, schema, mapping, snapshot, prevSnapshot, computeYChange)\n if (ns !== null) {\n ns.forEach(textchild => {\n if (textchild !== null) {\n children.push(textchild)\n }\n })\n }\n }\n }\n if (snapshot === undefined || prevSnapshot === undefined) {\n el.toArray().forEach(createChildren)\n } else {\n Y.typeListToArraySnapshot(el, new Y.Snapshot(prevSnapshot.ds, snapshot.sv)).forEach(createChildren)\n }\n try {\n const attrs = el.getAttributes(snapshot)\n if (snapshot !== undefined) {\n if (!isVisible(/** @type {Y.Item} */ (el._item), snapshot)) {\n attrs.ychange = computeYChange ? computeYChange('removed', /** @type {Y.Item} */ (el._item).id) : { type: 'removed' }\n } else if (!isVisible(/** @type {Y.Item} */ (el._item), prevSnapshot)) {\n attrs.ychange = computeYChange ? computeYChange('added', /** @type {Y.Item} */ (el._item).id) : { type: 'added' }\n }\n }\n const node = schema.node(el.nodeName, attrs, children)\n mapping.set(el, node)\n return node\n } catch (e) {\n // an error occured while creating the node. This is probably a result of a concurrent action.\n /** @type {Y.Doc} */ (el.doc).transact(transaction => {\n /** @type {Y.Item} */ (el._item).delete(transaction)\n }, ySyncPluginKey)\n mapping.delete(el)\n return null\n }\n}\n\n/**\n * @private\n * @param {Y.XmlText} text\n * @param {any} schema\n * @param {ProsemirrorMapping} mapping\n * @param {Y.Snapshot} [snapshot]\n * @param {Y.Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', Y.ID):any} [computeYChange]\n * @return {Array|null}\n */\nconst createTextNodesFromYText = (text, schema, mapping, snapshot, prevSnapshot, computeYChange) => {\n const nodes = []\n const deltas = text.toDelta(snapshot, prevSnapshot, computeYChange)\n try {\n for (let i = 0; i < deltas.length; i++) {\n const delta = deltas[i]\n const marks = []\n for (const markName in delta.attributes) {\n marks.push(schema.mark(markName, delta.attributes[markName]))\n }\n nodes.push(schema.text(delta.insert, marks))\n }\n } catch (e) {\n // an error occured while creating the node. This is probably a result of a concurrent action.\n /** @type {Y.Doc} */ (text.doc).transact(transaction => {\n /** @type {Y.Item} */ (text._item).delete(transaction)\n }, ySyncPluginKey)\n return null\n }\n // @ts-ignore\n return nodes\n}\n\n/**\n * @private\n * @param {Array} nodes prosemirror node\n * @param {ProsemirrorMapping} mapping\n * @return {Y.XmlText}\n */\nconst createTypeFromTextNodes = (nodes, mapping) => {\n const type = new Y.XmlText()\n const delta = nodes.map(node => ({\n // @ts-ignore\n insert: node.text,\n attributes: marksToAttributes(node.marks)\n }))\n type.applyDelta(delta)\n mapping.set(type, nodes)\n return type\n}\n\n/**\n * @private\n * @param {any} node prosemirror node\n * @param {ProsemirrorMapping} mapping\n * @return {Y.XmlElement}\n */\nconst createTypeFromElementNode = (node, mapping) => {\n const type = new Y.XmlElement(node.type.name)\n for (const key in node.attrs) {\n const val = node.attrs[key]\n if (val !== null && key !== 'ychange') {\n type.setAttribute(key, val)\n }\n }\n type.insert(0, normalizePNodeContent(node).map(n => createTypeFromTextOrElementNode(n, mapping)))\n mapping.set(type, node)\n return type\n}\n\n/**\n * @private\n * @param {PMNode|Array} node prosemirror text node\n * @param {ProsemirrorMapping} mapping\n * @return {Y.XmlElement|Y.XmlText}\n */\nconst createTypeFromTextOrElementNode = (node, mapping) => node instanceof Array ? createTypeFromTextNodes(node, mapping) : createTypeFromElementNode(node, mapping)\n\nconst equalAttrs = (pattrs, yattrs) => {\n const keys = Object.keys(pattrs).filter(key => pattrs[key] !== null)\n let eq = keys.length === Object.keys(yattrs).filter(key => yattrs[key] !== null).length\n for (let i = 0; i < keys.length && eq; i++) {\n const key = keys[i]\n const l = pattrs[key]\n const r = yattrs[key]\n eq = key === 'ychange' || l === r || (typeof l === 'object' && typeof r === 'object' && equalAttrs(l, r))\n }\n return eq\n}\n\n/**\n * @typedef {Array|PMNode>} NormalizedPNodeContent\n */\n\n/**\n * @param {any} pnode\n * @return {NormalizedPNodeContent}\n */\nconst normalizePNodeContent = pnode => {\n const c = pnode.content.content\n const res = []\n for (let i = 0; i < c.length; i++) {\n const n = c[i]\n if (n.isText) {\n const textNodes = []\n for (let tnode = c[i]; i < c.length && tnode.isText; tnode = c[++i]) {\n textNodes.push(tnode)\n }\n i--\n res.push(textNodes)\n } else {\n res.push(n)\n }\n }\n return res\n}\n\n/**\n * @param {Y.XmlText} ytext\n * @param {Array} ptexts\n */\nconst equalYTextPText = (ytext, ptexts) => {\n const delta = ytext.toDelta()\n return delta.length === ptexts.length && delta.every((d, i) => d.insert === /** @type {any} */ (ptexts[i]).text && keys(d.attributes || {}).length === ptexts[i].marks.length && ptexts[i].marks.every(mark => equalAttrs(d.attributes[mark.type.name] || {}, mark.attrs)))\n}\n\n/**\n * @param {Y.XmlElement|Y.XmlText|Y.XmlHook} ytype\n * @param {any|Array} pnode\n */\nconst equalYTypePNode = (ytype, pnode) => {\n if (ytype instanceof Y.XmlElement && !(pnode instanceof Array) && matchNodeName(ytype, pnode)) {\n const normalizedContent = normalizePNodeContent(pnode)\n return ytype._length === normalizedContent.length && equalAttrs(ytype.getAttributes(), pnode.attrs) && ytype.toArray().every((ychild, i) => equalYTypePNode(ychild, normalizedContent[i]))\n }\n return ytype instanceof Y.XmlText && pnode instanceof Array && equalYTextPText(ytype, pnode)\n}\n\n/**\n * @param {PMNode | Array | undefined} mapped\n * @param {PMNode | Array} pcontent\n */\nconst mappedIdentity = (mapped, pcontent) => mapped === pcontent || (mapped instanceof Array && pcontent instanceof Array && mapped.length === pcontent.length && mapped.every((a, i) => pcontent[i] === a))\n\n/**\n * @param {Y.XmlElement} ytype\n * @param {PMNode} pnode\n * @param {ProsemirrorMapping} mapping\n * @return {{ foundMappedChild: boolean, equalityFactor: number }}\n */\nconst computeChildEqualityFactor = (ytype, pnode, mapping) => {\n const yChildren = ytype.toArray()\n const pChildren = normalizePNodeContent(pnode)\n const pChildCnt = pChildren.length\n const yChildCnt = yChildren.length\n const minCnt = min(yChildCnt, pChildCnt)\n let left = 0\n let right = 0\n let foundMappedChild = false\n for (; left < minCnt; left++) {\n const leftY = yChildren[left]\n const leftP = pChildren[left]\n if (mappedIdentity(mapping.get(leftY), leftP)) {\n foundMappedChild = true// definite (good) match!\n } else if (!equalYTypePNode(leftY, leftP)) {\n break\n }\n }\n for (; left + right < minCnt; right++) {\n const rightY = yChildren[yChildCnt - right - 1]\n const rightP = pChildren[pChildCnt - right - 1]\n if (mappedIdentity(mapping.get(rightY), rightP)) {\n foundMappedChild = true\n } else if (!equalYTypePNode(rightY, rightP)) {\n break\n }\n }\n return {\n equalityFactor: left + right,\n foundMappedChild\n }\n}\n\nconst ytextTrans = ytext => {\n let str = ''\n /**\n * @type {Y.Item|null}\n */\n let n = ytext._start\n const nAttrs = {}\n while (n !== null) {\n if (!n.deleted) {\n if (n.countable && n.content instanceof Y.ContentString) {\n str += n.content.str\n } else if (n.content instanceof Y.ContentFormat) {\n nAttrs[n.content.key] = null\n }\n }\n n = n.right\n }\n return {\n str,\n nAttrs\n }\n}\n\n/**\n * @todo test this more\n *\n * @param {Y.Text} ytext\n * @param {Array} ptexts\n * @param {ProsemirrorMapping} mapping\n */\nconst updateYText = (ytext, ptexts, mapping) => {\n mapping.set(ytext, ptexts)\n const { nAttrs, str } = ytextTrans(ytext)\n const content = ptexts.map(p => ({ insert: /** @type {any} */ (p).text, attributes: Object.assign({}, nAttrs, marksToAttributes(p.marks)) }))\n const { insert, remove, index } = simpleDiff(str, content.map(c => c.insert).join(''))\n ytext.delete(index, remove)\n ytext.insert(index, insert)\n ytext.applyDelta(content.map(c => ({ retain: c.insert.length, attributes: c.attributes })))\n}\n\nconst marksToAttributes = marks => {\n const pattrs = {}\n marks.forEach(mark => {\n if (mark.type.name !== 'ychange') {\n pattrs[mark.type.name] = mark.attrs\n }\n })\n return pattrs\n}\n\n/**\n * @private\n * @param {Y.Doc} y\n * @param {Y.XmlFragment} yDomFragment\n * @param {any} pNode\n * @param {ProsemirrorMapping} mapping\n */\nexport const updateYFragment = (y, yDomFragment, pNode, mapping) => {\n if (yDomFragment instanceof Y.XmlElement && yDomFragment.nodeName !== pNode.type.name) {\n throw new Error('node name mismatch!')\n }\n mapping.set(yDomFragment, pNode)\n // update attributes\n if (yDomFragment instanceof Y.XmlElement) {\n const yDomAttrs = yDomFragment.getAttributes()\n const pAttrs = pNode.attrs\n for (const key in pAttrs) {\n if (pAttrs[key] !== null) {\n if (yDomAttrs[key] !== pAttrs[key] && key !== 'ychange') {\n yDomFragment.setAttribute(key, pAttrs[key])\n }\n } else {\n yDomFragment.removeAttribute(key)\n }\n }\n // remove all keys that are no longer in pAttrs\n for (const key in yDomAttrs) {\n if (pAttrs[key] === undefined) {\n yDomFragment.removeAttribute(key)\n }\n }\n }\n // update children\n const pChildren = normalizePNodeContent(pNode)\n const pChildCnt = pChildren.length\n const yChildren = yDomFragment.toArray()\n const yChildCnt = yChildren.length\n const minCnt = min(pChildCnt, yChildCnt)\n let left = 0\n let right = 0\n // find number of matching elements from left\n for (;left < minCnt; left++) {\n const leftY = yChildren[left]\n const leftP = pChildren[left]\n if (!mappedIdentity(mapping.get(leftY), leftP)) {\n if (equalYTypePNode(leftY, leftP)) {\n // update mapping\n mapping.set(leftY, leftP)\n } else {\n break\n }\n }\n }\n // find number of matching elements from right\n for (;right + left + 1 < minCnt; right++) {\n const rightY = yChildren[yChildCnt - right - 1]\n const rightP = pChildren[pChildCnt - right - 1]\n if (!mappedIdentity(mapping.get(rightY), rightP)) {\n if (equalYTypePNode(rightY, rightP)) {\n // update mapping\n mapping.set(rightY, rightP)\n } else {\n break\n }\n }\n }\n y.transact(() => {\n // try to compare and update\n while (yChildCnt - left - right > 0 && pChildCnt - left - right > 0) {\n const leftY = yChildren[left]\n const leftP = pChildren[left]\n const rightY = yChildren[yChildCnt - right - 1]\n const rightP = pChildren[pChildCnt - right - 1]\n if (leftY instanceof Y.XmlText && leftP instanceof Array) {\n if (!equalYTextPText(leftY, leftP)) {\n updateYText(leftY, leftP, mapping)\n }\n left += 1\n } else {\n let updateLeft = leftY instanceof Y.XmlElement && matchNodeName(leftY, leftP)\n let updateRight = rightY instanceof Y.XmlElement && matchNodeName(rightY, rightP)\n if (updateLeft && updateRight) {\n // decide which which element to update\n const equalityLeft = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (leftY), /** @type {PMNode} */ (leftP), mapping)\n const equalityRight = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (rightY), /** @type {PMNode} */ (rightP), mapping)\n if (equalityLeft.foundMappedChild && !equalityRight.foundMappedChild) {\n updateRight = false\n } else if (!equalityLeft.foundMappedChild && equalityRight.foundMappedChild) {\n updateLeft = false\n } else if (equalityLeft.equalityFactor < equalityRight.equalityFactor) {\n updateLeft = false\n } else {\n updateRight = false\n }\n }\n if (updateLeft) {\n updateYFragment(y, /** @type {Y.XmlFragment} */ (leftY), /** @type {PMNode} */ (leftP), mapping)\n left += 1\n } else if (updateRight) {\n updateYFragment(y, /** @type {Y.XmlFragment} */ (rightY), /** @type {PMNode} */ (rightP), mapping)\n right += 1\n } else {\n yDomFragment.delete(left, 1)\n yDomFragment.insert(left, [createTypeFromTextOrElementNode(leftP, mapping)])\n left += 1\n }\n }\n }\n const yDelLen = yChildCnt - left - right\n if (yDelLen > 0) {\n yDomFragment.delete(left, yDelLen)\n }\n if (left + right < pChildCnt) {\n const ins = []\n for (let i = left; i < pChildCnt - right; i++) {\n ins.push(createTypeFromTextOrElementNode(pChildren[i], mapping))\n }\n yDomFragment.insert(left, ins)\n }\n }, ySyncPluginKey)\n}\n\n/**\n * @function\n * @param {Y.XmlElement} yElement\n * @param {any} pNode Prosemirror Node\n */\nconst matchNodeName = (yElement, pNode) => !(pNode instanceof Array) && yElement.nodeName === pNode.type.name\n","import { updateYFragment } from './plugins/sync-plugin.js' // eslint-disable-line\nimport * as Y from 'yjs'\nimport { EditorView } from 'prosemirror-view' // eslint-disable-line\nimport { Node, Schema } from 'prosemirror-model' // eslint-disable-line\nimport * as error from 'lib0/error.js'\nimport * as map from 'lib0/map.js'\nimport * as eventloop from 'lib0/eventloop.js'\n\n/**\n * Either a node if type is YXmlElement or an Array of text nodes if YXmlText\n * @typedef {Map>} ProsemirrorMapping\n */\n\n/**\n * Is null if no timeout is in progress.\n * Is defined if a timeout is in progress.\n * Maps from view\n * @type {Map>|null}\n */\nlet viewsToUpdate = null\n\nconst updateMetas = () => {\n const ups = /** @type {Map>} */ (viewsToUpdate)\n viewsToUpdate = null\n ups.forEach((metas, view) => {\n const tr = view.state.tr\n metas.forEach((val, key) => {\n tr.setMeta(key, val)\n })\n view.dispatch(tr)\n })\n}\n\nexport const setMeta = (view, key, value) => {\n if (!viewsToUpdate) {\n viewsToUpdate = new Map()\n eventloop.timeout(0, updateMetas)\n }\n map.setIfUndefined(viewsToUpdate, view, map.create).set(key, value)\n}\n\n/**\n * Transforms a Prosemirror based absolute position to a Yjs Cursor (relative position in the Yjs model).\n *\n * @param {number} pos\n * @param {Y.XmlFragment} type\n * @param {ProsemirrorMapping} mapping\n * @return {any} relative position\n */\nexport const absolutePositionToRelativePosition = (pos, type, mapping) => {\n if (pos === 0) {\n return Y.createRelativePositionFromTypeIndex(type, 0)\n }\n let n = type._first === null ? null : /** @type {Y.ContentType} */ (type._first.content).type\n while (n !== null && type !== n) {\n if (n.constructor === Y.XmlText) {\n if (n._length >= pos) {\n return Y.createRelativePositionFromTypeIndex(n, pos)\n } else {\n pos -= n._length\n }\n if (n._item !== null && n._item.next !== null) {\n n = /** @type {Y.ContentType} */ (n._item.next.content).type\n } else {\n do {\n n = n._item === null ? null : n._item.parent\n pos--\n } while (n !== type && n !== null && n._item !== null && n._item.next === null)\n if (n !== null && n !== type) {\n // @ts-gnore we know that n.next !== null because of above loop conditition\n n = n._item === null ? null : /** @type {Y.ContentType} */ (/** @type Y.Item */ (n._item.next).content).type\n }\n }\n } else {\n const pNodeSize = /** @type {any} */ (mapping.get(n) || { nodeSize: 0 }).nodeSize\n if (n._first !== null && pos < pNodeSize) {\n n = /** @type {Y.ContentType} */ (n._first.content).type\n pos--\n } else {\n if (pos === 1 && n._length === 0 && pNodeSize > 1) {\n // edge case, should end in this paragraph\n return new Y.RelativePosition(n._item === null ? null : n._item.id, n._item === null ? Y.findRootTypeKey(n) : null, null)\n }\n pos -= pNodeSize\n if (n._item !== null && n._item.next !== null) {\n n = /** @type {Y.ContentType} */ (n._item.next.content).type\n } else {\n if (pos === 0) {\n // set to end of n.parent\n n = n._item === null ? n : n._item.parent\n return new Y.RelativePosition(n._item === null ? null : n._item.id, n._item === null ? Y.findRootTypeKey(n) : null, null)\n }\n do {\n n = /** @type {Y.Item} */ (n._item).parent\n pos--\n } while (n !== type && /** @type {Y.Item} */ (n._item).next === null)\n // if n is null at this point, we have an unexpected case\n if (n !== type) {\n // We know that n._item.next is defined because of above loop condition\n n = /** @type {Y.ContentType} */ (/** @type {Y.Item} */ (/** @type {Y.Item} */ (n._item).next).content).type\n }\n }\n }\n }\n if (n === null) {\n throw error.unexpectedCase()\n }\n if (pos === 0 && n.constructor !== Y.XmlText && n !== type) { // TODO: set to <= 0\n return createRelativePosition(n._item.parent, n._item)\n }\n }\n return Y.createRelativePositionFromTypeIndex(type, type._length)\n}\n\nconst createRelativePosition = (type, item) => {\n let typeid = null\n let tname = null\n if (type._item === null) {\n tname = Y.findRootTypeKey(type)\n } else {\n typeid = Y.createID(type._item.id.client, type._item.id.clock)\n }\n return new Y.RelativePosition(typeid, tname, item.id)\n}\n\n/**\n * @param {Y.Doc} y\n * @param {Y.XmlFragment} documentType Top level type that is bound to pView\n * @param {any} relPos Encoded Yjs based relative position\n * @param {ProsemirrorMapping} mapping\n * @return {null|number}\n */\nexport const relativePositionToAbsolutePosition = (y, documentType, relPos, mapping) => {\n const decodedPos = Y.createAbsolutePositionFromRelativePosition(relPos, y)\n if (decodedPos === null || (decodedPos.type !== documentType && !Y.isParentOf(documentType, decodedPos.type._item))) {\n return null\n }\n let type = decodedPos.type\n let pos = 0\n if (type.constructor === Y.XmlText) {\n pos = decodedPos.index\n } else if (type._item === null || !type._item.deleted) {\n let n = type._first\n let i = 0\n while (i < type._length && i < decodedPos.index && n !== null) {\n if (!n.deleted) {\n const t = /** @type {Y.ContentType} */ (n.content).type\n i++\n if (t.constructor === Y.XmlText) {\n pos += t._length\n } else {\n pos += /** @type {any} */ (mapping.get(t)).nodeSize\n }\n }\n n = /** @type {Y.Item} */ (n.right)\n }\n pos += 1 // increase because we go out of n\n }\n while (type !== documentType && type._item !== null) {\n // @ts-ignore\n const parent = type._item.parent\n // @ts-ignore\n if (parent._item === null || !parent._item.deleted) {\n pos += 1 // the start tag\n let n = parent._first\n // now iterate until we found type\n while (n !== null) {\n const contentType = /** @type {Y.ContentType} */ (n.content).type\n if (contentType === type) {\n break\n }\n if (!n.deleted) {\n if (contentType.constructor === Y.XmlText) {\n pos += contentType._length\n } else {\n pos += /** @type {any} */ (mapping.get(contentType)).nodeSize\n }\n }\n n = n.right\n }\n }\n type = parent\n }\n return pos - 1 // we don't count the most outer tag, because it is a fragment\n}\n\n/**\n * Utility method to convert a Prosemirror Doc Node into a Y.Doc.\n *\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param {Node} doc\n * @param {string} xmlFragment\n * @return {Y.Doc}\n */\nexport function prosemirrorToYDoc (doc, xmlFragment = 'prosemirror') {\n const ydoc = new Y.Doc()\n const type = ydoc.get(xmlFragment, Y.XmlFragment)\n if (!type.doc) {\n return ydoc\n }\n\n updateYFragment(type.doc, type, doc, new Map())\n return type.doc\n}\n\n/**\n * Utility method to convert Prosemirror compatible JSON into a Y.Doc.\n *\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param {Schema} schema\n * @param {any} state\n * @param {string} xmlFragment\n * @return {Y.Doc}\n */\nexport function prosemirrorJSONToYDoc (schema, state, xmlFragment = 'prosemirror') {\n const doc = Node.fromJSON(schema, state)\n return prosemirrorToYDoc(doc, xmlFragment)\n}\n\n/**\n * Utility method to convert a Y.Doc to a Prosemirror Doc node.\n *\n * @param {Schema} schema\n * @param {Y.Doc} ydoc\n * @return {Node}\n */\nexport function yDocToProsemirror (schema, ydoc) {\n const state = yDocToProsemirrorJSON(ydoc)\n return Node.fromJSON(schema, state)\n}\n\n/**\n * Utility method to convert a Y.Doc to Prosemirror compatible JSON.\n *\n * @param {Y.Doc} ydoc\n * @param {string} xmlFragment\n * @return {Record}\n */\nexport function yDocToProsemirrorJSON (\n ydoc,\n xmlFragment = 'prosemirror'\n) {\n const items = ydoc.getXmlFragment(xmlFragment).toArray()\n\n function serialize (item) {\n /**\n * @type {Object} NodeObject\n * @property {string} NodeObject.type\n * @property {Record=} NodeObject.attrs\n * @property {Array=} NodeObject.content\n */\n let response\n\n // TODO: Must be a better way to detect text nodes than this\n if (!item.nodeName) {\n const delta = item.toDelta()\n response = delta.map((d) => {\n const text = {\n type: 'text',\n text: d.insert\n }\n\n if (d.attributes) {\n text.marks = Object.keys(d.attributes).map((type) => {\n const attrs = d.attributes[type]\n const mark = {\n type\n }\n\n if (Object.keys(attrs)) {\n mark.attrs = attrs\n }\n\n return mark\n })\n }\n return text\n })\n } else {\n response = {\n type: item.nodeName\n }\n\n const attrs = item.getAttributes()\n if (Object.keys(attrs).length) {\n response.attrs = attrs\n }\n\n const children = item.toArray()\n if (children.length) {\n response.content = children.map(serialize).flat()\n }\n }\n\n return response\n }\n\n return {\n type: 'doc',\n content: items.map(serialize)\n }\n}\n","import { Schema } from 'prosemirror-model'\n\nconst brDOM = ['br']\n\nconst calcYchangeDomAttrs = (attrs, domAttrs = {}) => {\n domAttrs = Object.assign({}, domAttrs)\n if (attrs.ychange !== null) {\n domAttrs.ychange_user = attrs.ychange.user\n domAttrs.ychange_state = attrs.ychange.state\n }\n return domAttrs\n}\n\n// :: Object\n// [Specs](#model.NodeSpec) for the nodes defined in this schema.\nexport const nodes = {\n // :: NodeSpec The top level document node.\n doc: {\n content: 'custom paragraph'\n },\n\n custom: {\n atom: true,\n attrs: { checked: { default: false } },\n parseDOM: [{ tag: 'div' }],\n toDOM () {\n return ['div']\n }\n },\n\n // :: NodeSpec A plain paragraph textblock. Represented in the DOM\n // as a `

` element.\n paragraph: {\n attrs: { ychange: { default: null } },\n content: 'inline*',\n group: 'block',\n parseDOM: [{ tag: 'p' }],\n toDOM (node) {\n return ['p', calcYchangeDomAttrs(node.attrs), 0]\n }\n },\n\n // :: NodeSpec A blockquote (`

`) wrapping one or more blocks.\n blockquote: {\n attrs: { ychange: { default: null } },\n content: 'block+',\n group: 'block',\n defining: true,\n parseDOM: [{ tag: 'blockquote' }],\n toDOM (node) {\n return ['blockquote', calcYchangeDomAttrs(node.attrs), 0]\n }\n },\n\n // :: NodeSpec A horizontal rule (`
`).\n horizontal_rule: {\n attrs: { ychange: { default: null } },\n group: 'block',\n parseDOM: [{ tag: 'hr' }],\n toDOM (node) {\n return ['hr', calcYchangeDomAttrs(node.attrs)]\n }\n },\n\n // :: NodeSpec A heading textblock, with a `level` attribute that\n // should hold the number 1 to 6. Parsed and serialized as `

` to\n // `

` elements.\n heading: {\n attrs: {\n level: { default: 1 },\n ychange: { default: null }\n },\n content: 'inline*',\n group: 'block',\n defining: true,\n parseDOM: [\n { tag: 'h1', attrs: { level: 1 } },\n { tag: 'h2', attrs: { level: 2 } },\n { tag: 'h3', attrs: { level: 3 } },\n { tag: 'h4', attrs: { level: 4 } },\n { tag: 'h5', attrs: { level: 5 } },\n { tag: 'h6', attrs: { level: 6 } }\n ],\n toDOM (node) {\n return ['h' + node.attrs.level, calcYchangeDomAttrs(node.attrs), 0]\n }\n },\n\n // :: NodeSpec A code listing. Disallows marks or non-text inline\n // nodes by default. Represented as a `
` element with a\n  // `` element inside of it.\n  code_block: {\n    attrs: { ychange: { default: null } },\n    content: 'text*',\n    marks: '',\n    group: 'block',\n    code: true,\n    defining: true,\n    parseDOM: [{ tag: 'pre', preserveWhitespace: 'full' }],\n    toDOM (node) {\n      return ['pre', calcYchangeDomAttrs(node.attrs), ['code', 0]]\n    }\n  },\n\n  // :: NodeSpec The text node.\n  text: {\n    group: 'inline'\n  },\n\n  // :: NodeSpec An inline image (``) node. Supports `src`,\n  // `alt`, and `href` attributes. The latter two default to the empty\n  // string.\n  image: {\n    inline: true,\n    attrs: {\n      ychange: { default: null },\n      src: {},\n      alt: { default: null },\n      title: { default: null }\n    },\n    group: 'inline',\n    draggable: true,\n    parseDOM: [\n      {\n        tag: 'img[src]',\n        getAttrs (dom) {\n          return {\n            src: dom.getAttribute('src'),\n            title: dom.getAttribute('title'),\n            alt: dom.getAttribute('alt')\n          }\n        }\n      }\n    ],\n    toDOM (node) {\n      const domAttrs = {\n        src: node.attrs.src,\n        title: node.attrs.title,\n        alt: node.attrs.alt\n      }\n      return ['img', calcYchangeDomAttrs(node.attrs, domAttrs)]\n    }\n  },\n\n  // :: NodeSpec A hard line break, represented in the DOM as `
`.\n hard_break: {\n inline: true,\n group: 'inline',\n selectable: false,\n parseDOM: [{ tag: 'br' }],\n toDOM () {\n return brDOM\n }\n }\n}\n\nconst emDOM = ['em', 0]\nconst strongDOM = ['strong', 0]\nconst codeDOM = ['code', 0]\n\n// :: Object [Specs](#model.MarkSpec) for the marks in the schema.\nexport const marks = {\n // :: MarkSpec A link. Has `href` and `title` attributes. `title`\n // defaults to the empty string. Rendered and parsed as an `
`\n // element.\n link: {\n attrs: {\n href: {},\n title: { default: null }\n },\n inclusive: false,\n parseDOM: [\n {\n tag: 'a[href]',\n getAttrs (dom) {\n return {\n href: dom.getAttribute('href'),\n title: dom.getAttribute('title')\n }\n }\n }\n ],\n toDOM (node) {\n return ['a', node.attrs, 0]\n }\n },\n\n // :: MarkSpec An emphasis mark. Rendered as an `` element.\n // Has parse rules that also match `` and `font-style: italic`.\n em: {\n parseDOM: [{ tag: 'i' }, { tag: 'em' }, { style: 'font-style=italic' }],\n toDOM () {\n return emDOM\n }\n },\n\n // :: MarkSpec A strong mark. Rendered as ``, parse rules\n // also match `` and `font-weight: bold`.\n strong: {\n parseDOM: [\n { tag: 'strong' },\n // This works around a Google Docs misbehavior where\n // pasted content will be inexplicably wrapped in ``\n // tags with a font-weight normal.\n {\n tag: 'b',\n getAttrs: node => node.style.fontWeight !== 'normal' && null\n },\n {\n style: 'font-weight',\n getAttrs: value => /^(bold(er)?|[5-9]\\d{2,})$/.test(value) && null\n }\n ],\n toDOM () {\n return strongDOM\n }\n },\n\n // :: MarkSpec Code font mark. Represented as a `` element.\n code: {\n parseDOM: [{ tag: 'code' }],\n toDOM () {\n return codeDOM\n }\n },\n ychange: {\n attrs: {\n user: { default: null },\n state: { default: null }\n },\n inclusive: false,\n parseDOM: [{ tag: 'ychange' }],\n toDOM (node) {\n return [\n 'ychange',\n { ychange_user: node.attrs.user, ychange_state: node.attrs.state },\n 0\n ]\n }\n }\n}\n\n// :: Schema\n// This schema rougly corresponds to the document schema used by\n// [CommonMark](http://commonmark.org/), minus the list elements,\n// which are defined in the [`prosemirror-schema-list`](#schema-list)\n// module.\n//\n// To reuse elements from this schema, extend or read from its\n// `spec.nodes` and `spec.marks` [properties](#model.Schema.spec).\nexport const schema = new Schema({ nodes, marks })\n","\nimport * as t from 'lib0/testing.js'\nimport * as prng from 'lib0/prng.js'\nimport * as math from 'lib0/math.js'\nimport * as Y from 'yjs'\nimport { applyRandomTests } from 'yjs/tests/testHelper.js'\n\nimport { ySyncPlugin, prosemirrorJSONToYDoc, yDocToProsemirrorJSON } from '../src/y-prosemirror.js'\nimport { EditorState, TextSelection } from 'prosemirror-state'\nimport { EditorView } from 'prosemirror-view'\nimport * as basicSchema from 'prosemirror-schema-basic'\nimport { findWrapping } from 'prosemirror-transform'\nimport { schema as complexSchema } from './complexSchema.js'\n\nconst schema = /** @type {any} */ (basicSchema.schema)\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testDocTransformation = tc => {\n const view = createNewProsemirrorView(new Y.Doc())\n view.dispatch(view.state.tr.insert(0, /** @type {any} */ (schema.node('paragraph', undefined, schema.text('hello world')))))\n const stateJSON = view.state.doc.toJSON()\n // test if transforming back and forth from Yjs doc works\n const backandforth = yDocToProsemirrorJSON(prosemirrorJSONToYDoc(/** @type {any} */ (schema), stateJSON))\n t.compare(stateJSON, backandforth)\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testEmptyNotSync = tc => {\n const ydoc = new Y.Doc()\n const type = ydoc.getXmlFragment('prosemirror')\n const view = createNewComplexProsemirrorView(ydoc)\n t.assert(type.toString() === '', 'should only sync after first change')\n\n view.dispatch(\n view.state.tr.setNodeMarkup(0, undefined, {\n checked: true\n })\n )\n t.compareStrings(type.toString(), '')\n}\n\nconst createNewComplexProsemirrorView = y => {\n const view = new EditorView(null, {\n // @ts-ignore\n state: EditorState.create({\n schema: complexSchema,\n plugins: [ySyncPlugin(y.get('prosemirror', Y.XmlFragment))]\n })\n })\n return view\n}\n\nconst createNewProsemirrorView = y => {\n const view = new EditorView(null, {\n // @ts-ignore\n state: EditorState.create({\n schema,\n plugins: [ySyncPlugin(y.get('prosemirror', Y.XmlFragment))]\n })\n })\n return view\n}\n\nlet charCounter = 0\n\nconst marksChoices = [\n [schema.mark('strong')],\n [schema.mark('em')],\n [schema.mark('em'), schema.mark('strong')],\n [],\n []\n]\n\nconst pmChanges = [\n /**\n * @param {Y.Doc} y\n * @param {prng.PRNG} gen\n * @param {EditorView} p\n */\n (y, gen, p) => { // insert text\n const insertPos = prng.int32(gen, 0, p.state.doc.content.size)\n const marks = prng.oneOf(gen, marksChoices)\n const tr = p.state.tr\n const text = charCounter++ + prng.word(gen)\n p.dispatch(tr.insert(insertPos, schema.text(text, marks)))\n },\n /**\n * @param {Y.Doc} y\n * @param {prng.PRNG} gen\n * @param {EditorView} p\n */\n (y, gen, p) => { // delete text\n const insertPos = prng.int32(gen, 0, p.state.doc.content.size)\n const overwrite = math.min(prng.int32(gen, 0, p.state.doc.content.size - insertPos), 2)\n p.dispatch(p.state.tr.insertText('', insertPos, insertPos + overwrite))\n },\n /**\n * @param {Y.Doc} y\n * @param {prng.PRNG} gen\n * @param {EditorView} p\n */\n (y, gen, p) => { // replace text\n const insertPos = prng.int32(gen, 0, p.state.doc.content.size)\n const overwrite = math.min(prng.int32(gen, 0, p.state.doc.content.size - insertPos), 2)\n const text = charCounter++ + prng.word(gen)\n p.dispatch(p.state.tr.insertText(text, insertPos, insertPos + overwrite))\n },\n /**\n * @param {Y.Doc} y\n * @param {prng.PRNG} gen\n * @param {EditorView} p\n */\n (y, gen, p) => { // insert paragraph\n const insertPos = prng.int32(gen, 0, p.state.doc.content.size)\n const marks = prng.oneOf(gen, marksChoices)\n const tr = p.state.tr\n const text = charCounter++ + prng.word(gen)\n p.dispatch(tr.insert(insertPos, schema.node('paragraph', undefined, schema.text(text, marks))))\n },\n /**\n * @param {Y.Doc} y\n * @param {prng.PRNG} gen\n * @param {EditorView} p\n */\n (y, gen, p) => { // insert codeblock\n const insertPos = prng.int32(gen, 0, p.state.doc.content.size)\n const tr = p.state.tr\n const text = charCounter++ + prng.word(gen)\n p.dispatch(tr.insert(insertPos, schema.node('code_block', undefined, schema.text(text))))\n },\n /**\n * @param {Y.Doc} y\n * @param {prng.PRNG} gen\n * @param {EditorView} p\n */\n (y, gen, p) => { // wrap in blockquote\n const insertPos = prng.int32(gen, 0, p.state.doc.content.size)\n const overwrite = prng.int32(gen, 0, p.state.doc.content.size - insertPos)\n const tr = p.state.tr\n tr.setSelection(TextSelection.create(tr.doc, insertPos, insertPos + overwrite))\n const $from = tr.selection.$from\n const $to = tr.selection.$to\n const range = $from.blockRange($to)\n const wrapping = range && findWrapping(range, schema.nodes.blockquote)\n if (wrapping) {\n p.dispatch(tr.wrap(range, wrapping))\n }\n }\n]\n\n/**\n * @param {any} result\n */\nconst checkResult = result => {\n for (let i = 1; i < result.testObjects.length; i++) {\n const p1 = result.testObjects[i - 1].state.doc.toJSON()\n const p2 = result.testObjects[i].state.doc.toJSON()\n t.compare(p1, p2)\n }\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testRepeatGenerateProsemirrorChanges2 = tc => {\n checkResult(applyRandomTests(tc, pmChanges, 2, createNewProsemirrorView))\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testRepeatGenerateProsemirrorChanges3 = tc => {\n checkResult(applyRandomTests(tc, pmChanges, 3, createNewProsemirrorView))\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testRepeatGenerateProsemirrorChanges30 = tc => {\n checkResult(applyRandomTests(tc, pmChanges, 30, createNewProsemirrorView))\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testRepeatGenerateProsemirrorChanges40 = tc => {\n checkResult(applyRandomTests(tc, pmChanges, 40, createNewProsemirrorView))\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testRepeatGenerateProsemirrorChanges70 = tc => {\n checkResult(applyRandomTests(tc, pmChanges, 70, createNewProsemirrorView))\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testRepeatGenerateProsemirrorChanges100 = tc => {\n checkResult(applyRandomTests(tc, pmChanges, 100, createNewProsemirrorView))\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testRepeatGenerateProsemirrorChanges300 = tc => {\n checkResult(applyRandomTests(tc, pmChanges, 300, createNewProsemirrorView))\n}\n","// @ts-nocheck\nimport fs from 'fs'\nimport path from 'path'\nimport jsdom from 'jsdom'\n\nimport * as prosemirror from './y-prosemirror.test.js'\n\nimport { runTests } from 'lib0/testing.js'\nimport { isBrowser, isNode } from 'lib0/environment.js'\nimport * as log from 'lib0/logging.js'\n\nconst documentContent = fs.readFileSync(path.join(__dirname, '../test.html'))\nconst { window } = new jsdom.JSDOM(documentContent)\n\nglobal.window = window\nglobal.document = window.document\nglobal.innerHeight = 0\ndocument.getSelection = () => ({ })\n\ndocument.createRange = () => ({\n setStart () {},\n setEnd () {},\n getClientRects () {\n return {\n left: 0,\n top: 0,\n right: 0,\n bottom: 0\n }\n },\n getBoundingClientRect () {\n return {\n left: 0,\n top: 0,\n right: 0,\n bottom: 0\n }\n }\n})\n\nif (isBrowser) {\n log.createVConsole(document.body)\n}\nrunTests({\n prosemirror\n}).then(success => {\n /* istanbul ignore next */\n if (isNode) {\n process.exit(success ? 0 : 1)\n }\n})\n"],"names":["Observable","math.floor","array.appendTo","map.setIfUndefined","encoding.writeVarUint","decoding.readVarUint","decoding.createDecoder","random.uint32","random.uuidv4","array.from","error.methodUnimplemented","decoding.readUint8","decoding.readVarString","decoding.readAny","buffer.copyUint8Array","decoding.readVarUint8Array","decoding.IntDiffOptRleDecoder","decoding.UintOptRleDecoder","decoding.RleDecoder","decoding.StringDecoder","encoding.createEncoder","encoding.Encoder","encoding.toUint8Array","encoding.writeUint8","encoding.writeVarString","encoding.writeAny","encoding.writeVarUint8Array","error.unexpectedCase","encoding.IntDiffOptRleEncoder","encoding.UintOptRleEncoder","encoding.RleEncoder","encoding.StringEncoder","encoding.writeUint8Array","binary.BITS5","binary.BIT7","binary.BIT8","binary.BIT6","f.callAll","set.create","map.any","math.min","callAll","math.max","logging.print","logging.ORANGE","logging.BOLD","logging.UNBOLD","logging.RED","time.getUnixTime","array.last","math.abs","error.create","iterator.iteratorFilter","iterator.iteratorMap","object.equalFlat","map.create","map.copy","binary.BIT2","binary.BIT4","binary.BIT1","binary.BIT3","Y.encodeStateVector","Y.encodeStateAsUpdate","Y.applyUpdate","readUpdate","Y.Doc","syncProtocol.writeUpdate","syncProtocol.writeSyncStep1","prng.oneOf","syncProtocol.readSyncMessage","encoding.length","prng.bool","Y.useV2Encoding","Y.useV1Encoding","Y.YXmlElement","t.assert","t.compare","object.hasProperty","Y.AbstractType","Y.getStateVector","Y.createDeleteSetFromStructStore","Y.compareIDs","t.fail","Y.Item","prng.int32","PluginKey","isVisible","Y.isDeleted","Plugin","TextSelection","createMutex","isBrowser","doc","Y.createSnapshot","Y.createDeleteSet","PMSlice","PMFragment","snapshot","Y.snapshot","Y.iterateDeletedStructs","Y.typeListToArraySnapshot","Y.Snapshot","Y.XmlElement","methodUnimplemented","Y.XmlText","equalAttrs","keys","min","Y.ContentString","Y.ContentFormat","simpleDiff","Y.createRelativePositionFromTypeIndex","Y.RelativePosition","Y.findRootTypeKey","createRelativePosition","Y.createID","Y.createAbsolutePositionFromRelativePosition","Y.isParentOf","Y.XmlFragment","Node","Schema","schema","basicSchema.schema","t.compareStrings","EditorView","EditorState","complexSchema","prng.word","findWrapping","fs","path","window","jsdom","log.createVConsole","runTests","isNode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,iBAAiB,SAASA,wBAAU,CAAC;AAClD;AACA;AACA;AACA;AACA,EAAE,WAAW,CAAC,CAAC,IAAI,EAAE,SAAS,EAAE;AAChC,IAAI,KAAK,GAAE;AACX,IAAI,IAAI,CAAC,GAAG,GAAG,KAAI;AACnB,IAA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AC;;"} \ No newline at end of file diff --git a/dist/test.js b/dist/test.js new file mode 100644 index 0000000..974137e --- /dev/null +++ b/dist/test.js @@ -0,0 +1,25582 @@ +(function () { + 'use strict'; + + /** + * Utility module to work with key-value stores. + * + * @module map + */ + + /** + * Creates a new Map instance. + * + * @function + * @return {Map} + * + * @function + */ + const create = () => new Map(); + + /** + * Copy a Map object into a fresh Map object. + * + * @function + * @template X,Y + * @param {Map} m + * @return {Map} + */ + const copy = m => { + const r = create(); + m.forEach((v, k) => { r.set(k, v); }); + return r + }; + + /** + * Get map property. Create T if property is undefined and set T on map. + * + * ```js + * const listeners = map.setIfUndefined(events, 'eventName', set.create) + * listeners.add(listener) + * ``` + * + * @function + * @template T,K + * @param {Map} map + * @param {K} key + * @param {function():T} createT + * @return {T} + */ + const setIfUndefined = (map, key, createT) => { + let set = map.get(key); + if (set === undefined) { + map.set(key, set = createT()); + } + return set + }; + + /** + * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function. + * + * @function + * @template K + * @template V + * @template R + * @param {Map} m + * @param {function(V,K):R} f + * @return {Array} + */ + const map = (m, f) => { + const res = []; + for (const [key, value] of m) { + res.push(f(value, key)); + } + return res + }; + + /** + * Tests whether any key-value pairs pass the test implemented by `f(value, key)`. + * + * @todo should rename to some - similarly to Array.some + * + * @function + * @template K + * @template V + * @param {Map} m + * @param {function(V,K):boolean} f + * @return {boolean} + */ + const any = (m, f) => { + for (const [key, value] of m) { + if (f(value, key)) { + return true + } + } + return false + }; + + /** + * Utility module to work with strings. + * + * @module string + */ + + const fromCharCode = String.fromCharCode; + + /** + * @param {string} s + * @return {string} + */ + const toLowerCase = s => s.toLowerCase(); + + const trimLeftRegex = /^\s*/g; + + /** + * @param {string} s + * @return {string} + */ + const trimLeft = s => s.replace(trimLeftRegex, ''); + + const fromCamelCaseRegex = /([A-Z])/g; + + /** + * @param {string} s + * @param {string} separator + * @return {string} + */ + const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`)); + + /* istanbul ignore next */ + const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null); + + /* istanbul ignore next */ + let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }); + + /* istanbul ignore next */ + if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) { + // Safari doesn't handle BOM correctly. + // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called. + // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and + // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call + // Another issue is that from then on no BOM chars are recognized anymore + /* istanbul ignore next */ + utf8TextDecoder = null; + } + + /** + * Often used conditions. + * + * @module conditions + */ + + /** + * @template T + * @param {T|null|undefined} v + * @return {T|null} + */ + /* istanbul ignore next */ + const undefinedToNull = v => v === undefined ? null : v; + + /* global localStorage */ + + /** + * Isomorphic variable storage. + * + * Uses LocalStorage in the browser and falls back to in-memory storage. + * + * @module storage + */ + + /* istanbul ignore next */ + class VarStoragePolyfill { + constructor () { + this.map = new Map(); + } + + /** + * @param {string} key + * @param {any} value + */ + setItem (key, value) { + this.map.set(key, value); + } + + /** + * @param {string} key + */ + getItem (key) { + return this.map.get(key) + } + } + + /* istanbul ignore next */ + /** + * @type {any} + */ + let _localStorage = new VarStoragePolyfill(); + + try { + // if the same-origin rule is violated, accessing localStorage might thrown an error + /* istanbul ignore next */ + if (typeof localStorage !== 'undefined') { + _localStorage = localStorage; + } + } catch (e) { } + + /* istanbul ignore next */ + /** + * This is basically localStorage in browser, or a polyfill in nodejs + */ + const varStorage = _localStorage; + + /** + * Isomorphic module to work access the environment (query params, env variables). + * + * @module map + */ + + /* istanbul ignore next */ + // @ts-ignore + const isNode = typeof process !== 'undefined' && process.release && /node|io\.js/.test(process.release.name); + /* istanbul ignore next */ + const isBrowser = typeof window !== 'undefined' && !isNode; + /* istanbul ignore next */ + const isMac = typeof navigator !== 'undefined' ? /Mac/.test(navigator.platform) : false; + + /** + * @type {Map} + */ + let params; + + /* istanbul ignore next */ + const computeParams = () => { + if (params === undefined) { + if (isNode) { + params = create(); + const pargs = process.argv; + let currParamName = null; + /* istanbul ignore next */ + for (let i = 0; i < pargs.length; i++) { + const parg = pargs[i]; + if (parg[0] === '-') { + if (currParamName !== null) { + params.set(currParamName, ''); + } + currParamName = parg; + } else { + if (currParamName !== null) { + params.set(currParamName, parg); + currParamName = null; + } + } + } + if (currParamName !== null) { + params.set(currParamName, ''); + } + // in ReactNative for example this would not be true (unless connected to the Remote Debugger) + } else if (typeof location === 'object') { + params = create() + // eslint-disable-next-line no-undef + ;(location.search || '?').slice(1).split('&').forEach(kv => { + if (kv.length !== 0) { + const [key, value] = kv.split('='); + params.set(`--${fromCamelCase(key, '-')}`, value); + params.set(`-${fromCamelCase(key, '-')}`, value); + } + }); + } else { + params = create(); + } + } + return params + }; + + /** + * @param {string} name + * @return {boolean} + */ + /* istanbul ignore next */ + const hasParam = name => computeParams().has(name); + + /** + * @param {string} name + * @param {string} defaultVal + * @return {string} + */ + /* istanbul ignore next */ + const getParam = (name, defaultVal) => computeParams().get(name) || defaultVal; + // export const getArgs = name => computeParams() && args + + /** + * @param {string} name + * @return {string|null} + */ + /* istanbul ignore next */ + const getVariable = name => isNode ? undefinedToNull(process.env[name.toUpperCase()]) : undefinedToNull(varStorage.getItem(name)); + + /** + * @param {string} name + * @return {boolean} + */ + /* istanbul ignore next */ + const hasConf = name => hasParam('--' + name) || getVariable(name) !== null; + + /* istanbul ignore next */ + const production = hasConf('production'); + + /** + * Utility module to work with EcmaScript Symbols. + * + * @module symbol + */ + + /** + * Return fresh symbol. + * + * @return {Symbol} + */ + const create$1 = Symbol; + + /** + * Working with value pairs. + * + * @module pair + */ + + /** + * @template L,R + */ + class Pair { + /** + * @param {L} left + * @param {R} right + */ + constructor (left, right) { + this.left = left; + this.right = right; + } + } + + /** + * @template L,R + * @param {L} left + * @param {R} right + * @return {Pair} + */ + const create$2 = (left, right) => new Pair(left, right); + + /** + * @template L,R + * @param {Array>} arr + * @param {function(L, R):any} f + */ + const forEach = (arr, f) => arr.forEach(p => f(p.left, p.right)); + + /* eslint-env browser */ + + /* istanbul ignore next */ + /** + * @type {Document} + */ + const doc = /** @type {Document} */ (typeof document !== 'undefined' ? document : {}); + + /** + * @param {string} name + * @return {HTMLElement} + */ + /* istanbul ignore next */ + const createElement = name => doc.createElement(name); + + /** + * @return {DocumentFragment} + */ + /* istanbul ignore next */ + const createDocumentFragment = () => doc.createDocumentFragment(); + + /** + * @param {string} text + * @return {Text} + */ + /* istanbul ignore next */ + const createTextNode = text => doc.createTextNode(text); + + /* istanbul ignore next */ + const domParser = /** @type {DOMParser} */ (typeof DOMParser !== 'undefined' ? new DOMParser() : null); + + /** + * @param {Element} el + * @param {Array>} attrs Array of key-value pairs + * @return {Element} + */ + /* istanbul ignore next */ + const setAttributes = (el, attrs) => { + forEach(attrs, (key, value) => { + if (value === false) { + el.removeAttribute(key); + } else if (value === true) { + el.setAttribute(key, ''); + } else { + // @ts-ignore + el.setAttribute(key, value); + } + }); + return el + }; + + /** + * @param {Array|HTMLCollection} children + * @return {DocumentFragment} + */ + /* istanbul ignore next */ + const fragment = children => { + const fragment = createDocumentFragment(); + for (let i = 0; i < children.length; i++) { + appendChild(fragment, children[i]); + } + return fragment + }; + + /** + * @param {Element} parent + * @param {Array} nodes + * @return {Element} + */ + /* istanbul ignore next */ + const append = (parent, nodes) => { + appendChild(parent, fragment(nodes)); + return parent + }; + + /** + * @param {EventTarget} el + * @param {string} name + * @param {EventListener} f + */ + /* istanbul ignore next */ + const addEventListener = (el, name, f) => el.addEventListener(name, f); + + /** + * @param {string} name + * @param {Array|pair.Pair>} attrs Array of key-value pairs + * @param {Array} children + * @return {Element} + */ + /* istanbul ignore next */ + const element = (name, attrs = [], children = []) => + append(setAttributes(createElement(name), attrs), children); + + /** + * @param {string} t + * @return {Text} + */ + /* istanbul ignore next */ + const text = createTextNode; + + /** + * @param {Map} m + * @return {string} + */ + /* istanbul ignore next */ + const mapToStyleString = m => map(m, (value, key) => `${key}:${value};`).join(''); + + /** + * @param {Node} parent + * @param {Node} child + * @return {Node} + */ + /* istanbul ignore next */ + const appendChild = (parent, child) => parent.appendChild(child); + + /** + * JSON utility functions. + * + * @module json + */ + + /** + * Transform JavaScript object to JSON. + * + * @param {any} object + * @return {string} + */ + const stringify = JSON.stringify; + + /* global requestIdleCallback, requestAnimationFrame, cancelIdleCallback, cancelAnimationFrame */ + + /** + * Utility module to work with EcmaScript's event loop. + * + * @module eventloop + */ + + /** + * @type {Array} + */ + let queue = []; + + const _runQueue = () => { + for (let i = 0; i < queue.length; i++) { + queue[i](); + } + queue = []; + }; + + /** + * @param {function():void} f + */ + const enqueue = f => { + queue.push(f); + if (queue.length === 1) { + setTimeout(_runQueue, 0); + } + }; + + /** + * Common Math expressions. + * + * @module math + */ + + const floor = Math.floor; + const ceil = Math.ceil; + const abs = Math.abs; + const round = Math.round; + const log10 = Math.log10; + + /** + * @function + * @param {number} a + * @param {number} b + * @return {number} The sum of a and b + */ + const add = (a, b) => a + b; + + /** + * @function + * @param {number} a + * @param {number} b + * @return {number} The smaller element of a and b + */ + const min = (a, b) => a < b ? a : b; + + /** + * @function + * @param {number} a + * @param {number} b + * @return {number} The bigger element of a and b + */ + const max = (a, b) => a > b ? a : b; + /** + * Base 10 exponential function. Returns the value of 10 raised to the power of pow. + * + * @param {number} exp + * @return {number} + */ + const exp10 = exp => Math.pow(10, exp); + + /** + * @param {number} n + * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0 + */ + const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0; + + /** + * Utility module to convert metric values. + * + * @module metric + */ + + const prefixUp = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; + const prefixDown = ['', 'm', 'μ', 'n', 'p', 'f', 'a', 'z', 'y']; + + /** + * Calculate the metric prefix for a number. Assumes E.g. `prefix(1000) = { n: 1, prefix: 'k' }` + * + * @param {number} n + * @param {number} [baseMultiplier] Multiplier of the base (10^(3*baseMultiplier)). E.g. `convert(time, -3)` if time is already in milli seconds + * @return {{n:number,prefix:string}} + */ + const prefix = (n, baseMultiplier = 0) => { + const nPow = n === 0 ? 0 : log10(n); + let mult = 0; + while (nPow < mult * 3 && baseMultiplier > -8) { + baseMultiplier--; + mult--; + } + while (nPow >= 3 + mult * 3 && baseMultiplier < 8) { + baseMultiplier++; + mult++; + } + const prefix = baseMultiplier < 0 ? prefixDown[-baseMultiplier] : prefixUp[baseMultiplier]; + return { + n: round((mult > 0 ? n / exp10(mult * 3) : n * exp10(mult * -3)) * 1e12) / 1e12, + prefix + } + }; + + /** + * Utility module to work with time. + * + * @module time + */ + + /** + * Return current unix time. + * + * @return {number} + */ + const getUnixTime = Date.now; + + /** + * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs. + * + * @param {number} d duration in milliseconds + * @return {string} humanized approximation of time + */ + const humanizeDuration = d => { + if (d < 60000) { + const p = prefix(d, -1); + return round(p.n * 100) / 100 + p.prefix + 's' + } + d = floor(d / 1000); + const seconds = d % 60; + const minutes = floor(d / 60) % 60; + const hours = floor(d / 3600) % 24; + const days = floor(d / 86400); + if (days > 0) { + return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '') + } + if (hours > 0) { + /* istanbul ignore next */ + return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '') + } + return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '') + }; + + /** + * Utility module to work with Arrays. + * + * @module array + */ + + /** + * Return the last element of an array. The element must exist + * + * @template L + * @param {Array} arr + * @return {L} + */ + const last = arr => arr[arr.length - 1]; + + /** + * Append elements from src to dest + * + * @template M + * @param {Array} dest + * @param {Array} src + */ + const appendTo = (dest, src) => { + for (let i = 0; i < src.length; i++) { + dest.push(src[i]); + } + }; + + /** + * Transforms something array-like to an actual Array. + * + * @function + * @template T + * @param {ArrayLike|Iterable} arraylike + * @return {T} + */ + const from = Array.from; + + /** + * Utility functions for working with EcmaScript objects. + * + * @module object + */ + + /** + * @param {Object} obj + */ + const keys = Object.keys; + + /** + * @param {Object} obj + * @param {function(any,string):any} f + */ + const forEach$1 = (obj, f) => { + for (const key in obj) { + f(obj[key], key); + } + }; + + /** + * @template R + * @param {Object} obj + * @param {function(any,string):R} f + * @return {Array} + */ + const map$1 = (obj, f) => { + const results = []; + for (const key in obj) { + results.push(f(obj[key], key)); + } + return results + }; + + /** + * @param {Object} obj + * @return {number} + */ + const length = obj => keys(obj).length; + + /** + * @param {Object} obj + * @param {function(any,string):boolean} f + * @return {boolean} + */ + const every = (obj, f) => { + for (const key in obj) { + if (!f(obj[key], key)) { + return false + } + } + return true + }; + + /** + * Calls `Object.prototype.hasOwnProperty`. + * + * @param {any} obj + * @param {string|symbol} key + * @return {boolean} + */ + const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key); + + /** + * @param {Object} a + * @param {Object} b + * @return {boolean} + */ + const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val)); + + /** + * Common functions and function call helpers. + * + * @module function + */ + + /** + * Calls all functions in `fs` with args. Only throws after all functions were called. + * + * @param {Array} fs + * @param {Array} args + */ + const callAll = (fs, args, i = 0) => { + try { + for (; i < fs.length; i++) { + fs[i](...args); + } + } finally { + if (i < fs.length) { + callAll(fs, args, i + 1); + } + } + }; + + /** + * Isomorphic logging module with support for colors! + * + * @module logging + */ + + const BOLD = create$1(); + const UNBOLD = create$1(); + const BLUE = create$1(); + const GREY = create$1(); + const GREEN = create$1(); + const RED = create$1(); + const PURPLE = create$1(); + const ORANGE = create$1(); + const UNCOLOR = create$1(); + + /** + * @type {Object>} + */ + const _browserStyleMap = { + [BOLD]: create$2('font-weight', 'bold'), + [UNBOLD]: create$2('font-weight', 'normal'), + [BLUE]: create$2('color', 'blue'), + [GREEN]: create$2('color', 'green'), + [GREY]: create$2('color', 'grey'), + [RED]: create$2('color', 'red'), + [PURPLE]: create$2('color', 'purple'), + [ORANGE]: create$2('color', 'orange'), // not well supported in chrome when debugging node with inspector - TODO: deprecate + [UNCOLOR]: create$2('color', 'black') + }; + + const _nodeStyleMap = { + [BOLD]: '\u001b[1m', + [UNBOLD]: '\u001b[2m', + [BLUE]: '\x1b[34m', + [GREEN]: '\x1b[32m', + [GREY]: '\u001b[37m', + [RED]: '\x1b[31m', + [PURPLE]: '\x1b[35m', + [ORANGE]: '\x1b[38;5;208m', + [UNCOLOR]: '\x1b[0m' + }; + + /* istanbul ignore next */ + /** + * @param {Array} args + * @return {Array} + */ + const computeBrowserLoggingArgs = args => { + const strBuilder = []; + const styles = []; + const currentStyle = create(); + /** + * @type {Array} + */ + let logArgs = []; + // try with formatting until we find something unsupported + let i = 0; + + for (; i < args.length; i++) { + const arg = args[i]; + // @ts-ignore + const style = _browserStyleMap[arg]; + if (style !== undefined) { + currentStyle.set(style.left, style.right); + } else { + if (arg.constructor === String || arg.constructor === Number) { + const style = mapToStyleString(currentStyle); + if (i > 0 || style.length > 0) { + strBuilder.push('%c' + arg); + styles.push(style); + } else { + strBuilder.push(arg); + } + } else { + break + } + } + } + + if (i > 0) { + // create logArgs with what we have so far + logArgs = styles; + logArgs.unshift(strBuilder.join('')); + } + // append the rest + for (; i < args.length; i++) { + const arg = args[i]; + if (!(arg instanceof Symbol)) { + logArgs.push(arg); + } + } + return logArgs + }; + + /** + * @param {Array} args + * @return {Array} + */ + const computeNodeLoggingArgs = args => { + const strBuilder = []; + const logArgs = []; + + // try with formatting until we find something unsupported + let i = 0; + + for (; i < args.length; i++) { + const arg = args[i]; + // @ts-ignore + const style = _nodeStyleMap[arg]; + if (style !== undefined) { + strBuilder.push(style); + } else { + if (arg.constructor === String || arg.constructor === Number) { + strBuilder.push(arg); + } else { + break + } + } + } + if (i > 0) { + // create logArgs with what we have so far + strBuilder.push('\x1b[0m'); + logArgs.push(strBuilder.join('')); + } + // append the rest + for (; i < args.length; i++) { + const arg = args[i]; + /* istanbul ignore else */ + if (!(arg instanceof Symbol)) { + logArgs.push(arg); + } + } + return logArgs + }; + + /* istanbul ignore next */ + const computeLoggingArgs = isNode ? computeNodeLoggingArgs : computeBrowserLoggingArgs; + + /** + * @param {Array} args + */ + const print = (...args) => { + console.log(...computeLoggingArgs(args)); + /* istanbul ignore next */ + vconsoles.forEach(vc => vc.print(args)); + }; + + /* istanbul ignore next */ + /** + * @param {Error} err + */ + const printError = err => { + console.error(err); + vconsoles.forEach(vc => vc.printError(err)); + }; + + /* istanbul ignore next */ + /** + * @param {string} url image location + * @param {number} height height of the image in pixel + */ + const printImg = (url, height) => { + if (isBrowser) { + console.log('%c ', `font-size: ${height}px; background-size: contain; background-repeat: no-repeat; background-image: url(${url})`); + // console.log('%c ', `font-size: ${height}x; background: url(${url}) no-repeat;`) + } + vconsoles.forEach(vc => vc.printImg(url, height)); + }; + + /* istanbul ignore next */ + /** + * @param {string} base64 + * @param {number} height + */ + const printImgBase64 = (base64, height) => printImg(`data:image/gif;base64,${base64}`, height); + + /** + * @param {Array} args + */ + const group = (...args) => { + console.group(...computeLoggingArgs(args)); + /* istanbul ignore next */ + vconsoles.forEach(vc => vc.group(args)); + }; + + /** + * @param {Array} args + */ + const groupCollapsed = (...args) => { + console.groupCollapsed(...computeLoggingArgs(args)); + /* istanbul ignore next */ + vconsoles.forEach(vc => vc.groupCollapsed(args)); + }; + + const groupEnd = () => { + console.groupEnd(); + /* istanbul ignore next */ + vconsoles.forEach(vc => vc.groupEnd()); + }; + + const vconsoles = new Set(); + + /* istanbul ignore next */ + /** + * @param {Array} args + * @return {Array} + */ + const _computeLineSpans = args => { + const spans = []; + const currentStyle = new Map(); + // try with formatting until we find something unsupported + let i = 0; + for (; i < args.length; i++) { + const arg = args[i]; + // @ts-ignore + const style = _browserStyleMap[arg]; + if (style !== undefined) { + currentStyle.set(style.left, style.right); + } else { + if (arg.constructor === String || arg.constructor === Number) { + // @ts-ignore + const span = element('span', [create$2('style', mapToStyleString(currentStyle))], [text(arg)]); + if (span.innerHTML === '') { + span.innerHTML = ' '; + } + spans.push(span); + } else { + break + } + } + } + // append the rest + for (; i < args.length; i++) { + let content = args[i]; + if (!(content instanceof Symbol)) { + if (content.constructor !== String && content.constructor !== Number) { + content = ' ' + stringify(content) + ' '; + } + spans.push(element('span', [], [text(/** @type {string} */ (content))])); + } + } + return spans + }; + + const lineStyle = 'font-family:monospace;border-bottom:1px solid #e2e2e2;padding:2px;'; + + /* istanbul ignore next */ + class VConsole { + /** + * @param {Element} dom + */ + constructor (dom) { + this.dom = dom; + /** + * @type {Element} + */ + this.ccontainer = this.dom; + this.depth = 0; + vconsoles.add(this); + } + + /** + * @param {Array} args + * @param {boolean} collapsed + */ + group (args, collapsed = false) { + enqueue(() => { + const triangleDown = element('span', [create$2('hidden', collapsed), create$2('style', 'color:grey;font-size:120%;')], [text('▼')]); + const triangleRight = element('span', [create$2('hidden', !collapsed), create$2('style', 'color:grey;font-size:125%;')], [text('▶')]); + const content = element('div', [create$2('style', `${lineStyle};padding-left:${this.depth * 10}px`)], [triangleDown, triangleRight, text(' ')].concat(_computeLineSpans(args))); + const nextContainer = element('div', [create$2('hidden', collapsed)]); + const nextLine = element('div', [], [content, nextContainer]); + append(this.ccontainer, [nextLine]); + this.ccontainer = nextContainer; + this.depth++; + // when header is clicked, collapse/uncollapse container + addEventListener(content, 'click', event => { + nextContainer.toggleAttribute('hidden'); + triangleDown.toggleAttribute('hidden'); + triangleRight.toggleAttribute('hidden'); + }); + }); + } + + /** + * @param {Array} args + */ + groupCollapsed (args) { + this.group(args, true); + } + + groupEnd () { + enqueue(() => { + if (this.depth > 0) { + this.depth--; + // @ts-ignore + this.ccontainer = this.ccontainer.parentElement.parentElement; + } + }); + } + + /** + * @param {Array} args + */ + print (args) { + enqueue(() => { + append(this.ccontainer, [element('div', [create$2('style', `${lineStyle};padding-left:${this.depth * 10}px`)], _computeLineSpans(args))]); + }); + } + + /** + * @param {Error} err + */ + printError (err) { + this.print([RED, BOLD, err.toString()]); + } + + /** + * @param {string} url + * @param {number} height + */ + printImg (url, height) { + enqueue(() => { + append(this.ccontainer, [element('img', [create$2('src', url), create$2('height', `${round(height * 1.5)}px`)])]); + }); + } + + /** + * @param {Node} node + */ + printDom (node) { + enqueue(() => { + append(this.ccontainer, [node]); + }); + } + + destroy () { + enqueue(() => { + vconsoles.delete(this); + }); + } + } + + /* istanbul ignore next */ + /** + * @param {Element} dom + */ + const createVConsole = dom => new VConsole(dom); + + /** + * Efficient diffs. + * + * @module diff + */ + + /** + * A SimpleDiff describes a change on a String. + * + * ```js + * console.log(a) // the old value + * console.log(b) // the updated value + * // Apply changes of diff (pseudocode) + * a.remove(diff.index, diff.remove) // Remove `diff.remove` characters + * a.insert(diff.index, diff.insert) // Insert `diff.insert` + * a === b // values match + * ``` + * + * @typedef {Object} SimpleDiff + * @property {Number} index The index where changes were applied + * @property {Number} remove The number of characters to delete starting + * at `index`. + * @property {T} insert The new text to insert at `index` after applying + * `delete` + * + * @template T + */ + + /** + * Create a diff between two strings. This diff implementation is highly + * efficient, but not very sophisticated. + * + * @function + * + * @param {string} a The old version of the string + * @param {string} b The updated version of the string + * @return {SimpleDiff} The diff description. + */ + const simpleDiffString = (a, b) => { + let left = 0; // number of same characters counting from left + let right = 0; // number of same characters counting from right + while (left < a.length && left < b.length && a[left] === b[left]) { + left++; + } + if (left !== a.length || left !== b.length) { + // Only check right if a !== b + while (right + left < a.length && right + left < b.length && a[a.length - right - 1] === b[b.length - right - 1]) { + right++; + } + } + return { + index: left, + remove: a.length - left - right, + insert: b.slice(left, b.length - right) + } + }; + + /** + * @todo Remove in favor of simpleDiffString + * @deprecated + */ + const simpleDiff = simpleDiffString; + + /* eslint-env browser */ + const perf = typeof performance === 'undefined' ? null : performance; + + const isoCrypto = typeof crypto === 'undefined' ? null : crypto; + + /** + * @type {function(number):ArrayBuffer} + */ + const cryptoRandomBuffer = isoCrypto !== null + ? len => { + // browser + const buf = new ArrayBuffer(len); + const arr = new Uint8Array(buf); + isoCrypto.getRandomValues(arr); + return buf + } + : len => { + // polyfill + const buf = new ArrayBuffer(len); + const arr = new Uint8Array(buf); + for (let i = 0; i < len; i++) { + arr[i] = Math.ceil((Math.random() * 0xFFFFFFFF) >>> 0); + } + return buf + }; + + var performance_1 = perf; + var cryptoRandomBuffer_1 = cryptoRandomBuffer; + + var isoBrowser = { + performance: performance_1, + cryptoRandomBuffer: cryptoRandomBuffer_1 + }; + + /** + * Isomorphic library exports from isomorphic.js. + * + * @module isomorphic + */ + + const performance$1 = /** @type {any} */ (isoBrowser.performance); + const cryptoRandomBuffer$1 = /** @type {any} */ (isoBrowser.cryptoRandomBuffer); + + /* istanbul ignore next */ + const uint32 = () => new Uint32Array(cryptoRandomBuffer$1(4))[0]; + + // @ts-ignore + const uuidv4Template = [1e7] + -1e3 + -4e3 + -8e3 + -1e11; + const uuidv4 = () => uuidv4Template.replace(/[018]/g, /** @param {number} c */ c => + (c ^ uint32() & 15 >> c / 4).toString(16) + ); + + /* eslint-env browser */ + + /** + * Binary data constants. + * + * @module binary + */ + + /** + * n-th bit activated. + * + * @type {number} + */ + const BIT1 = 1; + const BIT2 = 2; + const BIT3 = 4; + const BIT4 = 8; + const BIT6 = 32; + const BIT7 = 64; + const BIT8 = 128; + const BITS5 = 31; + const BITS6 = 63; + const BITS7 = 127; + /** + * @type {number} + */ + const BITS31 = 0x7FFFFFFF; + /** + * @type {number} + */ + const BITS32 = 0xFFFFFFFF; + + /** + * @module prng + */ + + /** + * Xorshift32 is a very simple but elegang PRNG with a period of `2^32-1`. + */ + class Xorshift32 { + /** + * @param {number} seed Unsigned 32 bit number + */ + constructor (seed) { + this.seed = seed; + /** + * @type {number} + */ + this._state = seed; + } + + /** + * Generate a random signed integer. + * + * @return {Number} A 32 bit signed integer. + */ + next () { + let x = this._state; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + this._state = x; + return (x >>> 0) / (BITS32 + 1) + } + } + + /** + * @module prng + */ + + /** + * This is a variant of xoroshiro128plus - the fastest full-period generator passing BigCrush without systematic failures. + * + * This implementation follows the idea of the original xoroshiro128plus implementation, + * but is optimized for the JavaScript runtime. I.e. + * * The operations are performed on 32bit integers (the original implementation works with 64bit values). + * * The initial 128bit state is computed based on a 32bit seed and Xorshift32. + * * This implementation returns two 32bit values based on the 64bit value that is computed by xoroshiro128plus. + * Caution: The last addition step works slightly different than in the original implementation - the add carry of the + * first 32bit addition is not carried over to the last 32bit. + * + * [Reference implementation](http://vigna.di.unimi.it/xorshift/xoroshiro128plus.c) + */ + class Xoroshiro128plus { + /** + * @param {number} seed Unsigned 32 bit number + */ + constructor (seed) { + this.seed = seed; + // This is a variant of Xoroshiro128plus to fill the initial state + const xorshift32 = new Xorshift32(seed); + this.state = new Uint32Array(4); + for (let i = 0; i < 4; i++) { + this.state[i] = xorshift32.next() * BITS32; + } + this._fresh = true; + } + + /** + * @return {number} Float/Double in [0,1) + */ + next () { + const state = this.state; + if (this._fresh) { + this._fresh = false; + return ((state[0] + state[2]) >>> 0) / (BITS32 + 1) + } else { + this._fresh = true; + const s0 = state[0]; + const s1 = state[1]; + const s2 = state[2] ^ s0; + const s3 = state[3] ^ s1; + // function js_rotl (x, k) { + // k = k - 32 + // const x1 = x[0] + // const x2 = x[1] + // x[0] = x2 << k | x1 >>> (32 - k) + // x[1] = x1 << k | x2 >>> (32 - k) + // } + // rotl(s0, 55) // k = 23 = 55 - 32; j = 9 = 32 - 23 + state[0] = (s1 << 23 | s0 >>> 9) ^ s2 ^ (s2 << 14 | s3 >>> 18); + state[1] = (s0 << 23 | s1 >>> 9) ^ s3 ^ (s3 << 14); + // rol(s1, 36) // k = 4 = 36 - 32; j = 23 = 32 - 9 + state[2] = s3 << 4 | s2 >>> 28; + state[3] = s2 << 4 | s3 >>> 28; + return (((state[1] + state[3]) >>> 0) / (BITS32 + 1)) + } + } + } + + /* + // Reference implementation + // Source: http://vigna.di.unimi.it/xorshift/xoroshiro128plus.c + // By David Blackman and Sebastiano Vigna + // Who published the reference implementation under Public Domain (CC0) + + #include + #include + + uint64_t s[2]; + + static inline uint64_t rotl(const uint64_t x, int k) { + return (x << k) | (x >> (64 - k)); + } + + uint64_t next(void) { + const uint64_t s0 = s[0]; + uint64_t s1 = s[1]; + s1 ^= s0; + s[0] = rotl(s0, 55) ^ s1 ^ (s1 << 14); // a, b + s[1] = rotl(s1, 36); // c + return (s[0] + s[1]) & 0xFFFFFFFF; + } + + int main(void) + { + int i; + s[0] = 1111 | (1337ul << 32); + s[1] = 1234 | (9999ul << 32); + + printf("1000 outputs of genrand_int31()\n"); + for (i=0; i<100; i++) { + printf("%10lu ", i); + printf("%10lu ", next()); + printf("- %10lu ", s[0] >> 32); + printf("%10lu ", (s[0] << 32) >> 32); + printf("%10lu ", s[1] >> 32); + printf("%10lu ", (s[1] << 32) >> 32); + printf("\n"); + // if (i%5==4) printf("\n"); + } + return 0; + } + */ + + /** + * Utility helpers for working with numbers. + * + * @module number + */ + + /** + * @module number + */ + + /* istanbul ignore next */ + const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && floor(num) === num); + + /** + * Efficient schema-less binary encoding with support for variable length encoding. + * + * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function. + * + * Encodes numbers in little-endian order (least to most significant byte order) + * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/) + * which is also used in Protocol Buffers. + * + * ```js + * // encoding step + * const encoder = new encoding.createEncoder() + * encoding.writeVarUint(encoder, 256) + * encoding.writeVarString(encoder, 'Hello world!') + * const buf = encoding.toUint8Array(encoder) + * ``` + * + * ```js + * // decoding step + * const decoder = new decoding.createDecoder(buf) + * decoding.readVarUint(decoder) // => 256 + * decoding.readVarString(decoder) // => 'Hello world!' + * decoding.hasContent(decoder) // => false - all data is read + * ``` + * + * @module encoding + */ + + /** + * A BinaryEncoder handles the encoding to an Uint8Array. + */ + class Encoder { + constructor () { + this.cpos = 0; + this.cbuf = new Uint8Array(100); + /** + * @type {Array} + */ + this.bufs = []; + } + } + + /** + * @function + * @return {Encoder} + */ + const createEncoder = () => new Encoder(); + + /** + * The current length of the encoded data. + * + * @function + * @param {Encoder} encoder + * @return {number} + */ + const length$1 = encoder => { + let len = encoder.cpos; + for (let i = 0; i < encoder.bufs.length; i++) { + len += encoder.bufs[i].length; + } + return len + }; + + /** + * Transform to Uint8Array. + * + * @function + * @param {Encoder} encoder + * @return {Uint8Array} The created ArrayBuffer. + */ + const toUint8Array = encoder => { + const uint8arr = new Uint8Array(length$1(encoder)); + let curPos = 0; + for (let i = 0; i < encoder.bufs.length; i++) { + const d = encoder.bufs[i]; + uint8arr.set(d, curPos); + curPos += d.length; + } + uint8arr.set(createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos); + return uint8arr + }; + + /** + * Verify that it is possible to write `len` bytes wtihout checking. If + * necessary, a new Buffer with the required length is attached. + * + * @param {Encoder} encoder + * @param {number} len + */ + const verifyLen = (encoder, len) => { + const bufferLen = encoder.cbuf.length; + if (bufferLen - encoder.cpos < len) { + encoder.bufs.push(createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos)); + encoder.cbuf = new Uint8Array(max(bufferLen, len) * 2); + encoder.cpos = 0; + } + }; + + /** + * Write one byte to the encoder. + * + * @function + * @param {Encoder} encoder + * @param {number} num The byte that is to be encoded. + */ + const write = (encoder, num) => { + const bufferLen = encoder.cbuf.length; + if (encoder.cpos === bufferLen) { + encoder.bufs.push(encoder.cbuf); + encoder.cbuf = new Uint8Array(bufferLen * 2); + encoder.cpos = 0; + } + encoder.cbuf[encoder.cpos++] = num; + }; + + /** + * Write one byte as an unsigned integer. + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ + const writeUint8 = write; + + /** + * Write a variable length unsigned integer. + * + * Encodes integers in the range from [0, 4294967295] / [0, 0xffffffff]. (max 32 bit unsigned integer) + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ + const writeVarUint = (encoder, num) => { + while (num > BITS7) { + write(encoder, BIT8 | (BITS7 & num)); + num >>>= 7; + } + write(encoder, BITS7 & num); + }; + + /** + * Write a variable length integer. + * + * Encodes integers in the range from [-2147483648, -2147483647]. + * + * We don't use zig-zag encoding because we want to keep the option open + * to use the same function for BigInt and 53bit integers (doubles). + * + * We use the 7th bit instead for signaling that this is a negative number. + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ + const writeVarInt = (encoder, num) => { + const isNegative = isNegativeZero(num); + if (isNegative) { + num = -num; + } + // |- whether to continue reading |- whether is negative |- number + write(encoder, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | (BITS6 & num)); + num >>>= 6; + // We don't need to consider the case of num === 0 so we can use a different + // pattern here than above. + while (num > 0) { + write(encoder, (num > BITS7 ? BIT8 : 0) | (BITS7 & num)); + num >>>= 7; + } + }; + + /** + * Write a variable length string. + * + * @function + * @param {Encoder} encoder + * @param {String} str The string that is to be encoded. + */ + const writeVarString = (encoder, str) => { + const encodedString = unescape(encodeURIComponent(str)); + const len = encodedString.length; + writeVarUint(encoder, len); + for (let i = 0; i < len; i++) { + write(encoder, /** @type {number} */ (encodedString.codePointAt(i))); + } + }; + + /** + * Append fixed-length Uint8Array to the encoder. + * + * @function + * @param {Encoder} encoder + * @param {Uint8Array} uint8Array + */ + const writeUint8Array = (encoder, uint8Array) => { + const bufferLen = encoder.cbuf.length; + const cpos = encoder.cpos; + const leftCopyLen = min(bufferLen - cpos, uint8Array.length); + const rightCopyLen = uint8Array.length - leftCopyLen; + encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos); + encoder.cpos += leftCopyLen; + if (rightCopyLen > 0) { + // Still something to write, write right half.. + // Append new buffer + encoder.bufs.push(encoder.cbuf); + // must have at least size of remaining buffer + encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen)); + // copy array + encoder.cbuf.set(uint8Array.subarray(leftCopyLen)); + encoder.cpos = rightCopyLen; + } + }; + + /** + * Append an Uint8Array to Encoder. + * + * @function + * @param {Encoder} encoder + * @param {Uint8Array} uint8Array + */ + const writeVarUint8Array = (encoder, uint8Array) => { + writeVarUint(encoder, uint8Array.byteLength); + writeUint8Array(encoder, uint8Array); + }; + + /** + * Create an DataView of the next `len` bytes. Use it to write data after + * calling this function. + * + * ```js + * // write float32 using DataView + * const dv = writeOnDataView(encoder, 4) + * dv.setFloat32(0, 1.1) + * // read float32 using DataView + * const dv = readFromDataView(encoder, 4) + * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result) + * ``` + * + * @param {Encoder} encoder + * @param {number} len + * @return {DataView} + */ + const writeOnDataView = (encoder, len) => { + verifyLen(encoder, len); + const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len); + encoder.cpos += len; + return dview + }; + + /** + * @param {Encoder} encoder + * @param {number} num + */ + const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num); + + /** + * @param {Encoder} encoder + * @param {number} num + */ + const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num); + + /** + * @param {Encoder} encoder + * @param {bigint} num + */ + const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num); + + const floatTestBed = new DataView(new ArrayBuffer(4)); + /** + * Check if a number can be encoded as a 32 bit float. + * + * @param {number} num + * @return {boolean} + */ + const isFloat32 = num => { + floatTestBed.setFloat32(0, num); + return floatTestBed.getFloat32(0) === num + }; + + /** + * Encode data with efficient binary format. + * + * Differences to JSON: + * • Transforms data to a binary format (not to a string) + * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON) + * • Numbers are efficiently encoded either as a variable length integer, as a + * 32 bit float, as a 64 bit float, or as a 64 bit bigint. + * + * Encoding table: + * + * | Data Type | Prefix | Encoding Method | Comment | + * | ------------------- | -------- | ------------------ | ------- | + * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined | + * | null | 126 | | | + * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers | + * | float32 | 124 | writeFloat32 | | + * | float64 | 123 | writeFloat64 | | + * | bigint | 122 | writeBigInt64 | | + * | boolean (false) | 121 | | True and false are different data types so we save the following byte | + * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false | + * | string | 119 | writeVarString | | + * | object | 118 | custom | Writes {length} then {length} key-value pairs | + * | array | 117 | custom | Writes {length} then {length} json values | + * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data | + * + * Reasons for the decreasing prefix: + * We need the first bit for extendability (later we may want to encode the + * prefix with writeVarUint). The remaining 7 bits are divided as follows: + * [0-30] the beginning of the data range is used for custom purposes + * (defined by the function that uses this library) + * [31-127] the end of the data range is used for data encoding by + * lib0/encoding.js + * + * @param {Encoder} encoder + * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data + */ + const writeAny = (encoder, data) => { + switch (typeof data) { + case 'string': + // TYPE 119: STRING + write(encoder, 119); + writeVarString(encoder, data); + break + case 'number': + if (isInteger(data) && data <= BITS31) { + // TYPE 125: INTEGER + write(encoder, 125); + writeVarInt(encoder, data); + } else if (isFloat32(data)) { + // TYPE 124: FLOAT32 + write(encoder, 124); + writeFloat32(encoder, data); + } else { + // TYPE 123: FLOAT64 + write(encoder, 123); + writeFloat64(encoder, data); + } + break + case 'bigint': + // TYPE 122: BigInt + write(encoder, 122); + writeBigInt64(encoder, data); + break + case 'object': + if (data === null) { + // TYPE 126: null + write(encoder, 126); + } else if (data instanceof Array) { + // TYPE 117: Array + write(encoder, 117); + writeVarUint(encoder, data.length); + for (let i = 0; i < data.length; i++) { + writeAny(encoder, data[i]); + } + } else if (data instanceof Uint8Array) { + // TYPE 116: ArrayBuffer + write(encoder, 116); + writeVarUint8Array(encoder, data); + } else { + // TYPE 118: Object + write(encoder, 118); + const keys = Object.keys(data); + writeVarUint(encoder, keys.length); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + writeVarString(encoder, key); + writeAny(encoder, data[key]); + } + } + break + case 'boolean': + // TYPE 120/121: boolean (true/false) + write(encoder, data ? 120 : 121); + break + default: + // TYPE 127: undefined + write(encoder, 127); + } + }; + + /** + * Now come a few stateful encoder that have their own classes. + */ + + /** + * Basic Run Length Encoder - a basic compression implementation. + * + * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated. + * + * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf + * + * @note T must not be null! + * + * @template T + */ + class RleEncoder extends Encoder { + /** + * @param {function(Encoder, T):void} writer + */ + constructor (writer) { + super(); + /** + * The writer + */ + this.w = writer; + /** + * Current state + * @type {T|null} + */ + this.s = null; + this.count = 0; + } + + /** + * @param {T} v + */ + write (v) { + if (this.s === v) { + this.count++; + } else { + if (this.count > 0) { + // flush counter, unless this is the first value (count = 0) + writeVarUint(this, this.count - 1); // since count is always > 0, we can decrement by one. non-standard encoding ftw + } + this.count = 1; + // write first value + this.w(this, v); + this.s = v; + } + } + } + + /** + * @param {UintOptRleEncoder} encoder + */ + const flushUintOptRleEncoder = encoder => { + if (encoder.count > 0) { + // flush counter, unless this is the first value (count = 0) + // case 1: just a single value. set sign to positive + // case 2: write several values. set sign to negative to indicate that there is a length coming + writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s); + if (encoder.count > 1) { + writeVarUint(encoder.encoder, encoder.count - 2); // since count is always > 1, we can decrement by one. non-standard encoding ftw + } + } + }; + + /** + * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder. + * + * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write + * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count. + * + * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3) + */ + class UintOptRleEncoder { + constructor () { + this.encoder = new Encoder(); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + } + + /** + * @param {number} v + */ + write (v) { + if (this.s === v) { + this.count++; + } else { + flushUintOptRleEncoder(this); + this.count = 1; + this.s = v; + } + } + + toUint8Array () { + flushUintOptRleEncoder(this); + return toUint8Array(this.encoder) + } + } + + /** + * @param {IntDiffOptRleEncoder} encoder + */ + const flushIntDiffOptRleEncoder = encoder => { + if (encoder.count > 0) { + // 31 bit making up the diff | wether to write the counter + const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1); + // flush counter, unless this is the first value (count = 0) + // case 1: just a single value. set first bit to positive + // case 2: write several values. set first bit to negative to indicate that there is a length coming + writeVarInt(encoder.encoder, encodedDiff); + if (encoder.count > 1) { + writeVarUint(encoder.encoder, encoder.count - 2); // since count is always > 1, we can decrement by one. non-standard encoding ftw + } + } + }; + + /** + * A combination of the IntDiffEncoder and the UintOptRleEncoder. + * + * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes + * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers! + * + * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1]) + * + * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains: + * * 1 bit that denotes whether the next value is a count (LSB) + * * 1 bit that denotes whether this value is negative (MSB - 1) + * * 1 bit that denotes whether to continue reading the variable length integer (MSB) + * + * Therefore, only five bits remain to encode diff ranges. + * + * Use this Encoder only when appropriate. In most cases, this is probably a bad idea. + */ + class IntDiffOptRleEncoder { + constructor () { + this.encoder = new Encoder(); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + this.diff = 0; + } + + /** + * @param {number} v + */ + write (v) { + if (this.diff === v - this.s) { + this.s = v; + this.count++; + } else { + flushIntDiffOptRleEncoder(this); + this.count = 1; + this.diff = v - this.s; + this.s = v; + } + } + + toUint8Array () { + flushIntDiffOptRleEncoder(this); + return toUint8Array(this.encoder) + } + } + + /** + * Optimized String Encoder. + * + * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted. + * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?). + * + * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call. + * + * The lengths are encoded using a UintOptRleEncoder. + */ + class StringEncoder { + constructor () { + /** + * @type {Array} + */ + this.sarr = []; + this.s = ''; + this.lensE = new UintOptRleEncoder(); + } + + /** + * @param {string} string + */ + write (string) { + this.s += string; + if (this.s.length > 19) { + this.sarr.push(this.s); + this.s = ''; + } + this.lensE.write(string.length); + } + + toUint8Array () { + const encoder = new Encoder(); + this.sarr.push(this.s); + this.s = ''; + writeVarString(encoder, this.sarr.join('')); + writeUint8Array(encoder, this.lensE.toUint8Array()); + return toUint8Array(encoder) + } + } + + /** + * Efficient schema-less binary decoding with support for variable length encoding. + * + * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function. + * + * Encodes numbers in little-endian order (least to most significant byte order) + * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/) + * which is also used in Protocol Buffers. + * + * ```js + * // encoding step + * const encoder = new encoding.createEncoder() + * encoding.writeVarUint(encoder, 256) + * encoding.writeVarString(encoder, 'Hello world!') + * const buf = encoding.toUint8Array(encoder) + * ``` + * + * ```js + * // decoding step + * const decoder = new decoding.createDecoder(buf) + * decoding.readVarUint(decoder) // => 256 + * decoding.readVarString(decoder) // => 'Hello world!' + * decoding.hasContent(decoder) // => false - all data is read + * ``` + * + * @module decoding + */ + + /** + * A Decoder handles the decoding of an Uint8Array. + */ + class Decoder { + /** + * @param {Uint8Array} uint8Array Binary data to decode + */ + constructor (uint8Array) { + /** + * Decoding target. + * + * @type {Uint8Array} + */ + this.arr = uint8Array; + /** + * Current decoding position. + * + * @type {number} + */ + this.pos = 0; + } + } + + /** + * @function + * @param {Uint8Array} uint8Array + * @return {Decoder} + */ + const createDecoder = uint8Array => new Decoder(uint8Array); + + /** + * @function + * @param {Decoder} decoder + * @return {boolean} + */ + const hasContent = decoder => decoder.pos !== decoder.arr.length; + + /** + * Create an Uint8Array view of the next `len` bytes and advance the position by `len`. + * + * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks. + * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array. + * + * @function + * @param {Decoder} decoder The decoder instance + * @param {number} len The length of bytes to read + * @return {Uint8Array} + */ + const readUint8Array = (decoder, len) => { + const view = createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len); + decoder.pos += len; + return view + }; + + /** + * Read variable length Uint8Array. + * + * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks. + * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array. + * + * @function + * @param {Decoder} decoder + * @return {Uint8Array} + */ + const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder)); + + /** + * Read one byte as unsigned integer. + * @function + * @param {Decoder} decoder The decoder instance + * @return {number} Unsigned 8-bit integer + */ + const readUint8 = decoder => decoder.arr[decoder.pos++]; + + /** + * Read unsigned integer (32bit) with variable length. + * 1/8th of the storage is used as encoding overhead. + * * numbers < 2^7 is stored in one bytlength + * * numbers < 2^14 is stored in two bylength + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer.length + */ + const readVarUint = decoder => { + let num = 0; + let len = 0; + while (true) { + const r = decoder.arr[decoder.pos++]; + num = num | ((r & BITS7) << len); + len += 7; + if (r < BIT8) { + return num >>> 0 // return unsigned number! + } + /* istanbul ignore if */ + if (len > 35) { + throw new Error('Integer out of range!') + } + } + }; + + /** + * Read signed integer (32bit) with variable length. + * 1/8th of the storage is used as encoding overhead. + * * numbers < 2^7 is stored in one bytlength + * * numbers < 2^14 is stored in two bylength + * @todo This should probably create the inverse ~num if unmber is negative - but this would be a breaking change. + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer.length + */ + const readVarInt = decoder => { + let r = decoder.arr[decoder.pos++]; + let num = r & BITS6; + let len = 6; + const sign = (r & BIT7) > 0 ? -1 : 1; + if ((r & BIT8) === 0) { + // don't continue reading + return sign * num + } + while (true) { + r = decoder.arr[decoder.pos++]; + num = num | ((r & BITS7) << len); + len += 7; + if (r < BIT8) { + return sign * (num >>> 0) + } + /* istanbul ignore if */ + if (len > 41) { + throw new Error('Integer out of range!') + } + } + }; + + /** + * Read string of variable length + * * varUint is used to store the length of the string + * + * Transforming utf8 to a string is pretty expensive. The code performs 10x better + * when String.fromCodePoint is fed with all characters as arguments. + * But most environments have a maximum number of arguments per functions. + * For effiency reasons we apply a maximum of 10000 characters at once. + * + * @function + * @param {Decoder} decoder + * @return {String} The read String. + */ + const readVarString = decoder => { + let remainingLen = readVarUint(decoder); + if (remainingLen === 0) { + return '' + } else { + let encodedString = String.fromCodePoint(readUint8(decoder)); // remember to decrease remainingLen + if (--remainingLen < 100) { // do not create a Uint8Array for small strings + while (remainingLen--) { + encodedString += String.fromCodePoint(readUint8(decoder)); + } + } else { + while (remainingLen > 0) { + const nextLen = remainingLen < 10000 ? remainingLen : 10000; + // this is dangerous, we create a fresh array view from the existing buffer + const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen); + decoder.pos += nextLen; + // Starting with ES5.1 we can supply a generic array-like object as arguments + encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes)); + remainingLen -= nextLen; + } + } + return decodeURIComponent(escape(encodedString)) + } + }; + + /** + * @param {Decoder} decoder + * @param {number} len + * @return {DataView} + */ + const readFromDataView = (decoder, len) => { + const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len); + decoder.pos += len; + return dv + }; + + /** + * @param {Decoder} decoder + */ + const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0); + + /** + * @param {Decoder} decoder + */ + const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0); + + /** + * @param {Decoder} decoder + */ + const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0); + + /** + * @type {Array} + */ + const readAnyLookupTable = [ + decoder => undefined, // CASE 127: undefined + decoder => null, // CASE 126: null + readVarInt, // CASE 125: integer + readFloat32, // CASE 124: float32 + readFloat64, // CASE 123: float64 + readBigInt64, // CASE 122: bigint + decoder => false, // CASE 121: boolean (false) + decoder => true, // CASE 120: boolean (true) + readVarString, // CASE 119: string + decoder => { // CASE 118: object + const len = readVarUint(decoder); + /** + * @type {Object} + */ + const obj = {}; + for (let i = 0; i < len; i++) { + const key = readVarString(decoder); + obj[key] = readAny(decoder); + } + return obj + }, + decoder => { // CASE 117: array + const len = readVarUint(decoder); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(readAny(decoder)); + } + return arr + }, + readVarUint8Array // CASE 116: Uint8Array + ]; + + /** + * @param {Decoder} decoder + */ + const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder); + + /** + * T must not be null. + * + * @template T + */ + class RleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + * @param {function(Decoder):T} reader + */ + constructor (uint8Array, reader) { + super(uint8Array); + /** + * The reader + */ + this.reader = reader; + /** + * Current state + * @type {T|null} + */ + this.s = null; + this.count = 0; + } + + read () { + if (this.count === 0) { + this.s = this.reader(this); + if (hasContent(this)) { + this.count = readVarUint(this) + 1; // see encoder implementation for the reason why this is incremented + } else { + this.count = -1; // read the current value forever + } + } + this.count--; + return /** @type {T} */ (this.s) + } + } + + class UintOptRleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + super(uint8Array); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + } + + read () { + if (this.count === 0) { + this.s = readVarInt(this); + // if the sign is negative, we read the count too, otherwise count is 1 + const isNegative = isNegativeZero(this.s); + this.count = 1; + if (isNegative) { + this.s = -this.s; + this.count = readVarUint(this) + 2; + } + } + this.count--; + return /** @type {number} */ (this.s) + } + } + + class IntDiffOptRleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + super(uint8Array); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + this.diff = 0; + } + + /** + * @return {number} + */ + read () { + if (this.count === 0) { + const diff = readVarInt(this); + // if the first bit is set, we read more data + const hasCount = diff & 1; + this.diff = diff >> 1; + this.count = 1; + if (hasCount) { + this.count = readVarUint(this) + 2; + } + } + this.s += this.diff; + this.count--; + return this.s + } + } + + class StringDecoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + this.decoder = new UintOptRleDecoder(uint8Array); + this.str = readVarString(this.decoder); + /** + * @type {number} + */ + this.spos = 0; + } + + /** + * @return {string} + */ + read () { + const end = this.spos + this.decoder.read(); + const res = this.str.slice(this.spos, end); + this.spos = end; + return res + } + } + + /** + * Utility functions to work with buffers (Uint8Array). + * + * @module buffer + */ + + /** + * @param {number} len + */ + const createUint8ArrayFromLen = len => new Uint8Array(len); + + /** + * Create Uint8Array with initial content from buffer + * + * @param {ArrayBuffer} buffer + * @param {number} byteOffset + * @param {number} length + */ + const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length); + + /** + * Copy the content of an Uint8Array view to a new ArrayBuffer. + * + * @param {Uint8Array} uint8Array + * @return {Uint8Array} + */ + const copyUint8Array = uint8Array => { + const newBuf = createUint8ArrayFromLen(uint8Array.byteLength); + newBuf.set(uint8Array); + return newBuf + }; + + /** + * Fast Pseudo Random Number Generators. + * + * Given a seed a PRNG generates a sequence of numbers that cannot be reasonably predicted. + * Two PRNGs must generate the same random sequence of numbers if given the same seed. + * + * @module prng + */ + + /** + * Description of the function + * @callback generatorNext + * @return {number} A 32bit integer + */ + + /** + * A random type generator. + * + * @typedef {Object} PRNG + * @property {generatorNext} next Generate new number + */ + + const DefaultPRNG = Xoroshiro128plus; + + /** + * Create a Xoroshiro128plus Pseudo-Random-Number-Generator. + * This is the fastest full-period generator passing BigCrush without systematic failures. + * But there are more PRNGs available in ./PRNG/. + * + * @param {number} seed A positive 32bit integer. Do not use negative numbers. + * @return {PRNG} + */ + const create$3 = seed => new DefaultPRNG(seed); + + /** + * Generates a single random bool. + * + * @param {PRNG} gen A random number generator. + * @return {Boolean} A random boolean + */ + const bool = gen => (gen.next() >= 0.5); + + /** + * Generates a random integer with 32 bit resolution. + * + * @param {PRNG} gen A random number generator. + * @param {Number} min The lower bound of the allowed return values (inclusive). + * @param {Number} max The upper bound of the allowed return values (inclusive). + * @return {Number} A random integer on [min, max] + */ + const int32 = (gen, min, max) => floor(gen.next() * (max + 1 - min) + min); + + /** + * @deprecated + * Optimized version of prng.int32. It has the same precision as prng.int32, but should be preferred when + * openaring on smaller ranges. + * + * @param {PRNG} gen A random number generator. + * @param {Number} min The lower bound of the allowed return values (inclusive). + * @param {Number} max The upper bound of the allowed return values (inclusive). The max inclusive number is `binary.BITS31-1` + * @return {Number} A random integer on [min, max] + */ + const int31 = (gen, min, max) => int32(gen, min, max); + + /** + * @param {PRNG} gen + * @return {string} A single letter (a-z) + */ + const letter = gen => fromCharCode(int31(gen, 97, 122)); + + /** + * @param {PRNG} gen + * @param {number} [minLen=0] + * @param {number} [maxLen=20] + * @return {string} A random word (0-20 characters) without spaces consisting of letters (a-z) + */ + const word = (gen, minLen = 0, maxLen = 20) => { + const len = int31(gen, minLen, maxLen); + let str = ''; + for (let i = 0; i < len; i++) { + str += letter(gen); + } + return str + }; + + /** + * Returns one element of a given array. + * + * @param {PRNG} gen A random number generator. + * @param {Array} array Non empty Array of possible values. + * @return {T} One of the values of the supplied Array. + * @template T + */ + const oneOf = (gen, array) => array[int31(gen, 0, array.length - 1)]; + + /** + * Utility helpers for generating statistics. + * + * @module statistics + */ + + /** + * @param {Array} arr Array of values + * @return {number} Returns null if the array is empty + */ + const median = arr => arr.length === 0 ? NaN : (arr.length % 2 === 1 ? arr[(arr.length - 1) / 2] : (arr[floor((arr.length - 1) / 2)] + arr[ceil((arr.length - 1) / 2)]) / 2); + + /** + * @param {Array} arr + * @return {number} + */ + const average = arr => arr.reduce(add, 0) / arr.length; + + /** + * Utility helpers to work with promises. + * + * @module promise + */ + + /** + * Checks if an object is a promise using ducktyping. + * + * Promises are often polyfilled, so it makes sense to add some additional guarantees if the user of this + * library has some insane environment where global Promise objects are overwritten. + * + * @param {any} p + * @return {boolean} + */ + const isPromise = p => p instanceof Promise || (p && p.then && p.catch && p.finally); + + /** + * Testing framework with support for generating tests. + * + * ```js + * // test.js template for creating a test executable + * import { runTests } from 'lib0/testing.js' + * import * as log from 'lib0/logging.js' + * import * as mod1 from './mod1.test.js' + * import * as mod2 from './mod2.test.js' + + * import { isBrowser, isNode } from 'lib0/environment.js' + * + * if (isBrowser) { + * // optional: if this is ran in the browser, attach a virtual console to the dom + * log.createVConsole(document.body) + * } + * + * runTests({ + * mod1, + * mod2, + * }).then(success => { + * if (isNode) { + * process.exit(success ? 0 : 1) + * } + * }) + * ``` + * + * ```js + * // mod1.test.js + * /** + * * runTests automatically tests all exported functions that start with "test". + * * The name of the function should be in camelCase and is used for the logging output. + * * + * * @param {t.TestCase} tc + * *\/ + * export const testMyFirstTest = tc => { + * t.compare({ a: 4 }, { a: 4 }, 'objects are equal') + * } + * ``` + * + * Now you can simply run `node test.js` to run your test or run test.js in the browser. + * + * @module testing + */ + + const extensive = hasConf('extensive'); + + /* istanbul ignore next */ + const envSeed = hasParam('--seed') ? Number.parseInt(getParam('--seed', '0')) : null; + + class TestCase { + /** + * @param {string} moduleName + * @param {string} testName + */ + constructor (moduleName, testName) { + /** + * @type {string} + */ + this.moduleName = moduleName; + /** + * @type {string} + */ + this.testName = testName; + this._seed = null; + this._prng = null; + } + + resetSeed () { + this._seed = null; + this._prng = null; + } + + /** + * @type {number} + */ + /* istanbul ignore next */ + get seed () { + /* istanbul ignore else */ + if (this._seed === null) { + /* istanbul ignore next */ + this._seed = envSeed === null ? uint32() : envSeed; + } + return this._seed + } + + /** + * A PRNG for this test case. Use only this PRNG for randomness to make the test case reproducible. + * + * @type {prng.PRNG} + */ + get prng () { + /* istanbul ignore else */ + if (this._prng === null) { + this._prng = create$3(this.seed); + } + return this._prng + } + } + + const repititionTime = Number(getParam('--repitition-time', '50')); + /* istanbul ignore next */ + const testFilter = hasParam('--filter') ? getParam('--filter', '') : null; + + /* istanbul ignore next */ + const testFilterRegExp = testFilter !== null ? new RegExp(testFilter) : new RegExp('.*'); + + const repeatTestRegex = /^(repeat|repeating)\s/; + + /** + * @param {string} moduleName + * @param {string} name + * @param {function(TestCase):void|Promise} f + * @param {number} i + * @param {number} numberOfTests + */ + const run = async (moduleName, name, f, i, numberOfTests) => { + const uncamelized = fromCamelCase(name.slice(4), ' '); + const filtered = !testFilterRegExp.test(`[${i + 1}/${numberOfTests}] ${moduleName}: ${uncamelized}`); + /* istanbul ignore if */ + if (filtered) { + return true + } + const tc = new TestCase(moduleName, name); + const repeat = repeatTestRegex.test(uncamelized); + const groupArgs = [GREY, `[${i + 1}/${numberOfTests}] `, PURPLE, `${moduleName}: `, BLUE, uncamelized]; + /* istanbul ignore next */ + if (testFilter === null) { + groupCollapsed(...groupArgs); + } else { + group(...groupArgs); + } + const times = []; + const start = performance$1.now(); + let lastTime = start; + let err = null; + performance$1.mark(`${name}-start`); + do { + try { + const p = f(tc); + if (isPromise(p)) { + await p; + } + } catch (_err) { + err = _err; + } + const currTime = performance$1.now(); + times.push(currTime - lastTime); + lastTime = currTime; + if (repeat && err === null && (lastTime - start) < repititionTime) { + tc.resetSeed(); + } else { + break + } + } while (err === null && (lastTime - start) < repititionTime) + performance$1.mark(`${name}-end`); + /* istanbul ignore if */ + if (err !== null && err.constructor !== SkipError) { + printError(err); + } + performance$1.measure(name, `${name}-start`, `${name}-end`); + groupEnd(); + const duration = lastTime - start; + let success = true; + times.sort((a, b) => a - b); + /* istanbul ignore next */ + const againMessage = isBrowser + ? ` - ${window.location.href}?filter=\\[${i + 1}/${tc._seed === null ? '' : `&seed=${tc._seed}`}` + : `\nrepeat: npm run test -- --filter "\\[${i + 1}/" ${tc._seed === null ? '' : `--seed ${tc._seed}`}`; + const timeInfo = (repeat && err === null) + ? ` - ${times.length} repititions in ${humanizeDuration(duration)} (best: ${humanizeDuration(times[0])}, worst: ${humanizeDuration(last(times))}, median: ${humanizeDuration(median(times))}, average: ${humanizeDuration(average(times))})` + : ` in ${humanizeDuration(duration)}`; + if (err !== null) { + /* istanbul ignore else */ + if (err.constructor === SkipError) { + print(GREY, BOLD, 'Skipped: ', UNBOLD, uncamelized); + } else { + success = false; + print(RED, BOLD, 'Failure: ', UNBOLD, UNCOLOR, uncamelized, GREY, timeInfo, againMessage); + } + } else { + print(GREEN, BOLD, 'Success: ', UNBOLD, UNCOLOR, uncamelized, GREY, timeInfo, againMessage); + } + return success + }; + + /** + * @param {string} a + * @param {string} b + * @param {string} [m] + * @throws {TestError} Throws if tests fails + */ + const compareStrings = (a, b, m = 'Strings match') => { + if (a !== b) { + const diff = simpleDiff(a, b); + print(GREY, a.slice(0, diff.index), RED, a.slice(diff.index, diff.remove), GREEN, diff.insert, GREY, a.slice(diff.index + diff.remove)); + fail(m); + } + }; + + /** + * @param {any} constructor + * @param {any} a + * @param {any} b + * @param {string} path + * @throws {TestError} + */ + const compareValues = (constructor, a, b, path) => { + if (a !== b) { + fail(`Values ${stringify(a)} and ${stringify(b)} don't match (${path})`); + } + return true + }; + + /** + * @param {string?} message + * @param {string} reason + * @param {string} path + * @throws {TestError} + */ + const _failMessage = (message, reason, path) => fail( + message === null + ? `${reason} ${path}` + : `${message} (${reason}) ${path}` + ); + + /** + * @param {any} a + * @param {any} b + * @param {string} path + * @param {string?} message + * @param {function(any,any,any,string,any):boolean} customCompare + */ + const _compare = (a, b, path, message, customCompare) => { + // we don't use assert here because we want to test all branches (istanbul errors if one branch is not tested) + if (a == null || b == null) { + return compareValues(null, a, b, path) + } + if (a.constructor !== b.constructor) { + _failMessage(message, 'Constructors don\'t match', path); + } + let success = true; + switch (a.constructor) { + case ArrayBuffer: + a = new Uint8Array(a); + b = new Uint8Array(b); + // eslint-disable-next-line no-fallthrough + case Uint8Array: { + if (a.byteLength !== b.byteLength) { + _failMessage(message, 'ArrayBuffer lengths match', path); + } + for (let i = 0; success && i < a.length; i++) { + success = success && a[i] === b[i]; + } + break + } + case Set: { + if (a.size !== b.size) { + _failMessage(message, 'Sets have different number of attributes', path); + } + // @ts-ignore + a.forEach(value => { + if (!b.has(value)) { + _failMessage(message, `b.${path} does have ${value}`, path); + } + }); + break + } + case Map: { + if (a.size !== b.size) { + _failMessage(message, 'Maps have different number of attributes', path); + } + // @ts-ignore + a.forEach((value, key) => { + if (!b.has(key)) { + _failMessage(message, `Property ${path}["${key}"] does not exist on second argument`, path); + } + _compare(value, b.get(key), `${path}["${key}"]`, message, customCompare); + }); + break + } + case Object: + if (length(a) !== length(b)) { + _failMessage(message, 'Objects have a different number of attributes', path); + } + forEach$1(a, (value, key) => { + if (!hasProperty(b, key)) { + _failMessage(message, `Property ${path} does not exist on second argument`, path); + } + _compare(value, b[key], `${path}["${key}"]`, message, customCompare); + }); + break + case Array: + if (a.length !== b.length) { + _failMessage(message, 'Arrays have a different number of attributes', path); + } + // @ts-ignore + a.forEach((value, i) => _compare(value, b[i], `${path}[${i}]`, message, customCompare)); + break + /* istanbul ignore next */ + default: + if (!customCompare(a.constructor, a, b, path, compareValues)) { + _failMessage(message, `Values ${stringify(a)} and ${stringify(b)} don't match`, path); + } + } + assert(success, message); + return true + }; + + /** + * @template T + * @param {T} a + * @param {T} b + * @param {string?} [message] + * @param {function(any,T,T,string,any):boolean} [customCompare] + */ + const compare = (a, b, message = null, customCompare = compareValues) => _compare(a, b, 'obj', message, customCompare); + + /* istanbul ignore next */ + /** + * @param {boolean} condition + * @param {string?} [message] + * @throws {TestError} + */ + const assert = (condition, message = null) => condition || fail(`Assertion failed${message !== null ? `: ${message}` : ''}`); + + /** + * @param {Object>>} tests + */ + const runTests = async tests => { + const numberOfTests = map$1(tests, mod => map$1(mod, f => /* istanbul ignore next */ f ? 1 : 0).reduce(add, 0)).reduce(add, 0); + let successfulTests = 0; + let testnumber = 0; + const start = performance$1.now(); + for (const modName in tests) { + const mod = tests[modName]; + for (const fname in mod) { + const f = mod[fname]; + /* istanbul ignore else */ + if (f) { + const repeatEachTest = 1; + let success = true; + for (let i = 0; success && i < repeatEachTest; i++) { + success = await run(modName, fname, f, testnumber, numberOfTests); + } + testnumber++; + /* istanbul ignore else */ + if (success) { + successfulTests++; + } + } + } + } + const end = performance$1.now(); + print(''); + const success = successfulTests === numberOfTests; + /* istanbul ignore next */ + if (success) { + /* istanbul ignore next */ + print(GREEN, BOLD, 'All tests successful!', GREY, UNBOLD, ` in ${humanizeDuration(end - start)}`); + /* istanbul ignore next */ + printImgBase64(nyanCatImage, 50); + } else { + const failedTests = numberOfTests - successfulTests; + print(RED, BOLD, `> ${failedTests} test${failedTests > 1 ? 's' : ''} failed`); + } + return success + }; + + class TestError extends Error {} + + /** + * @param {string} reason + * @throws {TestError} + */ + const fail = reason => { + print(RED, BOLD, 'X ', UNBOLD, reason); + throw new TestError('Test Failed') + }; + + class SkipError extends Error {} + + // eslint-disable-next-line + const nyanCatImage = 'R0lGODlhjABMAPcAAMiSE0xMTEzMzUKJzjQ0NFsoKPc7//FM/9mH/z9x0HIiIoKCgmBHN+frGSkZLdDQ0LCwsDk71g0KCUzDdrQQEOFz/8yYdelmBdTiHFxcXDU2erR/mLrTHCgoKK5szBQUFNgSCTk6ymfpCB9VZS2Bl+cGBt2N8kWm0uDcGXhZRUvGq94NCFPhDiwsLGVlZTgqIPMDA1g3aEzS5D6xAURERDtG9JmBjJsZGWs2AD1W6Hp6eswyDeJ4CFNTU1LcEoJRmTMzSd14CTg5ser2GmDzBd17/xkZGUzMvoSMDiEhIfKruCwNAJaWlvRzA8kNDXDrCfi0pe1U/+GS6SZrAB4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DBKGArbhgG3wQwEL6AcEtmGBBnQgBMPgQAUusIEInKADHwjBCkIQgwfUoAQ7iEALMtAPa5iEfbTQIT0YgTxGKJAMvfSFDhDoHgT4AgE6hBA/+GEQ2AgiNvy84EMfekGI2BhEEf1QAyQuEYhCJGIRjyhEJRaxiUJ8IhKlaEQkWtGHWAyiFqO4RC/UIIUl2s4H9PAlw+lrBPHQQ4UCtDU7vJEgbsijHvfIxz768Y+ADKQgB0lIQGJjDdvZjkBstJ3EHCSRRLLRHQnCiEoSJAKVrOQcCCKGTDIiApTMpBgIMgdPbnIgncxkQTw5yoGUMpOnFEgqLRnKSrZSIK/U5Ag+kLjEDaSXCQGmQHzJpWIasyV3OaYyl8nMZi7nLsl0ZkagKc1qWvOa2JxLNLPJzW6+ZZvevAhdwrkStJCTI2gZ5zknos51shOc7oynPOdJz3ra857hDAgAOw=='; + + /** + * Utility module to work with sets. + * + * @module set + */ + + const create$4 = () => new Set(); + + /** + * Observable class prototype. + * + * @module observable + */ + + /** + * Handles named events. + * + * @template N + */ + class Observable { + constructor () { + /** + * Some desc. + * @type {Map} + */ + this._observers = create(); + } + + /** + * @param {N} name + * @param {function} f + */ + on (name, f) { + setIfUndefined(this._observers, name, create$4).add(f); + } + + /** + * @param {N} name + * @param {function} f + */ + once (name, f) { + /** + * @param {...any} args + */ + const _f = (...args) => { + this.off(name, _f); + f(...args); + }; + this.on(name, _f); + } + + /** + * @param {N} name + * @param {function} f + */ + off (name, f) { + const observers = this._observers.get(name); + if (observers !== undefined) { + observers.delete(f); + if (observers.size === 0) { + this._observers.delete(name); + } + } + } + + /** + * Emit a named event. All registered event listeners that listen to the + * specified name will receive the event. + * + * @todo This should catch exceptions + * + * @param {N} name The event name. + * @param {Array} args The arguments that are applied to the event listener. + */ + emit (name, args) { + // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called. + return from((this._observers.get(name) || create()).values()).forEach(f => f(...args)) + } + + destroy () { + this._observers = create(); + } + } + + /** + * This is an abstract interface that all Connectors should implement to keep them interchangeable. + * + * @note This interface is experimental and it is not advised to actually inherit this class. + * It just serves as typing information. + * + * @extends {Observable} + */ + class AbstractConnector extends Observable { + /** + * @param {Doc} ydoc + * @param {any} awareness + */ + constructor (ydoc, awareness) { + super(); + this.doc = ydoc; + this.awareness = awareness; + } + } + + class DeleteItem { + /** + * @param {number} clock + * @param {number} len + */ + constructor (clock, len) { + /** + * @type {number} + */ + this.clock = clock; + /** + * @type {number} + */ + this.len = len; + } + } + + /** + * We no longer maintain a DeleteStore. DeleteSet is a temporary object that is created when needed. + * - When created in a transaction, it must only be accessed after sorting, and merging + * - This DeleteSet is send to other clients + * - We do not create a DeleteSet when we send a sync message. The DeleteSet message is created directly from StructStore + * - We read a DeleteSet as part of a sync/update message. In this case the DeleteSet is already sorted and merged. + */ + class DeleteSet { + constructor () { + /** + * @type {Map>} + */ + this.clients = new Map(); + } + } + + /** + * Iterate over all structs that the DeleteSet gc's. + * + * @param {Transaction} transaction + * @param {DeleteSet} ds + * @param {function(GC|Item):void} f + * + * @function + */ + const iterateDeletedStructs = (transaction, ds, f) => + ds.clients.forEach((deletes, clientid) => { + const structs = /** @type {Array} */ (transaction.doc.store.clients.get(clientid)); + for (let i = 0; i < deletes.length; i++) { + const del = deletes[i]; + iterateStructs(transaction, structs, del.clock, del.len, f); + } + }); + + /** + * @param {Array} dis + * @param {number} clock + * @return {number|null} + * + * @private + * @function + */ + const findIndexDS = (dis, clock) => { + let left = 0; + let right = dis.length - 1; + while (left <= right) { + const midindex = floor((left + right) / 2); + const mid = dis[midindex]; + const midclock = mid.clock; + if (midclock <= clock) { + if (clock < midclock + mid.len) { + return midindex + } + left = midindex + 1; + } else { + right = midindex - 1; + } + } + return null + }; + + /** + * @param {DeleteSet} ds + * @param {ID} id + * @return {boolean} + * + * @private + * @function + */ + const isDeleted = (ds, id) => { + const dis = ds.clients.get(id.client); + return dis !== undefined && findIndexDS(dis, id.clock) !== null + }; + + /** + * @param {DeleteSet} ds + * + * @private + * @function + */ + const sortAndMergeDeleteSet = ds => { + ds.clients.forEach(dels => { + dels.sort((a, b) => a.clock - b.clock); + // merge items without filtering or splicing the array + // i is the current pointer + // j refers to the current insert position for the pointed item + // try to merge dels[i] into dels[j-1] or set dels[j]=dels[i] + let i, j; + for (i = 1, j = 1; i < dels.length; i++) { + const left = dels[j - 1]; + const right = dels[i]; + if (left.clock + left.len === right.clock) { + left.len += right.len; + } else { + if (j < i) { + dels[j] = right; + } + j++; + } + } + dels.length = j; + }); + }; + + /** + * @param {Array} dss + * @return {DeleteSet} A fresh DeleteSet + */ + const mergeDeleteSets = dss => { + const merged = new DeleteSet(); + for (let dssI = 0; dssI < dss.length; dssI++) { + dss[dssI].clients.forEach((delsLeft, client) => { + if (!merged.clients.has(client)) { + // Write all missing keys from current ds and all following. + // If merged already contains `client` current ds has already been added. + /** + * @type {Array} + */ + const dels = delsLeft.slice(); + for (let i = dssI + 1; i < dss.length; i++) { + appendTo(dels, dss[i].clients.get(client) || []); + } + merged.clients.set(client, dels); + } + }); + } + sortAndMergeDeleteSet(merged); + return merged + }; + + /** + * @param {DeleteSet} ds + * @param {number} client + * @param {number} clock + * @param {number} length + * + * @private + * @function + */ + const addToDeleteSet = (ds, client, clock, length) => { + setIfUndefined(ds.clients, client, () => []).push(new DeleteItem(clock, length)); + }; + + const createDeleteSet = () => new DeleteSet(); + + /** + * @param {StructStore} ss + * @return {DeleteSet} Merged and sorted DeleteSet + * + * @private + * @function + */ + const createDeleteSetFromStructStore = ss => { + const ds = createDeleteSet(); + ss.clients.forEach((structs, client) => { + /** + * @type {Array} + */ + const dsitems = []; + for (let i = 0; i < structs.length; i++) { + const struct = structs[i]; + if (struct.deleted) { + const clock = struct.id.clock; + let len = struct.length; + if (i + 1 < structs.length) { + for (let next = structs[i + 1]; i + 1 < structs.length && next.id.clock === clock + len && next.deleted; next = structs[++i + 1]) { + len += next.length; + } + } + dsitems.push(new DeleteItem(clock, len)); + } + } + if (dsitems.length > 0) { + ds.clients.set(client, dsitems); + } + }); + return ds + }; + + /** + * @param {AbstractDSEncoder} encoder + * @param {DeleteSet} ds + * + * @private + * @function + */ + const writeDeleteSet = (encoder, ds) => { + writeVarUint(encoder.restEncoder, ds.clients.size); + ds.clients.forEach((dsitems, client) => { + encoder.resetDsCurVal(); + writeVarUint(encoder.restEncoder, client); + const len = dsitems.length; + writeVarUint(encoder.restEncoder, len); + for (let i = 0; i < len; i++) { + const item = dsitems[i]; + encoder.writeDsClock(item.clock); + encoder.writeDsLen(item.len); + } + }); + }; + + /** + * @param {AbstractDSDecoder} decoder + * @return {DeleteSet} + * + * @private + * @function + */ + const readDeleteSet = decoder => { + const ds = new DeleteSet(); + const numClients = readVarUint(decoder.restDecoder); + for (let i = 0; i < numClients; i++) { + decoder.resetDsCurVal(); + const client = readVarUint(decoder.restDecoder); + const numberOfDeletes = readVarUint(decoder.restDecoder); + if (numberOfDeletes > 0) { + const dsField = setIfUndefined(ds.clients, client, () => []); + for (let i = 0; i < numberOfDeletes; i++) { + dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen())); + } + } + } + return ds + }; + + /** + * @todo YDecoder also contains references to String and other Decoders. Would make sense to exchange YDecoder.toUint8Array for YDecoder.DsToUint8Array().. + */ + + /** + * @param {AbstractDSDecoder} decoder + * @param {Transaction} transaction + * @param {StructStore} store + * + * @private + * @function + */ + const readAndApplyDeleteSet = (decoder, transaction, store) => { + const unappliedDS = new DeleteSet(); + const numClients = readVarUint(decoder.restDecoder); + for (let i = 0; i < numClients; i++) { + decoder.resetDsCurVal(); + const client = readVarUint(decoder.restDecoder); + const numberOfDeletes = readVarUint(decoder.restDecoder); + const structs = store.clients.get(client) || []; + const state = getState(store, client); + for (let i = 0; i < numberOfDeletes; i++) { + const clock = decoder.readDsClock(); + const clockEnd = clock + decoder.readDsLen(); + if (clock < state) { + if (state < clockEnd) { + addToDeleteSet(unappliedDS, client, state, clockEnd - state); + } + let index = findIndexSS(structs, clock); + /** + * We can ignore the case of GC and Delete structs, because we are going to skip them + * @type {Item} + */ + // @ts-ignore + let struct = structs[index]; + // split the first item if necessary + if (!struct.deleted && struct.id.clock < clock) { + structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); + index++; // increase we now want to use the next struct + } + while (index < structs.length) { + // @ts-ignore + struct = structs[index++]; + if (struct.id.clock < clockEnd) { + if (!struct.deleted) { + if (clockEnd < struct.id.clock + struct.length) { + structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock)); + } + struct.delete(transaction); + } + } else { + break + } + } + } else { + addToDeleteSet(unappliedDS, client, clock, clockEnd - clock); + } + } + } + if (unappliedDS.clients.size > 0) { + // TODO: no need for encoding+decoding ds anymore + const unappliedDSEncoder = new DSEncoderV2(); + writeDeleteSet(unappliedDSEncoder, unappliedDS); + store.pendingDeleteReaders.push(new DSDecoderV2(createDecoder((unappliedDSEncoder.toUint8Array())))); + } + }; + + /** + * @module Y + */ + + const generateNewClientId = uint32; + + /** + * @typedef {Object} DocOpts + * @property {boolean} [DocOpts.gc=true] Disable garbage collection (default: gc=true) + * @property {function(Item):boolean} [DocOpts.gcFilter] Will be called before an Item is garbage collected. Return false to keep the Item. + * @property {string} [DocOpts.guid] Define a globally unique identifier for this document + * @property {any} [DocOpts.meta] Any kind of meta information you want to associate with this document. If this is a subdocument, remote peers will store the meta information as well. + * @property {boolean} [DocOpts.autoLoad] If a subdocument, automatically load document. If this is a subdocument, remote peers will load the document as well automatically. + */ + + /** + * A Yjs instance handles the state of shared data. + * @extends Observable + */ + class Doc extends Observable { + /** + * @param {DocOpts} [opts] configuration + */ + constructor ({ guid = uuidv4(), gc = true, gcFilter = () => true, meta = null, autoLoad = false } = {}) { + super(); + this.gc = gc; + this.gcFilter = gcFilter; + this.clientID = generateNewClientId(); + this.guid = guid; + /** + * @type {Map>} + */ + this.share = new Map(); + this.store = new StructStore(); + /** + * @type {Transaction | null} + */ + this._transaction = null; + /** + * @type {Array} + */ + this._transactionCleanups = []; + /** + * @type {Set} + */ + this.subdocs = new Set(); + /** + * If this document is a subdocument - a document integrated into another document - then _item is defined. + * @type {Item?} + */ + this._item = null; + this.shouldLoad = autoLoad; + this.autoLoad = autoLoad; + this.meta = meta; + } + + /** + * Notify the parent document that you request to load data into this subdocument (if it is a subdocument). + * + * `load()` might be used in the future to request any provider to load the most current data. + * + * It is safe to call `load()` multiple times. + */ + load () { + const item = this._item; + if (item !== null && !this.shouldLoad) { + transact(/** @type {any} */ (item.parent).doc, transaction => { + transaction.subdocsLoaded.add(this); + }, null, true); + } + this.shouldLoad = true; + } + + getSubdocs () { + return this.subdocs + } + + getSubdocGuids () { + return new Set(Array.from(this.subdocs).map(doc => doc.guid)) + } + + /** + * Changes that happen inside of a transaction are bundled. This means that + * the observer fires _after_ the transaction is finished and that all changes + * that happened inside of the transaction are sent as one message to the + * other peers. + * + * @param {function(Transaction):void} f The function that should be executed as a transaction + * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin + * + * @public + */ + transact (f, origin = null) { + transact(this, f, origin); + } + + /** + * Define a shared data type. + * + * Multiple calls of `y.get(name, TypeConstructor)` yield the same result + * and do not overwrite each other. I.e. + * `y.define(name, Y.Array) === y.define(name, Y.Array)` + * + * After this method is called, the type is also available on `y.share.get(name)`. + * + * *Best Practices:* + * Define all types right after the Yjs instance is created and store them in a separate object. + * Also use the typed methods `getText(name)`, `getArray(name)`, .. + * + * @example + * const y = new Y(..) + * const appState = { + * document: y.getText('document') + * comments: y.getArray('comments') + * } + * + * @param {string} name + * @param {Function} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ... + * @return {AbstractType} The created type. Constructed with TypeConstructor + * + * @public + */ + get (name, TypeConstructor = AbstractType) { + const type = setIfUndefined(this.share, name, () => { + // @ts-ignore + const t = new TypeConstructor(); + t._integrate(this, null); + return t + }); + const Constr = type.constructor; + if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) { + if (Constr === AbstractType) { + // @ts-ignore + const t = new TypeConstructor(); + t._map = type._map; + type._map.forEach(/** @param {Item?} n */ n => { + for (; n !== null; n = n.left) { + // @ts-ignore + n.parent = t; + } + }); + t._start = type._start; + for (let n = t._start; n !== null; n = n.right) { + n.parent = t; + } + t._length = type._length; + this.share.set(name, t); + t._integrate(this, null); + return t + } else { + throw new Error(`Type with the name ${name} has already been defined with a different constructor`) + } + } + return type + } + + /** + * @template T + * @param {string} [name] + * @return {YArray} + * + * @public + */ + getArray (name = '') { + // @ts-ignore + return this.get(name, YArray) + } + + /** + * @param {string} [name] + * @return {YText} + * + * @public + */ + getText (name = '') { + // @ts-ignore + return this.get(name, YText) + } + + /** + * @param {string} [name] + * @return {YMap} + * + * @public + */ + getMap (name = '') { + // @ts-ignore + return this.get(name, YMap) + } + + /** + * @param {string} [name] + * @return {YXmlFragment} + * + * @public + */ + getXmlFragment (name = '') { + // @ts-ignore + return this.get(name, YXmlFragment) + } + + /** + * Converts the entire document into a js object, recursively traversing each yjs type + * + * @return {Object} + */ + toJSON () { + /** + * @type {Object} + */ + const doc = {}; + + this.share.forEach((value, key) => { + doc[key] = value.toJSON(); + }); + + return doc + } + + /** + * Emit `destroy` event and unregister all event handlers. + */ + destroy () { + from(this.subdocs).forEach(subdoc => subdoc.destroy()); + const item = this._item; + if (item !== null) { + this._item = null; + const content = /** @type {ContentDoc} */ (item.content); + if (item.deleted) { + // @ts-ignore + content.doc = null; + } else { + content.doc = new Doc({ guid: this.guid, ...content.opts }); + content.doc._item = item; + } + transact(/** @type {any} */ (item).parent.doc, transaction => { + if (!item.deleted) { + transaction.subdocsAdded.add(content.doc); + } + transaction.subdocsRemoved.add(this); + }, null, true); + } + this.emit('destroyed', [true]); + super.destroy(); + } + + /** + * @param {string} eventName + * @param {function(...any):any} f + */ + on (eventName, f) { + super.on(eventName, f); + } + + /** + * @param {string} eventName + * @param {function} f + */ + off (eventName, f) { + super.off(eventName, f); + } + } + + /** + * Error helpers. + * + * @module error + */ + + /** + * @param {string} s + * @return {Error} + */ + /* istanbul ignore next */ + const create$5 = s => new Error(s); + + /** + * @throws {Error} + * @return {never} + */ + /* istanbul ignore next */ + const methodUnimplemented = () => { + throw create$5('Method unimplemented') + }; + + /** + * @throws {Error} + * @return {never} + */ + /* istanbul ignore next */ + const unexpectedCase = () => { + throw create$5('Unexpected case') + }; + + class AbstractDSDecoder { + /** + * @param {decoding.Decoder} decoder + */ + constructor (decoder) { + this.restDecoder = decoder; + methodUnimplemented(); + } + + resetDsCurVal () { } + + /** + * @return {number} + */ + readDsClock () { + methodUnimplemented(); + } + + /** + * @return {number} + */ + readDsLen () { + methodUnimplemented(); + } + } + + class AbstractUpdateDecoder extends AbstractDSDecoder { + /** + * @return {ID} + */ + readLeftID () { + methodUnimplemented(); + } + + /** + * @return {ID} + */ + readRightID () { + methodUnimplemented(); + } + + /** + * Read the next client id. + * Use this in favor of readID whenever possible to reduce the number of objects created. + * + * @return {number} + */ + readClient () { + methodUnimplemented(); + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readInfo () { + methodUnimplemented(); + } + + /** + * @return {string} + */ + readString () { + methodUnimplemented(); + } + + /** + * @return {boolean} isKey + */ + readParentInfo () { + methodUnimplemented(); + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readTypeRef () { + methodUnimplemented(); + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @return {number} len + */ + readLen () { + methodUnimplemented(); + } + + /** + * @return {any} + */ + readAny () { + methodUnimplemented(); + } + + /** + * @return {Uint8Array} + */ + readBuf () { + methodUnimplemented(); + } + + /** + * Legacy implementation uses JSON parse. We use any-decoding in v2. + * + * @return {any} + */ + readJSON () { + methodUnimplemented(); + } + + /** + * @return {string} + */ + readKey () { + methodUnimplemented(); + } + } + + class DSDecoderV1 { + /** + * @param {decoding.Decoder} decoder + */ + constructor (decoder) { + this.restDecoder = decoder; + } + + resetDsCurVal () { + // nop + } + + /** + * @return {number} + */ + readDsClock () { + return readVarUint(this.restDecoder) + } + + /** + * @return {number} + */ + readDsLen () { + return readVarUint(this.restDecoder) + } + } + + class UpdateDecoderV1 extends DSDecoderV1 { + /** + * @return {ID} + */ + readLeftID () { + return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)) + } + + /** + * @return {ID} + */ + readRightID () { + return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)) + } + + /** + * Read the next client id. + * Use this in favor of readID whenever possible to reduce the number of objects created. + */ + readClient () { + return readVarUint(this.restDecoder) + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readInfo () { + return readUint8(this.restDecoder) + } + + /** + * @return {string} + */ + readString () { + return readVarString(this.restDecoder) + } + + /** + * @return {boolean} isKey + */ + readParentInfo () { + return readVarUint(this.restDecoder) === 1 + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readTypeRef () { + return readVarUint(this.restDecoder) + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @return {number} len + */ + readLen () { + return readVarUint(this.restDecoder) + } + + /** + * @return {any} + */ + readAny () { + return readAny(this.restDecoder) + } + + /** + * @return {Uint8Array} + */ + readBuf () { + return copyUint8Array(readVarUint8Array(this.restDecoder)) + } + + /** + * Legacy implementation uses JSON parse. We use any-decoding in v2. + * + * @return {any} + */ + readJSON () { + return JSON.parse(readVarString(this.restDecoder)) + } + + /** + * @return {string} + */ + readKey () { + return readVarString(this.restDecoder) + } + } + + class DSDecoderV2 { + /** + * @param {decoding.Decoder} decoder + */ + constructor (decoder) { + this.dsCurrVal = 0; + this.restDecoder = decoder; + } + + resetDsCurVal () { + this.dsCurrVal = 0; + } + + readDsClock () { + this.dsCurrVal += readVarUint(this.restDecoder); + return this.dsCurrVal + } + + readDsLen () { + const diff = readVarUint(this.restDecoder) + 1; + this.dsCurrVal += diff; + return diff + } + } + + class UpdateDecoderV2 extends DSDecoderV2 { + /** + * @param {decoding.Decoder} decoder + */ + constructor (decoder) { + super(decoder); + /** + * List of cached keys. If the keys[id] does not exist, we read a new key + * from stringEncoder and push it to keys. + * + * @type {Array} + */ + this.keys = []; + readUint8(decoder); // read feature flag - currently unused + this.keyClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); + this.clientDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); + this.leftClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); + this.rightClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); + this.infoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); + this.stringDecoder = new StringDecoder(readVarUint8Array(decoder)); + this.parentInfoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); + this.typeRefDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); + this.lenDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); + } + + /** + * @return {ID} + */ + readLeftID () { + return new ID(this.clientDecoder.read(), this.leftClockDecoder.read()) + } + + /** + * @return {ID} + */ + readRightID () { + return new ID(this.clientDecoder.read(), this.rightClockDecoder.read()) + } + + /** + * Read the next client id. + * Use this in favor of readID whenever possible to reduce the number of objects created. + */ + readClient () { + return this.clientDecoder.read() + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readInfo () { + return /** @type {number} */ (this.infoDecoder.read()) + } + + /** + * @return {string} + */ + readString () { + return this.stringDecoder.read() + } + + /** + * @return {boolean} + */ + readParentInfo () { + return this.parentInfoDecoder.read() === 1 + } + + /** + * @return {number} An unsigned 8-bit integer + */ + readTypeRef () { + return this.typeRefDecoder.read() + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @return {number} + */ + readLen () { + return this.lenDecoder.read() + } + + /** + * @return {any} + */ + readAny () { + return readAny(this.restDecoder) + } + + /** + * @return {Uint8Array} + */ + readBuf () { + return readVarUint8Array(this.restDecoder) + } + + /** + * This is mainly here for legacy purposes. + * + * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder. + * + * @return {any} + */ + readJSON () { + return readAny(this.restDecoder) + } + + /** + * @return {string} + */ + readKey () { + const keyClock = this.keyClockDecoder.read(); + if (keyClock < this.keys.length) { + return this.keys[keyClock] + } else { + const key = this.stringDecoder.read(); + this.keys.push(key); + return key + } + } + } + + class AbstractDSEncoder { + constructor () { + this.restEncoder = createEncoder(); + } + + /** + * @return {Uint8Array} + */ + toUint8Array () { + methodUnimplemented(); + } + + /** + * Resets the ds value to 0. + * The v2 encoder uses this information to reset the initial diff value. + */ + resetDsCurVal () { } + + /** + * @param {number} clock + */ + writeDsClock (clock) { } + + /** + * @param {number} len + */ + writeDsLen (len) { } + } + + class AbstractUpdateEncoder extends AbstractDSEncoder { + /** + * @return {Uint8Array} + */ + toUint8Array () { + methodUnimplemented(); + } + + /** + * @param {ID} id + */ + writeLeftID (id) { } + + /** + * @param {ID} id + */ + writeRightID (id) { } + + /** + * Use writeClient and writeClock instead of writeID if possible. + * @param {number} client + */ + writeClient (client) { } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeInfo (info) { } + + /** + * @param {string} s + */ + writeString (s) { } + + /** + * @param {boolean} isYKey + */ + writeParentInfo (isYKey) { } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeTypeRef (info) { } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @param {number} len + */ + writeLen (len) { } + + /** + * @param {any} any + */ + writeAny (any) { } + + /** + * @param {Uint8Array} buf + */ + writeBuf (buf) { } + + /** + * @param {any} embed + */ + writeJSON (embed) { } + + /** + * @param {string} key + */ + writeKey (key) { } + } + + class DSEncoderV1 { + constructor () { + this.restEncoder = new Encoder(); + } + + toUint8Array () { + return toUint8Array(this.restEncoder) + } + + resetDsCurVal () { + // nop + } + + /** + * @param {number} clock + */ + writeDsClock (clock) { + writeVarUint(this.restEncoder, clock); + } + + /** + * @param {number} len + */ + writeDsLen (len) { + writeVarUint(this.restEncoder, len); + } + } + + class UpdateEncoderV1 extends DSEncoderV1 { + /** + * @param {ID} id + */ + writeLeftID (id) { + writeVarUint(this.restEncoder, id.client); + writeVarUint(this.restEncoder, id.clock); + } + + /** + * @param {ID} id + */ + writeRightID (id) { + writeVarUint(this.restEncoder, id.client); + writeVarUint(this.restEncoder, id.clock); + } + + /** + * Use writeClient and writeClock instead of writeID if possible. + * @param {number} client + */ + writeClient (client) { + writeVarUint(this.restEncoder, client); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeInfo (info) { + writeUint8(this.restEncoder, info); + } + + /** + * @param {string} s + */ + writeString (s) { + writeVarString(this.restEncoder, s); + } + + /** + * @param {boolean} isYKey + */ + writeParentInfo (isYKey) { + writeVarUint(this.restEncoder, isYKey ? 1 : 0); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeTypeRef (info) { + writeVarUint(this.restEncoder, info); + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @param {number} len + */ + writeLen (len) { + writeVarUint(this.restEncoder, len); + } + + /** + * @param {any} any + */ + writeAny (any) { + writeAny(this.restEncoder, any); + } + + /** + * @param {Uint8Array} buf + */ + writeBuf (buf) { + writeVarUint8Array(this.restEncoder, buf); + } + + /** + * @param {any} embed + */ + writeJSON (embed) { + writeVarString(this.restEncoder, JSON.stringify(embed)); + } + + /** + * @param {string} key + */ + writeKey (key) { + writeVarString(this.restEncoder, key); + } + } + + class DSEncoderV2 { + constructor () { + this.restEncoder = new Encoder(); // encodes all the rest / non-optimized + this.dsCurrVal = 0; + } + + toUint8Array () { + return toUint8Array(this.restEncoder) + } + + resetDsCurVal () { + this.dsCurrVal = 0; + } + + /** + * @param {number} clock + */ + writeDsClock (clock) { + const diff = clock - this.dsCurrVal; + this.dsCurrVal = clock; + writeVarUint(this.restEncoder, diff); + } + + /** + * @param {number} len + */ + writeDsLen (len) { + if (len === 0) { + unexpectedCase(); + } + writeVarUint(this.restEncoder, len - 1); + this.dsCurrVal += len; + } + } + + class UpdateEncoderV2 extends DSEncoderV2 { + constructor () { + super(); + /** + * @type {Map} + */ + this.keyMap = new Map(); + /** + * Refers to the next uniqe key-identifier to me used. + * See writeKey method for more information. + * + * @type {number} + */ + this.keyClock = 0; + this.keyClockEncoder = new IntDiffOptRleEncoder(); + this.clientEncoder = new UintOptRleEncoder(); + this.leftClockEncoder = new IntDiffOptRleEncoder(); + this.rightClockEncoder = new IntDiffOptRleEncoder(); + this.infoEncoder = new RleEncoder(writeUint8); + this.stringEncoder = new StringEncoder(); + this.parentInfoEncoder = new RleEncoder(writeUint8); + this.typeRefEncoder = new UintOptRleEncoder(); + this.lenEncoder = new UintOptRleEncoder(); + } + + toUint8Array () { + const encoder = createEncoder(); + writeUint8(encoder, 0); // this is a feature flag that we might use in the future + writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array()); + writeVarUint8Array(encoder, this.clientEncoder.toUint8Array()); + writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array()); + writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array()); + writeVarUint8Array(encoder, toUint8Array(this.infoEncoder)); + writeVarUint8Array(encoder, this.stringEncoder.toUint8Array()); + writeVarUint8Array(encoder, toUint8Array(this.parentInfoEncoder)); + writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array()); + writeVarUint8Array(encoder, this.lenEncoder.toUint8Array()); + // @note The rest encoder is appended! (note the missing var) + writeUint8Array(encoder, toUint8Array(this.restEncoder)); + return toUint8Array(encoder) + } + + /** + * @param {ID} id + */ + writeLeftID (id) { + this.clientEncoder.write(id.client); + this.leftClockEncoder.write(id.clock); + } + + /** + * @param {ID} id + */ + writeRightID (id) { + this.clientEncoder.write(id.client); + this.rightClockEncoder.write(id.clock); + } + + /** + * @param {number} client + */ + writeClient (client) { + this.clientEncoder.write(client); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeInfo (info) { + this.infoEncoder.write(info); + } + + /** + * @param {string} s + */ + writeString (s) { + this.stringEncoder.write(s); + } + + /** + * @param {boolean} isYKey + */ + writeParentInfo (isYKey) { + this.parentInfoEncoder.write(isYKey ? 1 : 0); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeTypeRef (info) { + this.typeRefEncoder.write(info); + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @param {number} len + */ + writeLen (len) { + this.lenEncoder.write(len); + } + + /** + * @param {any} any + */ + writeAny (any) { + writeAny(this.restEncoder, any); + } + + /** + * @param {Uint8Array} buf + */ + writeBuf (buf) { + writeVarUint8Array(this.restEncoder, buf); + } + + /** + * This is mainly here for legacy purposes. + * + * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder. + * + * @param {any} embed + */ + writeJSON (embed) { + writeAny(this.restEncoder, embed); + } + + /** + * Property keys are often reused. For example, in y-prosemirror the key `bold` might + * occur very often. For a 3d application, the key `position` might occur very often. + * + * We cache these keys in a Map and refer to them via a unique number. + * + * @param {string} key + */ + writeKey (key) { + const clock = this.keyMap.get(key); + if (clock === undefined) { + this.keyClockEncoder.write(this.keyClock++); + this.stringEncoder.write(key); + } else { + this.keyClockEncoder.write(this.keyClock++); + } + } + } + + let DefaultDSEncoder = DSEncoderV1; + let DefaultDSDecoder = DSDecoderV1; + let DefaultUpdateEncoder = UpdateEncoderV1; + let DefaultUpdateDecoder = UpdateDecoderV1; + + const useV1Encoding = () => { + DefaultDSEncoder = DSEncoderV1; + DefaultDSDecoder = DSDecoderV1; + DefaultUpdateEncoder = UpdateEncoderV1; + DefaultUpdateDecoder = UpdateDecoderV1; + }; + + const useV2Encoding = () => { + DefaultDSEncoder = DSEncoderV2; + DefaultDSDecoder = DSDecoderV2; + DefaultUpdateEncoder = UpdateEncoderV2; + DefaultUpdateDecoder = UpdateDecoderV2; + }; + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {Array} structs All structs by `client` + * @param {number} client + * @param {number} clock write structs starting with `ID(client,clock)` + * + * @function + */ + const writeStructs = (encoder, structs, client, clock) => { + // write first id + const startNewStructs = findIndexSS(structs, clock); + // write # encoded structs + writeVarUint(encoder.restEncoder, structs.length - startNewStructs); + encoder.writeClient(client); + writeVarUint(encoder.restEncoder, clock); + const firstStruct = structs[startNewStructs]; + // write first struct with an offset + firstStruct.write(encoder, clock - firstStruct.id.clock); + for (let i = startNewStructs + 1; i < structs.length; i++) { + structs[i].write(encoder, 0); + } + }; + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {StructStore} store + * @param {Map} _sm + * + * @private + * @function + */ + const writeClientsStructs = (encoder, store, _sm) => { + // we filter all valid _sm entries into sm + const sm = new Map(); + _sm.forEach((clock, client) => { + // only write if new structs are available + if (getState(store, client) > clock) { + sm.set(client, clock); + } + }); + getStateVector(store).forEach((clock, client) => { + if (!_sm.has(client)) { + sm.set(client, 0); + } + }); + // write # states that were updated + writeVarUint(encoder.restEncoder, sm.size); + // Write items with higher client ids first + // This heavily improves the conflict algorithm. + Array.from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => { + // @ts-ignore + writeStructs(encoder, store.clients.get(client), client, clock); + }); + }; + + /** + * @param {AbstractUpdateDecoder} decoder The decoder object to read data from. + * @param {Map>} clientRefs + * @param {Doc} doc + * @return {Map>} + * + * @private + * @function + */ + const readClientsStructRefs = (decoder, clientRefs, doc) => { + const numOfStateUpdates = readVarUint(decoder.restDecoder); + for (let i = 0; i < numOfStateUpdates; i++) { + const numberOfStructs = readVarUint(decoder.restDecoder); + /** + * @type {Array} + */ + const refs = new Array(numberOfStructs); + const client = decoder.readClient(); + let clock = readVarUint(decoder.restDecoder); + // const start = performance.now() + clientRefs.set(client, refs); + for (let i = 0; i < numberOfStructs; i++) { + const info = decoder.readInfo(); + if ((BITS5 & info) !== 0) { + /** + * The optimized implementation doesn't use any variables because inlining variables is faster. + * Below a non-optimized version is shown that implements the basic algorithm with + * a few comments + */ + const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0; + // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y` + // and we read the next string as parentYKey. + // It indicates how we store/retrieve parent from `y.share` + // @type {string|null} + const struct = new Item( + createID(client, clock), + null, // leftd + (info & BIT8) === BIT8 ? decoder.readLeftID() : null, // origin + null, // right + (info & BIT7) === BIT7 ? decoder.readRightID() : null, // right origin + cantCopyParentInfo ? (decoder.readParentInfo() ? doc.get(decoder.readString()) : decoder.readLeftID()) : null, // parent + cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null, // parentSub + readItemContent(decoder, info) // item content + ); + /* A non-optimized implementation of the above algorithm: + + // The item that was originally to the left of this item. + const origin = (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null + // The item that was originally to the right of this item. + const rightOrigin = (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null + const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0 + const hasParentYKey = cantCopyParentInfo ? decoder.readParentInfo() : false + // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y` + // and we read the next string as parentYKey. + // It indicates how we store/retrieve parent from `y.share` + // @type {string|null} + const parentYKey = cantCopyParentInfo && hasParentYKey ? decoder.readString() : null + + const struct = new Item( + createID(client, clock), + null, // leftd + origin, // origin + null, // right + rightOrigin, // right origin + cantCopyParentInfo && !hasParentYKey ? decoder.readLeftID() : (parentYKey !== null ? doc.get(parentYKey) : null), // parent + cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub + readItemContent(decoder, info) // item content + ) + */ + refs[i] = struct; + clock += struct.length; + } else { + const len = decoder.readLen(); + refs[i] = new GC(createID(client, clock), len); + clock += len; + } + } + // console.log('time to read: ', performance.now() - start) // @todo remove + } + return clientRefs + }; + + /** + * Resume computing structs generated by struct readers. + * + * While there is something to do, we integrate structs in this order + * 1. top element on stack, if stack is not empty + * 2. next element from current struct reader (if empty, use next struct reader) + * + * If struct causally depends on another struct (ref.missing), we put next reader of + * `ref.id.client` on top of stack. + * + * At some point we find a struct that has no causal dependencies, + * then we start emptying the stack. + * + * It is not possible to have circles: i.e. struct1 (from client1) depends on struct2 (from client2) + * depends on struct3 (from client1). Therefore the max stack size is eqaul to `structReaders.length`. + * + * This method is implemented in a way so that we can resume computation if this update + * causally depends on another update. + * + * @param {Transaction} transaction + * @param {StructStore} store + * + * @private + * @function + */ + const resumeStructIntegration = (transaction, store) => { + const stack = store.pendingStack; // @todo don't forget to append stackhead at the end + const clientsStructRefs = store.pendingClientsStructRefs; + // sort them so that we take the higher id first, in case of conflicts the lower id will probably not conflict with the id from the higher user. + const clientsStructRefsIds = Array.from(clientsStructRefs.keys()).sort((a, b) => a - b); + if (clientsStructRefsIds.length === 0) { + return + } + const getNextStructTarget = () => { + let nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1])); + while (nextStructsTarget.refs.length === nextStructsTarget.i) { + clientsStructRefsIds.pop(); + if (clientsStructRefsIds.length > 0) { + nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1])); + } else { + store.pendingClientsStructRefs.clear(); + return null + } + } + return nextStructsTarget + }; + let curStructsTarget = getNextStructTarget(); + if (curStructsTarget === null && stack.length === 0) { + return + } + /** + * @type {GC|Item} + */ + let stackHead = stack.length > 0 + ? /** @type {GC|Item} */ (stack.pop()) + : /** @type {any} */ (curStructsTarget).refs[/** @type {any} */ (curStructsTarget).i++]; + // caching the state because it is used very often + const state = new Map(); + // iterate over all struct readers until we are done + while (true) { + const localClock = setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client)); + const offset = stackHead.id.clock < localClock ? localClock - stackHead.id.clock : 0; + if (stackHead.id.clock + offset !== localClock) { + // A previous message from this client is missing + // check if there is a pending structRef with a smaller clock and switch them + /** + * @type {{ refs: Array, i: number }} + */ + const structRefs = clientsStructRefs.get(stackHead.id.client) || { refs: [], i: 0 }; + if (structRefs.refs.length !== structRefs.i) { + const r = structRefs.refs[structRefs.i]; + if (r.id.clock < stackHead.id.clock) { + // put ref with smaller clock on stack instead and continue + structRefs.refs[structRefs.i] = stackHead; + stackHead = r; + // sort the set because this approach might bring the list out of order + structRefs.refs = structRefs.refs.slice(structRefs.i).sort((r1, r2) => r1.id.clock - r2.id.clock); + structRefs.i = 0; + continue + } + } + // wait until missing struct is available + stack.push(stackHead); + return + } + const missing = stackHead.getMissing(transaction, store); + if (missing === null) { + if (offset === 0 || offset < stackHead.length) { + stackHead.integrate(transaction, offset); + state.set(stackHead.id.client, stackHead.id.clock + stackHead.length); + } + // iterate to next stackHead + if (stack.length > 0) { + stackHead = /** @type {GC|Item} */ (stack.pop()); + } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) { + stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++]); + } else { + curStructsTarget = getNextStructTarget(); + if (curStructsTarget === null) { + // we are done! + break + } else { + stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++]); + } + } + } else { + // get the struct reader that has the missing struct + /** + * @type {{ refs: Array, i: number }} + */ + const structRefs = clientsStructRefs.get(missing) || { refs: [], i: 0 }; + if (structRefs.refs.length === structRefs.i) { + // This update message causally depends on another update message. + stack.push(stackHead); + return + } + stack.push(stackHead); + stackHead = structRefs.refs[structRefs.i++]; + } + } + store.pendingClientsStructRefs.clear(); + }; + + /** + * @param {Transaction} transaction + * @param {StructStore} store + * + * @private + * @function + */ + const tryResumePendingDeleteReaders = (transaction, store) => { + const pendingReaders = store.pendingDeleteReaders; + store.pendingDeleteReaders = []; + for (let i = 0; i < pendingReaders.length; i++) { + readAndApplyDeleteSet(pendingReaders[i], transaction, store); + } + }; + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {Transaction} transaction + * + * @private + * @function + */ + const writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState); + + /** + * @param {StructStore} store + * @param {Map>} clientsStructsRefs + * + * @private + * @function + */ + const mergeReadStructsIntoPendingReads = (store, clientsStructsRefs) => { + const pendingClientsStructRefs = store.pendingClientsStructRefs; + clientsStructsRefs.forEach((structRefs, client) => { + const pendingStructRefs = pendingClientsStructRefs.get(client); + if (pendingStructRefs === undefined) { + pendingClientsStructRefs.set(client, { refs: structRefs, i: 0 }); + } else { + // merge into existing structRefs + const merged = pendingStructRefs.i > 0 ? pendingStructRefs.refs.slice(pendingStructRefs.i) : pendingStructRefs.refs; + for (let i = 0; i < structRefs.length; i++) { + merged.push(structRefs[i]); + } + pendingStructRefs.i = 0; + pendingStructRefs.refs = merged.sort((r1, r2) => r1.id.clock - r2.id.clock); + } + }); + }; + + /** + * @param {Map,i:number}>} pendingClientsStructRefs + */ + const cleanupPendingStructs = pendingClientsStructRefs => { + // cleanup pendingClientsStructs if not fully finished + pendingClientsStructRefs.forEach((refs, client) => { + if (refs.i === refs.refs.length) { + pendingClientsStructRefs.delete(client); + } else { + refs.refs.splice(0, refs.i); + refs.i = 0; + } + }); + }; + + /** + * Read the next Item in a Decoder and fill this Item with the read data. + * + * This is called when data is received from a remote peer. + * + * @param {AbstractUpdateDecoder} decoder The decoder object to read data from. + * @param {Transaction} transaction + * @param {StructStore} store + * + * @private + * @function + */ + const readStructs = (decoder, transaction, store) => { + const clientsStructRefs = new Map(); + // let start = performance.now() + readClientsStructRefs(decoder, clientsStructRefs, transaction.doc); + // console.log('time to read structs: ', performance.now() - start) // @todo remove + // start = performance.now() + mergeReadStructsIntoPendingReads(store, clientsStructRefs); + // console.log('time to merge: ', performance.now() - start) // @todo remove + // start = performance.now() + resumeStructIntegration(transaction, store); + // console.log('time to integrate: ', performance.now() - start) // @todo remove + // start = performance.now() + cleanupPendingStructs(store.pendingClientsStructRefs); + // console.log('time to cleanup: ', performance.now() - start) // @todo remove + // start = performance.now() + tryResumePendingDeleteReaders(transaction, store); + // console.log('time to resume delete readers: ', performance.now() - start) // @todo remove + // start = performance.now() + }; + + /** + * Read and apply a document update. + * + * This function has the same effect as `applyUpdate` but accepts an decoder. + * + * @param {decoding.Decoder} decoder + * @param {Doc} ydoc + * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))` + * @param {AbstractUpdateDecoder} [structDecoder] + * + * @function + */ + const readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) => + transact(ydoc, transaction => { + readStructs(structDecoder, transaction, ydoc.store); + readAndApplyDeleteSet(structDecoder, transaction, ydoc.store); + }, transactionOrigin, false); + + /** + * Read and apply a document update. + * + * This function has the same effect as `applyUpdate` but accepts an decoder. + * + * @param {decoding.Decoder} decoder + * @param {Doc} ydoc + * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))` + * + * @function + */ + const readUpdate = (decoder, ydoc, transactionOrigin) => readUpdateV2(decoder, ydoc, transactionOrigin, new DefaultUpdateDecoder(decoder)); + + /** + * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`. + * + * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder. + * + * @param {Doc} ydoc + * @param {Uint8Array} update + * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))` + * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder] + * + * @function + */ + const applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => { + const decoder = createDecoder(update); + readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder)); + }; + + /** + * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`. + * + * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder. + * + * @param {Doc} ydoc + * @param {Uint8Array} update + * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))` + * + * @function + */ + const applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, DefaultUpdateDecoder); + + /** + * Write all the document as a single update message. If you specify the state of the remote client (`targetStateVector`) it will + * only write the operations that are missing. + * + * @param {AbstractUpdateEncoder} encoder + * @param {Doc} doc + * @param {Map} [targetStateVector] The state of the target that receives the update. Leave empty to write all known structs + * + * @function + */ + const writeStateAsUpdate = (encoder, doc, targetStateVector = new Map()) => { + writeClientsStructs(encoder, doc.store, targetStateVector); + writeDeleteSet(encoder, createDeleteSetFromStructStore(doc.store)); + }; + + /** + * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will + * only write the operations that are missing. + * + * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder + * + * @param {Doc} doc + * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs + * @param {AbstractUpdateEncoder} [encoder] + * @return {Uint8Array} + * + * @function + */ + const encodeStateAsUpdateV2 = (doc, encodedTargetStateVector, encoder = new UpdateEncoderV2()) => { + const targetStateVector = encodedTargetStateVector == null ? new Map() : decodeStateVector(encodedTargetStateVector); + writeStateAsUpdate(encoder, doc, targetStateVector); + return encoder.toUint8Array() + }; + + /** + * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will + * only write the operations that are missing. + * + * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder + * + * @param {Doc} doc + * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs + * @return {Uint8Array} + * + * @function + */ + const encodeStateAsUpdate = (doc, encodedTargetStateVector) => encodeStateAsUpdateV2(doc, encodedTargetStateVector, new DefaultUpdateEncoder()); + + /** + * Read state vector from Decoder and return as Map + * + * @param {AbstractDSDecoder} decoder + * @return {Map} Maps `client` to the number next expected `clock` from that client. + * + * @function + */ + const readStateVector = decoder => { + const ss = new Map(); + const ssLength = readVarUint(decoder.restDecoder); + for (let i = 0; i < ssLength; i++) { + const client = readVarUint(decoder.restDecoder); + const clock = readVarUint(decoder.restDecoder); + ss.set(client, clock); + } + return ss + }; + + /** + * Read decodedState and return State as Map. + * + * @param {Uint8Array} decodedState + * @return {Map} Maps `client` to the number next expected `clock` from that client. + * + * @function + */ + const decodeStateVectorV2 = decodedState => readStateVector(new DSDecoderV2(createDecoder(decodedState))); + + /** + * Read decodedState and return State as Map. + * + * @param {Uint8Array} decodedState + * @return {Map} Maps `client` to the number next expected `clock` from that client. + * + * @function + */ + const decodeStateVector = decodedState => readStateVector(new DefaultDSDecoder(createDecoder(decodedState))); + + /** + * @param {AbstractDSEncoder} encoder + * @param {Map} sv + * @function + */ + const writeStateVector = (encoder, sv) => { + writeVarUint(encoder.restEncoder, sv.size); + sv.forEach((clock, client) => { + writeVarUint(encoder.restEncoder, client); // @todo use a special client decoder that is based on mapping + writeVarUint(encoder.restEncoder, clock); + }); + return encoder + }; + + /** + * @param {AbstractDSEncoder} encoder + * @param {Doc} doc + * + * @function + */ + const writeDocumentStateVector = (encoder, doc) => writeStateVector(encoder, getStateVector(doc.store)); + + /** + * Encode State as Uint8Array. + * + * @param {Doc} doc + * @param {AbstractDSEncoder} [encoder] + * @return {Uint8Array} + * + * @function + */ + const encodeStateVectorV2 = (doc, encoder = new DSEncoderV2()) => { + writeDocumentStateVector(encoder, doc); + return encoder.toUint8Array() + }; + + /** + * Encode State as Uint8Array. + * + * @param {Doc} doc + * @return {Uint8Array} + * + * @function + */ + const encodeStateVector = doc => encodeStateVectorV2(doc, new DefaultDSEncoder()); + + /** + * General event handler implementation. + * + * @template ARG0, ARG1 + * + * @private + */ + class EventHandler { + constructor () { + /** + * @type {Array} + */ + this.l = []; + } + } + + /** + * @template ARG0,ARG1 + * @returns {EventHandler} + * + * @private + * @function + */ + const createEventHandler = () => new EventHandler(); + + /** + * Adds an event listener that is called when + * {@link EventHandler#callEventListeners} is called. + * + * @template ARG0,ARG1 + * @param {EventHandler} eventHandler + * @param {function(ARG0,ARG1):void} f The event handler. + * + * @private + * @function + */ + const addEventHandlerListener = (eventHandler, f) => + eventHandler.l.push(f); + + /** + * Removes an event listener. + * + * @template ARG0,ARG1 + * @param {EventHandler} eventHandler + * @param {function(ARG0,ARG1):void} f The event handler that was added with + * {@link EventHandler#addEventListener} + * + * @private + * @function + */ + const removeEventHandlerListener = (eventHandler, f) => { + const l = eventHandler.l; + const len = l.length; + eventHandler.l = l.filter(g => f !== g); + if (len === eventHandler.l.length) { + console.error('[yjs] Tried to remove event handler that doesn\'t exist.'); + } + }; + + /** + * Removes all event listeners. + * @template ARG0,ARG1 + * @param {EventHandler} eventHandler + * + * @private + * @function + */ + const removeAllEventHandlerListeners = eventHandler => { + eventHandler.l.length = 0; + }; + + /** + * Call all event listeners that were added via + * {@link EventHandler#addEventListener}. + * + * @template ARG0,ARG1 + * @param {EventHandler} eventHandler + * @param {ARG0} arg0 + * @param {ARG1} arg1 + * + * @private + * @function + */ + const callEventHandlerListeners = (eventHandler, arg0, arg1) => + callAll(eventHandler.l, [arg0, arg1]); + + class ID { + /** + * @param {number} client client id + * @param {number} clock unique per client id, continuous number + */ + constructor (client, clock) { + /** + * Client id + * @type {number} + */ + this.client = client; + /** + * unique per client id, continuous number + * @type {number} + */ + this.clock = clock; + } + } + + /** + * @param {ID | null} a + * @param {ID | null} b + * @return {boolean} + * + * @function + */ + const compareIDs = (a, b) => a === b || (a !== null && b !== null && a.client === b.client && a.clock === b.clock); + + /** + * @param {number} client + * @param {number} clock + * + * @private + * @function + */ + const createID = (client, clock) => new ID(client, clock); + + /** + * @param {encoding.Encoder} encoder + * @param {ID} id + * + * @private + * @function + */ + const writeID = (encoder, id) => { + writeVarUint(encoder, id.client); + writeVarUint(encoder, id.clock); + }; + + /** + * Read ID. + * * If first varUint read is 0xFFFFFF a RootID is returned. + * * Otherwise an ID is returned + * + * @param {decoding.Decoder} decoder + * @return {ID} + * + * @private + * @function + */ + const readID = decoder => + createID(readVarUint(decoder), readVarUint(decoder)); + + /** + * The top types are mapped from y.share.get(keyname) => type. + * `type` does not store any information about the `keyname`. + * This function finds the correct `keyname` for `type` and throws otherwise. + * + * @param {AbstractType} type + * @return {string} + * + * @private + * @function + */ + const findRootTypeKey = type => { + // @ts-ignore _y must be defined, otherwise unexpected case + for (const [key, value] of type.doc.share.entries()) { + if (value === type) { + return key + } + } + throw unexpectedCase() + }; + + /** + * Check if `parent` is a parent of `child`. + * + * @param {AbstractType} parent + * @param {Item|null} child + * @return {Boolean} Whether `parent` is a parent of `child`. + * + * @private + * @function + */ + const isParentOf = (parent, child) => { + while (child !== null) { + if (child.parent === parent) { + return true + } + child = /** @type {AbstractType} */ (child.parent)._item; + } + return false + }; + + /** + * Convenient helper to log type information. + * + * Do not use in productive systems as the output can be immense! + * + * @param {AbstractType} type + */ + const logType = type => { + const res = []; + let n = type._start; + while (n) { + res.push(n); + n = n.right; + } + console.log('Children: ', res); + console.log('Children content: ', res.filter(m => !m.deleted).map(m => m.content)); + }; + + class PermanentUserData { + /** + * @param {Doc} doc + * @param {YMap} [storeType] + */ + constructor (doc, storeType = doc.getMap('users')) { + /** + * @type {Map} + */ + const dss = new Map(); + this.yusers = storeType; + this.doc = doc; + /** + * Maps from clientid to userDescription + * + * @type {Map} + */ + this.clients = new Map(); + this.dss = dss; + /** + * @param {YMap} user + * @param {string} userDescription + */ + const initUser = (user, userDescription) => { + /** + * @type {YArray} + */ + const ds = user.get('ds'); + const ids = user.get('ids'); + const addClientId = /** @param {number} clientid */ clientid => this.clients.set(clientid, userDescription); + ds.observe(/** @param {YArrayEvent} event */ event => { + event.changes.added.forEach(item => { + item.content.getContent().forEach(encodedDs => { + if (encodedDs instanceof Uint8Array) { + this.dss.set(userDescription, mergeDeleteSets([this.dss.get(userDescription) || createDeleteSet(), readDeleteSet(new DSDecoderV1(createDecoder(encodedDs)))])); + } + }); + }); + }); + this.dss.set(userDescription, mergeDeleteSets(ds.map(encodedDs => readDeleteSet(new DSDecoderV1(createDecoder(encodedDs)))))); + ids.observe(/** @param {YArrayEvent} event */ event => + event.changes.added.forEach(item => item.content.getContent().forEach(addClientId)) + ); + ids.forEach(addClientId); + }; + // observe users + storeType.observe(event => { + event.keysChanged.forEach(userDescription => + initUser(storeType.get(userDescription), userDescription) + ); + }); + // add intial data + storeType.forEach(initUser); + } + + /** + * @param {Doc} doc + * @param {number} clientid + * @param {string} userDescription + * @param {Object} [conf] + * @param {function(Transaction, DeleteSet):boolean} [conf.filter] + */ + setUserMapping (doc, clientid, userDescription, { filter = () => true } = {}) { + const users = this.yusers; + let user = users.get(userDescription); + if (!user) { + user = new YMap(); + user.set('ids', new YArray()); + user.set('ds', new YArray()); + users.set(userDescription, user); + } + user.get('ids').push([clientid]); + users.observe(event => { + setTimeout(() => { + const userOverwrite = users.get(userDescription); + if (userOverwrite !== user) { + // user was overwritten, port all data over to the next user object + // @todo Experiment with Y.Sets here + user = userOverwrite; + // @todo iterate over old type + this.clients.forEach((_userDescription, clientid) => { + if (userDescription === _userDescription) { + user.get('ids').push([clientid]); + } + }); + const encoder = new DSEncoderV1(); + const ds = this.dss.get(userDescription); + if (ds) { + writeDeleteSet(encoder, ds); + user.get('ds').push([encoder.toUint8Array()]); + } + } + }, 0); + }); + doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => { + setTimeout(() => { + const yds = user.get('ds'); + const ds = transaction.deleteSet; + if (transaction.local && ds.clients.size > 0 && filter(transaction, ds)) { + const encoder = new DSEncoderV1(); + writeDeleteSet(encoder, ds); + yds.push([encoder.toUint8Array()]); + } + }); + }); + } + + /** + * @param {number} clientid + * @return {any} + */ + getUserByClientId (clientid) { + return this.clients.get(clientid) || null + } + + /** + * @param {ID} id + * @return {string | null} + */ + getUserByDeletedId (id) { + for (const [userDescription, ds] of this.dss.entries()) { + if (isDeleted(ds, id)) { + return userDescription + } + } + return null + } + } + + /** + * A relative position is based on the Yjs model and is not affected by document changes. + * E.g. If you place a relative position before a certain character, it will always point to this character. + * If you place a relative position at the end of a type, it will always point to the end of the type. + * + * A numeric position is often unsuited for user selections, because it does not change when content is inserted + * before or after. + * + * ```Insert(0, 'x')('a|bc') = 'xa|bc'``` Where | is the relative position. + * + * One of the properties must be defined. + * + * @example + * // Current cursor position is at position 10 + * const relativePosition = createRelativePositionFromIndex(yText, 10) + * // modify yText + * yText.insert(0, 'abc') + * yText.delete(3, 10) + * // Compute the cursor position + * const absolutePosition = createAbsolutePositionFromRelativePosition(y, relativePosition) + * absolutePosition.type === yText // => true + * console.log('cursor location is ' + absolutePosition.index) // => cursor location is 3 + * + */ + class RelativePosition { + /** + * @param {ID|null} type + * @param {string|null} tname + * @param {ID|null} item + */ + constructor (type, tname, item) { + /** + * @type {ID|null} + */ + this.type = type; + /** + * @type {string|null} + */ + this.tname = tname; + /** + * @type {ID | null} + */ + this.item = item; + } + } + + /** + * @param {any} json + * @return {RelativePosition} + * + * @function + */ + const createRelativePositionFromJSON = json => new RelativePosition(json.type == null ? null : createID(json.type.client, json.type.clock), json.tname || null, json.item == null ? null : createID(json.item.client, json.item.clock)); + + class AbsolutePosition { + /** + * @param {AbstractType} type + * @param {number} index + */ + constructor (type, index) { + /** + * @type {AbstractType} + */ + this.type = type; + /** + * @type {number} + */ + this.index = index; + } + } + + /** + * @param {AbstractType} type + * @param {number} index + * + * @function + */ + const createAbsolutePosition = (type, index) => new AbsolutePosition(type, index); + + /** + * @param {AbstractType} type + * @param {ID|null} item + * + * @function + */ + const createRelativePosition = (type, item) => { + let typeid = null; + let tname = null; + if (type._item === null) { + tname = findRootTypeKey(type); + } else { + typeid = createID(type._item.id.client, type._item.id.clock); + } + return new RelativePosition(typeid, tname, item) + }; + + /** + * Create a relativePosition based on a absolute position. + * + * @param {AbstractType} type The base type (e.g. YText or YArray). + * @param {number} index The absolute position. + * @return {RelativePosition} + * + * @function + */ + const createRelativePositionFromTypeIndex = (type, index) => { + let t = type._start; + while (t !== null) { + if (!t.deleted && t.countable) { + if (t.length > index) { + // case 1: found position somewhere in the linked list + return createRelativePosition(type, createID(t.id.client, t.id.clock + index)) + } + index -= t.length; + } + t = t.right; + } + return createRelativePosition(type, null) + }; + + /** + * @param {encoding.Encoder} encoder + * @param {RelativePosition} rpos + * + * @function + */ + const writeRelativePosition = (encoder, rpos) => { + const { type, tname, item } = rpos; + if (item !== null) { + writeVarUint(encoder, 0); + writeID(encoder, item); + } else if (tname !== null) { + // case 2: found position at the end of the list and type is stored in y.share + writeUint8(encoder, 1); + writeVarString(encoder, tname); + } else if (type !== null) { + // case 3: found position at the end of the list and type is attached to an item + writeUint8(encoder, 2); + writeID(encoder, type); + } else { + throw unexpectedCase() + } + return encoder + }; + + /** + * @param {RelativePosition} rpos + * @return {Uint8Array} + */ + const encodeRelativePosition = rpos => { + const encoder = createEncoder(); + writeRelativePosition(encoder, rpos); + return toUint8Array(encoder) + }; + + /** + * @param {decoding.Decoder} decoder + * @return {RelativePosition|null} + * + * @function + */ + const readRelativePosition = decoder => { + let type = null; + let tname = null; + let itemID = null; + switch (readVarUint(decoder)) { + case 0: + // case 1: found position somewhere in the linked list + itemID = readID(decoder); + break + case 1: + // case 2: found position at the end of the list and type is stored in y.share + tname = readVarString(decoder); + break + case 2: { + // case 3: found position at the end of the list and type is attached to an item + type = readID(decoder); + } + } + return new RelativePosition(type, tname, itemID) + }; + + /** + * @param {Uint8Array} uint8Array + * @return {RelativePosition|null} + */ + const decodeRelativePosition = uint8Array => readRelativePosition(createDecoder(uint8Array)); + + /** + * @param {RelativePosition} rpos + * @param {Doc} doc + * @return {AbsolutePosition|null} + * + * @function + */ + const createAbsolutePositionFromRelativePosition = (rpos, doc) => { + const store = doc.store; + const rightID = rpos.item; + const typeID = rpos.type; + const tname = rpos.tname; + let type = null; + let index = 0; + if (rightID !== null) { + if (getState(store, rightID.client) <= rightID.clock) { + return null + } + const res = followRedone(store, rightID); + const right = res.item; + if (!(right instanceof Item)) { + return null + } + type = /** @type {AbstractType} */ (right.parent); + if (type._item === null || !type._item.deleted) { + index = right.deleted || !right.countable ? 0 : res.diff; + let n = right.left; + while (n !== null) { + if (!n.deleted && n.countable) { + index += n.length; + } + n = n.left; + } + } + } else { + if (tname !== null) { + type = doc.get(tname); + } else if (typeID !== null) { + if (getState(store, typeID.client) <= typeID.clock) { + // type does not exist yet + return null + } + const { item } = followRedone(store, typeID); + if (item instanceof Item && item.content instanceof ContentType) { + type = item.content.type; + } else { + // struct is garbage collected + return null + } + } else { + throw unexpectedCase() + } + index = type._length; + } + return createAbsolutePosition(type, index) + }; + + /** + * @param {RelativePosition|null} a + * @param {RelativePosition|null} b + * + * @function + */ + const compareRelativePositions = (a, b) => a === b || ( + a !== null && b !== null && a.tname === b.tname && compareIDs(a.item, b.item) && compareIDs(a.type, b.type) + ); + + class Snapshot { + /** + * @param {DeleteSet} ds + * @param {Map} sv state map + */ + constructor (ds, sv) { + /** + * @type {DeleteSet} + */ + this.ds = ds; + /** + * State Map + * @type {Map} + */ + this.sv = sv; + } + } + + /** + * @param {Snapshot} snap1 + * @param {Snapshot} snap2 + * @return {boolean} + */ + const equalSnapshots = (snap1, snap2) => { + const ds1 = snap1.ds.clients; + const ds2 = snap2.ds.clients; + const sv1 = snap1.sv; + const sv2 = snap2.sv; + if (sv1.size !== sv2.size || ds1.size !== ds2.size) { + return false + } + for (const [key, value] of sv1.entries()) { + if (sv2.get(key) !== value) { + return false + } + } + for (const [client, dsitems1] of ds1.entries()) { + const dsitems2 = ds2.get(client) || []; + if (dsitems1.length !== dsitems2.length) { + return false + } + for (let i = 0; i < dsitems1.length; i++) { + const dsitem1 = dsitems1[i]; + const dsitem2 = dsitems2[i]; + if (dsitem1.clock !== dsitem2.clock || dsitem1.len !== dsitem2.len) { + return false + } + } + } + return true + }; + + /** + * @param {Snapshot} snapshot + * @param {AbstractDSEncoder} [encoder] + * @return {Uint8Array} + */ + const encodeSnapshotV2 = (snapshot, encoder = new DSEncoderV2()) => { + writeDeleteSet(encoder, snapshot.ds); + writeStateVector(encoder, snapshot.sv); + return encoder.toUint8Array() + }; + + /** + * @param {Snapshot} snapshot + * @return {Uint8Array} + */ + const encodeSnapshot = snapshot => encodeSnapshotV2(snapshot, new DefaultDSEncoder()); + + /** + * @param {Uint8Array} buf + * @param {AbstractDSDecoder} [decoder] + * @return {Snapshot} + */ + const decodeSnapshotV2 = (buf, decoder = new DSDecoderV2(createDecoder(buf))) => { + return new Snapshot(readDeleteSet(decoder), readStateVector(decoder)) + }; + + /** + * @param {Uint8Array} buf + * @return {Snapshot} + */ + const decodeSnapshot = buf => decodeSnapshotV2(buf, new DSDecoderV1(createDecoder(buf))); + + /** + * @param {DeleteSet} ds + * @param {Map} sm + * @return {Snapshot} + */ + const createSnapshot = (ds, sm) => new Snapshot(ds, sm); + + const emptySnapshot = createSnapshot(createDeleteSet(), new Map()); + + /** + * @param {Doc} doc + * @return {Snapshot} + */ + const snapshot = doc => createSnapshot(createDeleteSetFromStructStore(doc.store), getStateVector(doc.store)); + + /** + * @param {Item} item + * @param {Snapshot|undefined} snapshot + * + * @protected + * @function + */ + const isVisible = (item, snapshot) => snapshot === undefined ? !item.deleted : ( + snapshot.sv.has(item.id.client) && (snapshot.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot.ds, item.id) + ); + + /** + * @param {Transaction} transaction + * @param {Snapshot} snapshot + */ + const splitSnapshotAffectedStructs = (transaction, snapshot) => { + const meta = setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, create$4); + const store = transaction.doc.store; + // check if we already split for this snapshot + if (!meta.has(snapshot)) { + snapshot.sv.forEach((clock, client) => { + if (clock < getState(store, client)) { + getItemCleanStart(transaction, createID(client, clock)); + } + }); + iterateDeletedStructs(transaction, snapshot.ds, item => {}); + meta.add(snapshot); + } + }; + + /** + * @param {Doc} originDoc + * @param {Snapshot} snapshot + * @param {Doc} [newDoc] Optionally, you may define the Yjs document that receives the data from originDoc + * @return {Doc} + */ + const createDocFromSnapshot = (originDoc, snapshot, newDoc = new Doc()) => { + if (originDoc.gc) { + // we should not try to restore a GC-ed document, because some of the restored items might have their content deleted + throw new Error('originDoc must not be garbage collected') + } + const { sv, ds } = snapshot; + + const encoder = new UpdateEncoderV2(); + originDoc.transact(transaction => { + let size = 0; + sv.forEach(clock => { + if (clock > 0) { + size++; + } + }); + writeVarUint(encoder.restEncoder, size); + // splitting the structs before writing them to the encoder + for (const [client, clock] of sv) { + if (clock === 0) { + continue + } + if (clock < getState(originDoc.store, client)) { + getItemCleanStart(transaction, createID(client, clock)); + } + const structs = originDoc.store.clients.get(client) || []; + const lastStructIndex = findIndexSS(structs, clock - 1); + // write # encoded structs + writeVarUint(encoder.restEncoder, lastStructIndex + 1); + encoder.writeClient(client); + // first clock written is 0 + writeVarUint(encoder.restEncoder, 0); + for (let i = 0; i <= lastStructIndex; i++) { + structs[i].write(encoder, 0); + } + } + writeDeleteSet(encoder, ds); + }); + + applyUpdateV2(newDoc, encoder.toUint8Array(), 'snapshot'); + return newDoc + }; + + class StructStore { + constructor () { + /** + * @type {Map>} + */ + this.clients = new Map(); + /** + * Store incompleted struct reads here + * `i` denotes to the next read operation + * We could shift the array of refs instead, but shift is incredible + * slow in Chrome for arrays with more than 100k elements + * @see tryResumePendingStructRefs + * @type {Map}>} + */ + this.pendingClientsStructRefs = new Map(); + /** + * Stack of pending structs waiting for struct dependencies + * Maximum length of stack is structReaders.size + * @type {Array} + */ + this.pendingStack = []; + /** + * @type {Array} + */ + this.pendingDeleteReaders = []; + } + } + + /** + * Return the states as a Map. + * Note that clock refers to the next expected clock id. + * + * @param {StructStore} store + * @return {Map} + * + * @public + * @function + */ + const getStateVector = store => { + const sm = new Map(); + store.clients.forEach((structs, client) => { + const struct = structs[structs.length - 1]; + sm.set(client, struct.id.clock + struct.length); + }); + return sm + }; + + /** + * @param {StructStore} store + * @param {number} client + * @return {number} + * + * @public + * @function + */ + const getState = (store, client) => { + const structs = store.clients.get(client); + if (structs === undefined) { + return 0 + } + const lastStruct = structs[structs.length - 1]; + return lastStruct.id.clock + lastStruct.length + }; + + /** + * @param {StructStore} store + * + * @private + * @function + */ + const integretyCheck = store => { + store.clients.forEach(structs => { + for (let i = 1; i < structs.length; i++) { + const l = structs[i - 1]; + const r = structs[i]; + if (l.id.clock + l.length !== r.id.clock) { + throw new Error('StructStore failed integrety check') + } + } + }); + }; + + /** + * @param {StructStore} store + * @param {GC|Item} struct + * + * @private + * @function + */ + const addStruct = (store, struct) => { + let structs = store.clients.get(struct.id.client); + if (structs === undefined) { + structs = []; + store.clients.set(struct.id.client, structs); + } else { + const lastStruct = structs[structs.length - 1]; + if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) { + throw unexpectedCase() + } + } + structs.push(struct); + }; + + /** + * Perform a binary search on a sorted array + * @param {Array} structs + * @param {number} clock + * @return {number} + * + * @private + * @function + */ + const findIndexSS = (structs, clock) => { + let left = 0; + let right = structs.length - 1; + let mid = structs[right]; + let midclock = mid.id.clock; + if (midclock === clock) { + return right + } + // @todo does it even make sense to pivot the search? + // If a good split misses, it might actually increase the time to find the correct item. + // Currently, the only advantage is that search with pivoting might find the item on the first try. + let midindex = floor((clock / (midclock + mid.length - 1)) * right); // pivoting the search + while (left <= right) { + mid = structs[midindex]; + midclock = mid.id.clock; + if (midclock <= clock) { + if (clock < midclock + mid.length) { + return midindex + } + left = midindex + 1; + } else { + right = midindex - 1; + } + midindex = floor((left + right) / 2); + } + // Always check state before looking for a struct in StructStore + // Therefore the case of not finding a struct is unexpected + throw unexpectedCase() + }; + + /** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * + * @param {StructStore} store + * @param {ID} id + * @return {GC|Item} + * + * @private + * @function + */ + const find = (store, id) => { + /** + * @type {Array} + */ + // @ts-ignore + const structs = store.clients.get(id.client); + return structs[findIndexSS(structs, id.clock)] + }; + + /** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * @private + * @function + */ + const getItem = /** @type {function(StructStore,ID):Item} */ (find); + + /** + * @param {Transaction} transaction + * @param {Array} structs + * @param {number} clock + */ + const findIndexCleanStart = (transaction, structs, clock) => { + const index = findIndexSS(structs, clock); + const struct = structs[index]; + if (struct.id.clock < clock && struct instanceof Item) { + structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); + return index + 1 + } + return index + }; + + /** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * + * @param {Transaction} transaction + * @param {ID} id + * @return {Item} + * + * @private + * @function + */ + const getItemCleanStart = (transaction, id) => { + const structs = /** @type {Array} */ (transaction.doc.store.clients.get(id.client)); + return structs[findIndexCleanStart(transaction, structs, id.clock)] + }; + + /** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * + * @param {Transaction} transaction + * @param {StructStore} store + * @param {ID} id + * @return {Item} + * + * @private + * @function + */ + const getItemCleanEnd = (transaction, store, id) => { + /** + * @type {Array} + */ + // @ts-ignore + const structs = store.clients.get(id.client); + const index = findIndexSS(structs, id.clock); + const struct = structs[index]; + if (id.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) { + structs.splice(index + 1, 0, splitItem(transaction, struct, id.clock - struct.id.clock + 1)); + } + return struct + }; + + /** + * Replace `item` with `newitem` in store + * @param {StructStore} store + * @param {GC|Item} struct + * @param {GC|Item} newStruct + * + * @private + * @function + */ + const replaceStruct = (store, struct, newStruct) => { + const structs = /** @type {Array} */ (store.clients.get(struct.id.client)); + structs[findIndexSS(structs, struct.id.clock)] = newStruct; + }; + + /** + * Iterate over a range of structs + * + * @param {Transaction} transaction + * @param {Array} structs + * @param {number} clockStart Inclusive start + * @param {number} len + * @param {function(GC|Item):void} f + * + * @function + */ + const iterateStructs = (transaction, structs, clockStart, len, f) => { + if (len === 0) { + return + } + const clockEnd = clockStart + len; + let index = findIndexCleanStart(transaction, structs, clockStart); + let struct; + do { + struct = structs[index++]; + if (clockEnd < struct.id.clock + struct.length) { + findIndexCleanStart(transaction, structs, clockEnd); + } + f(struct); + } while (index < structs.length && structs[index].id.clock < clockEnd) + }; + + /** + * A transaction is created for every change on the Yjs model. It is possible + * to bundle changes on the Yjs model in a single transaction to + * minimize the number on messages sent and the number of observer calls. + * If possible the user of this library should bundle as many changes as + * possible. Here is an example to illustrate the advantages of bundling: + * + * @example + * const map = y.define('map', YMap) + * // Log content when change is triggered + * map.observe(() => { + * console.log('change triggered') + * }) + * // Each change on the map type triggers a log message: + * map.set('a', 0) // => "change triggered" + * map.set('b', 0) // => "change triggered" + * // When put in a transaction, it will trigger the log after the transaction: + * y.transact(() => { + * map.set('a', 1) + * map.set('b', 1) + * }) // => "change triggered" + * + * @public + */ + class Transaction { + /** + * @param {Doc} doc + * @param {any} origin + * @param {boolean} local + */ + constructor (doc, origin, local) { + /** + * The Yjs instance. + * @type {Doc} + */ + this.doc = doc; + /** + * Describes the set of deleted items by ids + * @type {DeleteSet} + */ + this.deleteSet = new DeleteSet(); + /** + * Holds the state before the transaction started. + * @type {Map} + */ + this.beforeState = getStateVector(doc.store); + /** + * Holds the state after the transaction. + * @type {Map} + */ + this.afterState = new Map(); + /** + * All types that were directly modified (property added or child + * inserted/deleted). New types are not included in this Set. + * Maps from type to parentSubs (`item.parentSub = null` for YArray) + * @type {Map,Set>} + */ + this.changed = new Map(); + /** + * Stores the events for the types that observe also child elements. + * It is mainly used by `observeDeep`. + * @type {Map,Array>} + */ + this.changedParentTypes = new Map(); + /** + * @type {Array} + */ + this._mergeStructs = []; + /** + * @type {any} + */ + this.origin = origin; + /** + * Stores meta information on the transaction + * @type {Map} + */ + this.meta = new Map(); + /** + * Whether this change originates from this doc. + * @type {boolean} + */ + this.local = local; + /** + * @type {Set} + */ + this.subdocsAdded = new Set(); + /** + * @type {Set} + */ + this.subdocsRemoved = new Set(); + /** + * @type {Set} + */ + this.subdocsLoaded = new Set(); + } + } + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {Transaction} transaction + * @return {boolean} Whether data was written. + */ + const writeUpdateMessageFromTransaction = (encoder, transaction) => { + if (transaction.deleteSet.clients.size === 0 && !any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) { + return false + } + sortAndMergeDeleteSet(transaction.deleteSet); + writeStructsFromTransaction(encoder, transaction); + writeDeleteSet(encoder, transaction.deleteSet); + return true + }; + + /** + * @param {Transaction} transaction + * + * @private + * @function + */ + const nextID = transaction => { + const y = transaction.doc; + return createID(y.clientID, getState(y.store, y.clientID)) + }; + + /** + * If `type.parent` was added in current transaction, `type` technically + * did not change, it was just added and we should not fire events for `type`. + * + * @param {Transaction} transaction + * @param {AbstractType} type + * @param {string|null} parentSub + */ + const addChangedTypeToTransaction = (transaction, type, parentSub) => { + const item = type._item; + if (item === null || (item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted)) { + setIfUndefined(transaction.changed, type, create$4).add(parentSub); + } + }; + + /** + * @param {Array} structs + * @param {number} pos + */ + const tryToMergeWithLeft = (structs, pos) => { + const left = structs[pos - 1]; + const right = structs[pos]; + if (left.deleted === right.deleted && left.constructor === right.constructor) { + if (left.mergeWith(right)) { + structs.splice(pos, 1); + if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType} */ (right.parent)._map.get(right.parentSub) === right) { + /** @type {AbstractType} */ (right.parent)._map.set(right.parentSub, /** @type {Item} */ (left)); + } + } + } + }; + + /** + * @param {DeleteSet} ds + * @param {StructStore} store + * @param {function(Item):boolean} gcFilter + */ + const tryGcDeleteSet = (ds, store, gcFilter) => { + for (const [client, deleteItems] of ds.clients.entries()) { + const structs = /** @type {Array} */ (store.clients.get(client)); + for (let di = deleteItems.length - 1; di >= 0; di--) { + const deleteItem = deleteItems[di]; + const endDeleteItemClock = deleteItem.clock + deleteItem.len; + for ( + let si = findIndexSS(structs, deleteItem.clock), struct = structs[si]; + si < structs.length && struct.id.clock < endDeleteItemClock; + struct = structs[++si] + ) { + const struct = structs[si]; + if (deleteItem.clock + deleteItem.len <= struct.id.clock) { + break + } + if (struct instanceof Item && struct.deleted && !struct.keep && gcFilter(struct)) { + struct.gc(store, false); + } + } + } + } + }; + + /** + * @param {DeleteSet} ds + * @param {StructStore} store + */ + const tryMergeDeleteSet = (ds, store) => { + // try to merge deleted / gc'd items + // merge from right to left for better efficiecy and so we don't miss any merge targets + ds.clients.forEach((deleteItems, client) => { + const structs = /** @type {Array} */ (store.clients.get(client)); + for (let di = deleteItems.length - 1; di >= 0; di--) { + const deleteItem = deleteItems[di]; + // start with merging the item next to the last deleted item + const mostRightIndexToCheck = min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1)); + for ( + let si = mostRightIndexToCheck, struct = structs[si]; + si > 0 && struct.id.clock >= deleteItem.clock; + struct = structs[--si] + ) { + tryToMergeWithLeft(structs, si); + } + } + }); + }; + + /** + * @param {DeleteSet} ds + * @param {StructStore} store + * @param {function(Item):boolean} gcFilter + */ + const tryGc = (ds, store, gcFilter) => { + tryGcDeleteSet(ds, store, gcFilter); + tryMergeDeleteSet(ds, store); + }; + + /** + * @param {Array} transactionCleanups + * @param {number} i + */ + const cleanupTransactions = (transactionCleanups, i) => { + if (i < transactionCleanups.length) { + const transaction = transactionCleanups[i]; + const doc = transaction.doc; + const store = doc.store; + const ds = transaction.deleteSet; + const mergeStructs = transaction._mergeStructs; + try { + sortAndMergeDeleteSet(ds); + transaction.afterState = getStateVector(transaction.doc.store); + doc._transaction = null; + doc.emit('beforeObserverCalls', [transaction, doc]); + /** + * An array of event callbacks. + * + * Each callback is called even if the other ones throw errors. + * + * @type {Array} + */ + const fs = []; + // observe events on changed types + transaction.changed.forEach((subs, itemtype) => + fs.push(() => { + if (itemtype._item === null || !itemtype._item.deleted) { + itemtype._callObserver(transaction, subs); + } + }) + ); + fs.push(() => { + // deep observe events + transaction.changedParentTypes.forEach((events, type) => + fs.push(() => { + // We need to think about the possibility that the user transforms the + // Y.Doc in the event. + if (type._item === null || !type._item.deleted) { + events = events + .filter(event => + event.target._item === null || !event.target._item.deleted + ); + events + .forEach(event => { + event.currentTarget = type; + }); + // sort events by path length so that top-level events are fired first. + events + .sort((event1, event2) => event1.path.length - event2.path.length); + // We don't need to check for events.length + // because we know it has at least one element + callEventHandlerListeners(type._dEH, events, transaction); + } + }) + ); + fs.push(() => doc.emit('afterTransaction', [transaction, doc])); + }); + callAll(fs, []); + } finally { + // Replace deleted items with ItemDeleted / GC. + // This is where content is actually remove from the Yjs Doc. + if (doc.gc) { + tryGcDeleteSet(ds, store, doc.gcFilter); + } + tryMergeDeleteSet(ds, store); + + // on all affected store.clients props, try to merge + transaction.afterState.forEach((clock, client) => { + const beforeClock = transaction.beforeState.get(client) || 0; + if (beforeClock !== clock) { + const structs = /** @type {Array} */ (store.clients.get(client)); + // we iterate from right to left so we can safely remove entries + const firstChangePos = max(findIndexSS(structs, beforeClock), 1); + for (let i = structs.length - 1; i >= firstChangePos; i--) { + tryToMergeWithLeft(structs, i); + } + } + }); + // try to merge mergeStructs + // @todo: it makes more sense to transform mergeStructs to a DS, sort it, and merge from right to left + // but at the moment DS does not handle duplicates + for (let i = 0; i < mergeStructs.length; i++) { + const { client, clock } = mergeStructs[i].id; + const structs = /** @type {Array} */ (store.clients.get(client)); + const replacedStructPos = findIndexSS(structs, clock); + if (replacedStructPos + 1 < structs.length) { + tryToMergeWithLeft(structs, replacedStructPos + 1); + } + if (replacedStructPos > 0) { + tryToMergeWithLeft(structs, replacedStructPos); + } + } + if (!transaction.local && transaction.afterState.get(doc.clientID) !== transaction.beforeState.get(doc.clientID)) { + doc.clientID = generateNewClientId(); + print(ORANGE, BOLD, '[yjs] ', UNBOLD, RED, 'Changed the client-id because another client seems to be using it.'); + } + // @todo Merge all the transactions into one and provide send the data as a single update message + doc.emit('afterTransactionCleanup', [transaction, doc]); + if (doc._observers.has('update')) { + const encoder = new DefaultUpdateEncoder(); + const hasContent = writeUpdateMessageFromTransaction(encoder, transaction); + if (hasContent) { + doc.emit('update', [encoder.toUint8Array(), transaction.origin, doc]); + } + } + if (doc._observers.has('updateV2')) { + const encoder = new UpdateEncoderV2(); + const hasContent = writeUpdateMessageFromTransaction(encoder, transaction); + if (hasContent) { + doc.emit('updateV2', [encoder.toUint8Array(), transaction.origin, doc]); + } + } + transaction.subdocsAdded.forEach(subdoc => doc.subdocs.add(subdoc)); + transaction.subdocsRemoved.forEach(subdoc => doc.subdocs.delete(subdoc)); + + doc.emit('subdocs', [{ loaded: transaction.subdocsLoaded, added: transaction.subdocsAdded, removed: transaction.subdocsRemoved }]); + transaction.subdocsRemoved.forEach(subdoc => subdoc.destroy()); + + if (transactionCleanups.length <= i + 1) { + doc._transactionCleanups = []; + doc.emit('afterAllTransactions', [doc, transactionCleanups]); + } else { + cleanupTransactions(transactionCleanups, i + 1); + } + } + } + }; + + /** + * Implements the functionality of `y.transact(()=>{..})` + * + * @param {Doc} doc + * @param {function(Transaction):void} f + * @param {any} [origin=true] + * + * @function + */ + const transact = (doc, f, origin = null, local = true) => { + const transactionCleanups = doc._transactionCleanups; + let initialCall = false; + if (doc._transaction === null) { + initialCall = true; + doc._transaction = new Transaction(doc, origin, local); + transactionCleanups.push(doc._transaction); + if (transactionCleanups.length === 1) { + doc.emit('beforeAllTransactions', [doc]); + } + doc.emit('beforeTransaction', [doc._transaction, doc]); + } + try { + f(doc._transaction); + } finally { + if (initialCall && transactionCleanups[0] === doc._transaction) { + // The first transaction ended, now process observer calls. + // Observer call may create new transactions for which we need to call the observers and do cleanup. + // We don't want to nest these calls, so we execute these calls one after + // another. + // Also we need to ensure that all cleanups are called, even if the + // observes throw errors. + // This file is full of hacky try {} finally {} blocks to ensure that an + // event can throw errors and also that the cleanup is called. + cleanupTransactions(transactionCleanups, 0); + } + } + }; + + class StackItem { + /** + * @param {DeleteSet} ds + * @param {Map} beforeState + * @param {Map} afterState + */ + constructor (ds, beforeState, afterState) { + this.ds = ds; + this.beforeState = beforeState; + this.afterState = afterState; + /** + * Use this to save and restore metadata like selection range + */ + this.meta = new Map(); + } + } + + /** + * @param {UndoManager} undoManager + * @param {Array} stack + * @param {string} eventType + * @return {StackItem?} + */ + const popStackItem = (undoManager, stack, eventType) => { + /** + * Whether a change happened + * @type {StackItem?} + */ + let result = null; + const doc = undoManager.doc; + const scope = undoManager.scope; + transact(doc, transaction => { + while (stack.length > 0 && result === null) { + const store = doc.store; + const stackItem = /** @type {StackItem} */ (stack.pop()); + /** + * @type {Set} + */ + const itemsToRedo = new Set(); + /** + * @type {Array} + */ + const itemsToDelete = []; + let performedChange = false; + stackItem.afterState.forEach((endClock, client) => { + const startClock = stackItem.beforeState.get(client) || 0; + const len = endClock - startClock; + // @todo iterateStructs should not need the structs parameter + const structs = /** @type {Array} */ (store.clients.get(client)); + if (startClock !== endClock) { + // make sure structs don't overlap with the range of created operations [stackItem.start, stackItem.start + stackItem.end) + // this must be executed before deleted structs are iterated. + getItemCleanStart(transaction, createID(client, startClock)); + if (endClock < getState(doc.store, client)) { + getItemCleanStart(transaction, createID(client, endClock)); + } + iterateStructs(transaction, structs, startClock, len, struct => { + if (struct instanceof Item) { + if (struct.redone !== null) { + let { item, diff } = followRedone(store, struct.id); + if (diff > 0) { + item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff)); + } + if (item.length > len) { + getItemCleanStart(transaction, createID(item.id.client, endClock)); + } + struct = item; + } + if (!struct.deleted && scope.some(type => isParentOf(type, /** @type {Item} */ (struct)))) { + itemsToDelete.push(struct); + } + } + }); + } + }); + iterateDeletedStructs(transaction, stackItem.ds, struct => { + const id = struct.id; + const clock = id.clock; + const client = id.client; + const startClock = stackItem.beforeState.get(client) || 0; + const endClock = stackItem.afterState.get(client) || 0; + if ( + struct instanceof Item && + scope.some(type => isParentOf(type, struct)) && + // Never redo structs in [stackItem.start, stackItem.start + stackItem.end) because they were created and deleted in the same capture interval. + !(clock >= startClock && clock < endClock) + ) { + itemsToRedo.add(struct); + } + }); + itemsToRedo.forEach(struct => { + performedChange = redoItem(transaction, struct, itemsToRedo) !== null || performedChange; + }); + // We want to delete in reverse order so that children are deleted before + // parents, so we have more information available when items are filtered. + for (let i = itemsToDelete.length - 1; i >= 0; i--) { + const item = itemsToDelete[i]; + if (undoManager.deleteFilter(item)) { + item.delete(transaction); + performedChange = true; + } + } + result = stackItem; + if (result != null) { + undoManager.emit('stack-item-popped', [{ stackItem: result, type: eventType }, undoManager]); + } + } + transaction.changed.forEach((subProps, type) => { + // destroy search marker if necessary + if (subProps.has(null) && type._searchMarker) { + type._searchMarker.length = 0; + } + }); + }, undoManager); + return result + }; + + /** + * @typedef {Object} UndoManagerOptions + * @property {number} [UndoManagerOptions.captureTimeout=500] + * @property {function(Item):boolean} [UndoManagerOptions.deleteFilter=()=>true] Sometimes + * it is necessary to filter whan an Undo/Redo operation can delete. If this + * filter returns false, the type/item won't be deleted even it is in the + * undo/redo scope. + * @property {Set} [UndoManagerOptions.trackedOrigins=new Set([null])] + */ + + /** + * Fires 'stack-item-added' event when a stack item was added to either the undo- or + * the redo-stack. You may store additional stack information via the + * metadata property on `event.stackItem.meta` (it is a `Map` of metadata properties). + * Fires 'stack-item-popped' event when a stack item was popped from either the + * undo- or the redo-stack. You may restore the saved stack information from `event.stackItem.meta`. + * + * @extends {Observable<'stack-item-added'|'stack-item-popped'>} + */ + class UndoManager extends Observable { + /** + * @param {AbstractType|Array>} typeScope Accepts either a single type, or an array of types + * @param {UndoManagerOptions} options + */ + constructor (typeScope, { captureTimeout = 500, deleteFilter = () => true, trackedOrigins = new Set([null]) } = {}) { + super(); + this.scope = typeScope instanceof Array ? typeScope : [typeScope]; + this.deleteFilter = deleteFilter; + trackedOrigins.add(this); + this.trackedOrigins = trackedOrigins; + /** + * @type {Array} + */ + this.undoStack = []; + /** + * @type {Array} + */ + this.redoStack = []; + /** + * Whether the client is currently undoing (calling UndoManager.undo) + * + * @type {boolean} + */ + this.undoing = false; + this.redoing = false; + this.doc = /** @type {Doc} */ (this.scope[0].doc); + this.lastChange = 0; + this.doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => { + // Only track certain transactions + if (!this.scope.some(type => transaction.changedParentTypes.has(type)) || (!this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor)))) { + return + } + const undoing = this.undoing; + const redoing = this.redoing; + const stack = undoing ? this.redoStack : this.undoStack; + if (undoing) { + this.stopCapturing(); // next undo should not be appended to last stack item + } else if (!redoing) { + // neither undoing nor redoing: delete redoStack + this.redoStack = []; + } + const beforeState = transaction.beforeState; + const afterState = transaction.afterState; + const now = getUnixTime(); + if (now - this.lastChange < captureTimeout && stack.length > 0 && !undoing && !redoing) { + // append change to last stack op + const lastOp = stack[stack.length - 1]; + lastOp.ds = mergeDeleteSets([lastOp.ds, transaction.deleteSet]); + lastOp.afterState = afterState; + } else { + // create a new stack op + stack.push(new StackItem(transaction.deleteSet, beforeState, afterState)); + } + if (!undoing && !redoing) { + this.lastChange = now; + } + // make sure that deleted structs are not gc'd + iterateDeletedStructs(transaction, transaction.deleteSet, /** @param {Item|GC} item */ item => { + if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) { + keepItem(item, true); + } + }); + this.emit('stack-item-added', [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? 'redo' : 'undo' }, this]); + }); + } + + clear () { + this.doc.transact(transaction => { + /** + * @param {StackItem} stackItem + */ + const clearItem = stackItem => { + iterateDeletedStructs(transaction, stackItem.ds, item => { + if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) { + keepItem(item, false); + } + }); + }; + this.undoStack.forEach(clearItem); + this.redoStack.forEach(clearItem); + }); + this.undoStack = []; + this.redoStack = []; + } + + /** + * UndoManager merges Undo-StackItem if they are created within time-gap + * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next + * StackItem won't be merged. + * + * + * @example + * // without stopCapturing + * ytext.insert(0, 'a') + * ytext.insert(1, 'b') + * um.undo() + * ytext.toString() // => '' (note that 'ab' was removed) + * // with stopCapturing + * ytext.insert(0, 'a') + * um.stopCapturing() + * ytext.insert(0, 'b') + * um.undo() + * ytext.toString() // => 'a' (note that only 'b' was removed) + * + */ + stopCapturing () { + this.lastChange = 0; + } + + /** + * Undo last changes on type. + * + * @return {StackItem?} Returns StackItem if a change was applied + */ + undo () { + this.undoing = true; + let res; + try { + res = popStackItem(this, this.undoStack, 'undo'); + } finally { + this.undoing = false; + } + return res + } + + /** + * Redo last undo operation. + * + * @return {StackItem?} Returns StackItem if a change was applied + */ + redo () { + this.redoing = true; + let res; + try { + res = popStackItem(this, this.redoStack, 'redo'); + } finally { + this.redoing = false; + } + return res + } + } + + /** + * YEvent describes the changes on a YType. + */ + class YEvent { + /** + * @param {AbstractType} target The changed type. + * @param {Transaction} transaction + */ + constructor (target, transaction) { + /** + * The type on which this event was created on. + * @type {AbstractType} + */ + this.target = target; + /** + * The current target on which the observe callback is called. + * @type {AbstractType} + */ + this.currentTarget = target; + /** + * The transaction that triggered this event. + * @type {Transaction} + */ + this.transaction = transaction; + /** + * @type {Object|null} + */ + this._changes = null; + } + + /** + * Computes the path from `y` to the changed type. + * + * The following property holds: + * @example + * let type = y + * event.path.forEach(dir => { + * type = type.get(dir) + * }) + * type === event.target // => true + */ + get path () { + // @ts-ignore _item is defined because target is integrated + return getPathTo(this.currentTarget, this.target) + } + + /** + * Check if a struct is deleted by this event. + * + * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. + * + * @param {AbstractStruct} struct + * @return {boolean} + */ + deletes (struct) { + return isDeleted(this.transaction.deleteSet, struct.id) + } + + /** + * Check if a struct is added by this event. + * + * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. + * + * @param {AbstractStruct} struct + * @return {boolean} + */ + adds (struct) { + return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0) + } + + /** + * @return {{added:Set,deleted:Set,keys:Map,delta:Array<{insert:Array}|{delete:number}|{retain:number}>}} + */ + get changes () { + let changes = this._changes; + if (changes === null) { + const target = this.target; + const added = create$4(); + const deleted = create$4(); + /** + * @type {Array<{insert:Array}|{delete:number}|{retain:number}>} + */ + const delta = []; + /** + * @type {Map} + */ + const keys = new Map(); + changes = { + added, deleted, delta, keys + }; + const changed = /** @type Set */ (this.transaction.changed.get(target)); + if (changed.has(null)) { + /** + * @type {any} + */ + let lastOp = null; + const packOp = () => { + if (lastOp) { + delta.push(lastOp); + } + }; + for (let item = target._start; item !== null; item = item.right) { + if (item.deleted) { + if (this.deletes(item) && !this.adds(item)) { + if (lastOp === null || lastOp.delete === undefined) { + packOp(); + lastOp = { delete: 0 }; + } + lastOp.delete += item.length; + deleted.add(item); + } // else nop + } else { + if (this.adds(item)) { + if (lastOp === null || lastOp.insert === undefined) { + packOp(); + lastOp = { insert: [] }; + } + lastOp.insert = lastOp.insert.concat(item.content.getContent()); + added.add(item); + } else { + if (lastOp === null || lastOp.retain === undefined) { + packOp(); + lastOp = { retain: 0 }; + } + lastOp.retain += item.length; + } + } + } + if (lastOp !== null && lastOp.retain === undefined) { + packOp(); + } + } + changed.forEach(key => { + if (key !== null) { + const item = /** @type {Item} */ (target._map.get(key)); + /** + * @type {'delete' | 'add' | 'update'} + */ + let action; + let oldValue; + if (this.adds(item)) { + let prev = item.left; + while (prev !== null && this.adds(prev)) { + prev = prev.left; + } + if (this.deletes(item)) { + if (prev !== null && this.deletes(prev)) { + action = 'delete'; + oldValue = last(prev.content.getContent()); + } else { + return + } + } else { + if (prev !== null && this.deletes(prev)) { + action = 'update'; + oldValue = last(prev.content.getContent()); + } else { + action = 'add'; + oldValue = undefined; + } + } + } else { + if (this.deletes(item)) { + action = 'delete'; + oldValue = last(/** @type {Item} */ item.content.getContent()); + } else { + return // nop + } + } + keys.set(key, { action, oldValue }); + } + }); + this._changes = changes; + } + return /** @type {any} */ (changes) + } + } + + /** + * Compute the path from this type to the specified target. + * + * @example + * // `child` should be accessible via `type.get(path[0]).get(path[1])..` + * const path = type.getPathTo(child) + * // assuming `type instanceof YArray` + * console.log(path) // might look like => [2, 'key1'] + * child === type.get(path[0]).get(path[1]) + * + * @param {AbstractType} parent + * @param {AbstractType} child target + * @return {Array} Path to the target + * + * @private + * @function + */ + const getPathTo = (parent, child) => { + const path = []; + while (child._item !== null && child !== parent) { + if (child._item.parentSub !== null) { + // parent is map-ish + path.unshift(child._item.parentSub); + } else { + // parent is array-ish + let i = 0; + let c = /** @type {AbstractType} */ (child._item.parent)._start; + while (c !== child._item && c !== null) { + if (!c.deleted) { + i++; + } + c = c.right; + } + path.unshift(i); + } + child = /** @type {AbstractType} */ (child._item.parent); + } + return path + }; + + /** + * Utility module to create and manipulate Iterators. + * + * @module iterator + */ + + /** + * @template T + * @param {function():IteratorResult} next + * @return {IterableIterator} + */ + const createIterator = next => ({ + /** + * @return {IterableIterator} + */ + [Symbol.iterator] () { + return this + }, + // @ts-ignore + next + }); + + /** + * @template T + * @param {Iterator} iterator + * @param {function(T):boolean} filter + */ + const iteratorFilter = (iterator, filter) => createIterator(() => { + let res; + do { + res = iterator.next(); + } while (!res.done && !filter(res.value)) + return res + }); + + /** + * @template T,M + * @param {Iterator} iterator + * @param {function(T):M} fmap + */ + const iteratorMap = (iterator, fmap) => createIterator(() => { + const { done, value } = iterator.next(); + return { done, value: done ? undefined : fmap(value) } + }); + + const maxSearchMarker = 80; + + /** + * A unique timestamp that identifies each marker. + * + * Time is relative,.. this is more like an ever-increasing clock. + * + * @type {number} + */ + let globalSearchMarkerTimestamp = 0; + + class ArraySearchMarker { + /** + * @param {Item} p + * @param {number} index + */ + constructor (p, index) { + p.marker = true; + this.p = p; + this.index = index; + this.timestamp = globalSearchMarkerTimestamp++; + } + } + + /** + * @param {ArraySearchMarker} marker + */ + const refreshMarkerTimestamp = marker => { marker.timestamp = globalSearchMarkerTimestamp++; }; + + /** + * This is rather complex so this function is the only thing that should overwrite a marker + * + * @param {ArraySearchMarker} marker + * @param {Item} p + * @param {number} index + */ + const overwriteMarker = (marker, p, index) => { + marker.p.marker = false; + marker.p = p; + p.marker = true; + marker.index = index; + marker.timestamp = globalSearchMarkerTimestamp++; + }; + + /** + * @param {Array} searchMarker + * @param {Item} p + * @param {number} index + */ + const markPosition = (searchMarker, p, index) => { + if (searchMarker.length >= maxSearchMarker) { + // override oldest marker (we don't want to create more objects) + const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b); + overwriteMarker(marker, p, index); + return marker + } else { + // create new marker + const pm = new ArraySearchMarker(p, index); + searchMarker.push(pm); + return pm + } + }; + + /** + * Search marker help us to find positions in the associative array faster. + * + * They speed up the process of finding a position without much bookkeeping. + * + * A maximum of `maxSearchMarker` objects are created. + * + * This function always returns a refreshed marker (updated timestamp) + * + * @param {AbstractType} yarray + * @param {number} index + */ + const findMarker = (yarray, index) => { + if (yarray._start === null || index === 0 || yarray._searchMarker === null) { + return null + } + const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => abs(index - a.index) < abs(index - b.index) ? a : b); + let p = yarray._start; + let pindex = 0; + if (marker !== null) { + p = marker.p; + pindex = marker.index; + refreshMarkerTimestamp(marker); // we used it, we might need to use it again + } + // iterate to right if possible + while (p.right !== null && pindex < index) { + if (!p.deleted && p.countable) { + if (index < pindex + p.length) { + break + } + pindex += p.length; + } + p = p.right; + } + // iterate to left if necessary (might be that pindex > index) + while (p.left !== null && pindex > index) { + p = p.left; + if (!p.deleted && p.countable) { + pindex -= p.length; + } + } + // we want to make sure that p can't be merged with left, because that would screw up everything + // in that cas just return what we have (it is most likely the best marker anyway) + // iterate to left until p can't be merged with left + while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) { + p = p.left; + if (!p.deleted && p.countable) { + pindex -= p.length; + } + } + + // @todo remove! + // assure position + // { + // let start = yarray._start + // let pos = 0 + // while (start !== p) { + // if (!start.deleted && start.countable) { + // pos += start.length + // } + // start = /** @type {Item} */ (start.right) + // } + // if (pos !== pindex) { + // debugger + // throw new Error('Gotcha position fail!') + // } + // } + // if (marker) { + // if (window.lengthes == null) { + // window.lengthes = [] + // window.getLengthes = () => window.lengthes.sort((a, b) => a - b) + // } + // window.lengthes.push(marker.index - pindex) + // console.log('distance', marker.index - pindex, 'len', p && p.parent.length) + // } + if (marker !== null && abs(marker.index - pindex) < /** @type {YText|YArray} */ (p.parent).length / maxSearchMarker) { + // adjust existing marker + overwriteMarker(marker, p, pindex); + return marker + } else { + // create new marker + return markPosition(yarray._searchMarker, p, pindex) + } + }; + + /** + * Update markers when a change happened. + * + * This should be called before doing a deletion! + * + * @param {Array} searchMarker + * @param {number} index + * @param {number} len If insertion, len is positive. If deletion, len is negative. + */ + const updateMarkerChanges = (searchMarker, index, len) => { + for (let i = searchMarker.length - 1; i >= 0; i--) { + const m = searchMarker[i]; + if (len > 0) { + /** + * @type {Item|null} + */ + let p = m.p; + p.marker = false; + // Ideally we just want to do a simple position comparison, but this will only work if + // search markers don't point to deleted items for formats. + // Iterate marker to prev undeleted countable position so we know what to do when updating a position + while (p && (p.deleted || !p.countable)) { + p = p.left; + if (p && !p.deleted && p.countable) { + // adjust position. the loop should break now + m.index -= p.length; + } + } + if (p === null || p.marker === true) { + // remove search marker if updated position is null or if position is already marked + searchMarker.splice(i, 1); + continue + } + m.p = p; + p.marker = true; + } + if (index < m.index || (len > 0 && index === m.index)) { // a simple index <= m.index check would actually suffice + m.index = max(index, m.index + len); + } + } + }; + + /** + * Accumulate all (list) children of a type and return them as an Array. + * + * @param {AbstractType} t + * @return {Array} + */ + const getTypeChildren = t => { + let s = t._start; + const arr = []; + while (s) { + arr.push(s); + s = s.right; + } + return arr + }; + + /** + * Call event listeners with an event. This will also add an event to all + * parents (for `.observeDeep` handlers). + * + * @template EventType + * @param {AbstractType} type + * @param {Transaction} transaction + * @param {EventType} event + */ + const callTypeObservers = (type, transaction, event) => { + const changedType = type; + const changedParentTypes = transaction.changedParentTypes; + while (true) { + // @ts-ignore + setIfUndefined(changedParentTypes, type, () => []).push(event); + if (type._item === null) { + break + } + type = /** @type {AbstractType} */ (type._item.parent); + } + callEventHandlerListeners(changedType._eH, event, transaction); + }; + + /** + * @template EventType + * Abstract Yjs Type class + */ + class AbstractType { + constructor () { + /** + * @type {Item|null} + */ + this._item = null; + /** + * @type {Map} + */ + this._map = new Map(); + /** + * @type {Item|null} + */ + this._start = null; + /** + * @type {Doc|null} + */ + this.doc = null; + this._length = 0; + /** + * Event handlers + * @type {EventHandler} + */ + this._eH = createEventHandler(); + /** + * Deep event handlers + * @type {EventHandler,Transaction>} + */ + this._dEH = createEventHandler(); + /** + * @type {null | Array} + */ + this._searchMarker = null; + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item|null} item + */ + _integrate (y, item) { + this.doc = y; + this._item = item; + } + + /** + * @return {AbstractType} + */ + _copy () { + throw methodUnimplemented() + } + + /** + * @param {AbstractUpdateEncoder} encoder + */ + _write (encoder) { } + + /** + * The first non-deleted item + */ + get _first () { + let n = this._start; + while (n !== null && n.deleted) { + n = n.right; + } + return n + } + + /** + * Creates YEvent and calls all type observers. + * Must be implemented by each type. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + if (!transaction.local && this._searchMarker) { + this._searchMarker.length = 0; + } + } + + /** + * Observe all events that are created on this type. + * + * @param {function(EventType, Transaction):void} f Observer function + */ + observe (f) { + addEventHandlerListener(this._eH, f); + } + + /** + * Observe all events that are created by this type and its children. + * + * @param {function(Array,Transaction):void} f Observer function + */ + observeDeep (f) { + addEventHandlerListener(this._dEH, f); + } + + /** + * Unregister an observer function. + * + * @param {function(EventType,Transaction):void} f Observer function + */ + unobserve (f) { + removeEventHandlerListener(this._eH, f); + } + + /** + * Unregister an observer function. + * + * @param {function(Array,Transaction):void} f Observer function + */ + unobserveDeep (f) { + removeEventHandlerListener(this._dEH, f); + } + + /** + * @abstract + * @return {any} + */ + toJSON () {} + } + + /** + * @param {AbstractType} type + * @return {Array} + * + * @private + * @function + */ + const typeListToArray = type => { + const cs = []; + let n = type._start; + while (n !== null) { + if (n.countable && !n.deleted) { + const c = n.content.getContent(); + for (let i = 0; i < c.length; i++) { + cs.push(c[i]); + } + } + n = n.right; + } + return cs + }; + + /** + * @param {AbstractType} type + * @param {Snapshot} snapshot + * @return {Array} + * + * @private + * @function + */ + const typeListToArraySnapshot = (type, snapshot) => { + const cs = []; + let n = type._start; + while (n !== null) { + if (n.countable && isVisible(n, snapshot)) { + const c = n.content.getContent(); + for (let i = 0; i < c.length; i++) { + cs.push(c[i]); + } + } + n = n.right; + } + return cs + }; + + /** + * Executes a provided function on once on overy element of this YArray. + * + * @param {AbstractType} type + * @param {function(any,number,any):void} f A function to execute on every element of this YArray. + * + * @private + * @function + */ + const typeListForEach = (type, f) => { + let index = 0; + let n = type._start; + while (n !== null) { + if (n.countable && !n.deleted) { + const c = n.content.getContent(); + for (let i = 0; i < c.length; i++) { + f(c[i], index++, type); + } + } + n = n.right; + } + }; + + /** + * @template C,R + * @param {AbstractType} type + * @param {function(C,number,AbstractType):R} f + * @return {Array} + * + * @private + * @function + */ + const typeListMap = (type, f) => { + /** + * @type {Array} + */ + const result = []; + typeListForEach(type, (c, i) => { + result.push(f(c, i, type)); + }); + return result + }; + + /** + * @param {AbstractType} type + * @return {IterableIterator} + * + * @private + * @function + */ + const typeListCreateIterator = type => { + let n = type._start; + /** + * @type {Array|null} + */ + let currentContent = null; + let currentContentIndex = 0; + return { + [Symbol.iterator] () { + return this + }, + next: () => { + // find some content + if (currentContent === null) { + while (n !== null && n.deleted) { + n = n.right; + } + // check if we reached the end, no need to check currentContent, because it does not exist + if (n === null) { + return { + done: true, + value: undefined + } + } + // we found n, so we can set currentContent + currentContent = n.content.getContent(); + currentContentIndex = 0; + n = n.right; // we used the content of n, now iterate to next + } + const value = currentContent[currentContentIndex++]; + // check if we need to empty currentContent + if (currentContent.length <= currentContentIndex) { + currentContent = null; + } + return { + done: false, + value + } + } + } + }; + + /** + * Executes a provided function on once on overy element of this YArray. + * Operates on a snapshotted state of the document. + * + * @param {AbstractType} type + * @param {function(any,number,AbstractType):void} f A function to execute on every element of this YArray. + * @param {Snapshot} snapshot + * + * @private + * @function + */ + const typeListForEachSnapshot = (type, f, snapshot) => { + let index = 0; + let n = type._start; + while (n !== null) { + if (n.countable && isVisible(n, snapshot)) { + const c = n.content.getContent(); + for (let i = 0; i < c.length; i++) { + f(c[i], index++, type); + } + } + n = n.right; + } + }; + + /** + * @param {AbstractType} type + * @param {number} index + * @return {any} + * + * @private + * @function + */ + const typeListGet = (type, index) => { + const marker = findMarker(type, index); + let n = type._start; + if (marker !== null) { + n = marker.p; + index -= marker.index; + } + for (; n !== null; n = n.right) { + if (!n.deleted && n.countable) { + if (index < n.length) { + return n.content.getContent()[index] + } + index -= n.length; + } + } + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {Item?} referenceItem + * @param {Array|Array|boolean|number|string|Uint8Array>} content + * + * @private + * @function + */ + const typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => { + let left = referenceItem; + const doc = transaction.doc; + const ownClientId = doc.clientID; + const store = doc.store; + const right = referenceItem === null ? parent._start : referenceItem.right; + /** + * @type {Array|number>} + */ + let jsonContent = []; + const packJsonContent = () => { + if (jsonContent.length > 0) { + left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent)); + left.integrate(transaction, 0); + jsonContent = []; + } + }; + content.forEach(c => { + switch (c.constructor) { + case Number: + case Object: + case Boolean: + case Array: + case String: + jsonContent.push(c); + break + default: + packJsonContent(); + switch (c.constructor) { + case Uint8Array: + case ArrayBuffer: + left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array(/** @type {Uint8Array} */ (c)))); + left.integrate(transaction, 0); + break + case Doc: + left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc(/** @type {Doc} */ (c))); + left.integrate(transaction, 0); + break + default: + if (c instanceof AbstractType) { + left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c)); + left.integrate(transaction, 0); + } else { + throw new Error('Unexpected content type in insert operation') + } + } + } + }); + packJsonContent(); + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {number} index + * @param {Array|Array|number|string|Uint8Array>} content + * + * @private + * @function + */ + const typeListInsertGenerics = (transaction, parent, index, content) => { + if (index === 0) { + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, index, content.length); + } + return typeListInsertGenericsAfter(transaction, parent, null, content) + } + const startIndex = index; + const marker = findMarker(parent, index); + let n = parent._start; + if (marker !== null) { + n = marker.p; + index -= marker.index; + // we need to iterate one to the left so that the algorithm works + if (index === 0) { + // @todo refactor this as it actually doesn't consider formats + n = n.prev; // important! get the left undeleted item so that we can actually decrease index + index += (n && n.countable && !n.deleted) ? n.length : 0; + } + } + for (; n !== null; n = n.right) { + if (!n.deleted && n.countable) { + if (index <= n.length) { + if (index < n.length) { + // insert in-between + getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index)); + } + break + } + index -= n.length; + } + } + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, startIndex, content.length); + } + return typeListInsertGenericsAfter(transaction, parent, n, content) + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {number} index + * @param {number} length + * + * @private + * @function + */ + const typeListDelete = (transaction, parent, index, length) => { + if (length === 0) { return } + const startIndex = index; + const startLength = length; + const marker = findMarker(parent, index); + let n = parent._start; + if (marker !== null) { + n = marker.p; + index -= marker.index; + } + // compute the first item to be deleted + for (; n !== null && index > 0; n = n.right) { + if (!n.deleted && n.countable) { + if (index < n.length) { + getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index)); + } + index -= n.length; + } + } + // delete all items until done + while (length > 0 && n !== null) { + if (!n.deleted) { + if (length < n.length) { + getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length)); + } + n.delete(transaction); + length -= n.length; + } + n = n.right; + } + if (length > 0) { + throw create$5('array length exceeded') + } + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, startIndex, -startLength + length /* in case we remove the above exception */); + } + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {string} key + * + * @private + * @function + */ + const typeMapDelete = (transaction, parent, key) => { + const c = parent._map.get(key); + if (c !== undefined) { + c.delete(transaction); + } + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {string} key + * @param {Object|number|Array|string|Uint8Array|AbstractType} value + * + * @private + * @function + */ + const typeMapSet = (transaction, parent, key, value) => { + const left = parent._map.get(key) || null; + const doc = transaction.doc; + const ownClientId = doc.clientID; + let content; + if (value == null) { + content = new ContentAny([value]); + } else { + switch (value.constructor) { + case Number: + case Object: + case Boolean: + case Array: + case String: + content = new ContentAny([value]); + break + case Uint8Array: + content = new ContentBinary(/** @type {Uint8Array} */ (value)); + break + case Doc: + content = new ContentDoc(/** @type {Doc} */ (value)); + break + default: + if (value instanceof AbstractType) { + content = new ContentType(value); + } else { + throw new Error('Unexpected content type') + } + } + } + new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0); + }; + + /** + * @param {AbstractType} parent + * @param {string} key + * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined} + * + * @private + * @function + */ + const typeMapGet = (parent, key) => { + const val = parent._map.get(key); + return val !== undefined && !val.deleted ? val.content.getContent()[val.length - 1] : undefined + }; + + /** + * @param {AbstractType} parent + * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined>} + * + * @private + * @function + */ + const typeMapGetAll = (parent) => { + /** + * @type {Object} + */ + const res = {}; + parent._map.forEach((value, key) => { + if (!value.deleted) { + res[key] = value.content.getContent()[value.length - 1]; + } + }); + return res + }; + + /** + * @param {AbstractType} parent + * @param {string} key + * @return {boolean} + * + * @private + * @function + */ + const typeMapHas = (parent, key) => { + const val = parent._map.get(key); + return val !== undefined && !val.deleted + }; + + /** + * @param {AbstractType} parent + * @param {string} key + * @param {Snapshot} snapshot + * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined} + * + * @private + * @function + */ + const typeMapGetSnapshot = (parent, key, snapshot) => { + let v = parent._map.get(key) || null; + while (v !== null && (!snapshot.sv.has(v.id.client) || v.id.clock >= (snapshot.sv.get(v.id.client) || 0))) { + v = v.left; + } + return v !== null && isVisible(v, snapshot) ? v.content.getContent()[v.length - 1] : undefined + }; + + /** + * @param {Map} map + * @return {IterableIterator>} + * + * @private + * @function + */ + const createMapIterator = map => iteratorFilter(map.entries(), /** @param {any} entry */ entry => !entry[1].deleted); + + /** + * @module YArray + */ + + /** + * Event that describes the changes on a YArray + * @template T + */ + class YArrayEvent extends YEvent { + /** + * @param {YArray} yarray The changed type + * @param {Transaction} transaction The transaction object + */ + constructor (yarray, transaction) { + super(yarray, transaction); + this._transaction = transaction; + } + } + + /** + * A shared Array implementation. + * @template T + * @extends AbstractType> + * @implements {Iterable} + */ + class YArray extends AbstractType { + constructor () { + super(); + /** + * @type {Array?} + * @private + */ + this._prelimContent = []; + /** + * @type {Array} + */ + this._searchMarker = []; + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item); + this.insert(0, /** @type {Array} */ (this._prelimContent)); + this._prelimContent = null; + } + + _copy () { + return new YArray() + } + + get length () { + return this._prelimContent === null ? this._length : this._prelimContent.length + } + + /** + * Creates YArrayEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + super._callObserver(transaction, parentSubs); + callTypeObservers(this, transaction, new YArrayEvent(this, transaction)); + } + + /** + * Inserts new content at an index. + * + * Important: This function expects an array of content. Not just a content + * object. The reason for this "weirdness" is that inserting several elements + * is very efficient when it is done as a single operation. + * + * @example + * // Insert character 'a' at position 0 + * yarray.insert(0, ['a']) + * // Insert numbers 1, 2 at position 1 + * yarray.insert(1, [1, 2]) + * + * @param {number} index The index to insert content at. + * @param {Array} content The array of content + */ + insert (index, content) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListInsertGenerics(transaction, this, index, content); + }); + } else { + /** @type {Array} */ (this._prelimContent).splice(index, 0, ...content); + } + } + + /** + * Appends content to this YArray. + * + * @param {Array} content Array of content to append. + */ + push (content) { + this.insert(this.length, content); + } + + /** + * Preppends content to this YArray. + * + * @param {Array} content Array of content to preppend. + */ + unshift (content) { + this.insert(0, content); + } + + /** + * Deletes elements starting from an index. + * + * @param {number} index Index at which to start deleting elements + * @param {number} length The number of elements to remove. Defaults to 1. + */ + delete (index, length = 1) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListDelete(transaction, this, index, length); + }); + } else { + /** @type {Array} */ (this._prelimContent).splice(index, length); + } + } + + /** + * Returns the i-th element from a YArray. + * + * @param {number} index The index of the element to return from the YArray + * @return {T} + */ + get (index) { + return typeListGet(this, index) + } + + /** + * Transforms this YArray to a JavaScript Array. + * + * @return {Array} + */ + toArray () { + return typeListToArray(this) + } + + /** + * Transforms this Shared Type to a JSON object. + * + * @return {Array} + */ + toJSON () { + return this.map(c => c instanceof AbstractType ? c.toJSON() : c) + } + + /** + * Returns an Array with the result of calling a provided function on every + * element of this YArray. + * + * @template T,M + * @param {function(T,number,YArray):M} f Function that produces an element of the new Array + * @return {Array} A new array with each element being the result of the + * callback function + */ + map (f) { + return typeListMap(this, /** @type {any} */ (f)) + } + + /** + * Executes a provided function on once on overy element of this YArray. + * + * @param {function(T,number,YArray):void} f A function to execute on every element of this YArray. + */ + forEach (f) { + typeListForEach(this, f); + } + + /** + * @return {IterableIterator} + */ + [Symbol.iterator] () { + return typeListCreateIterator(this) + } + + /** + * @param {AbstractUpdateEncoder} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YArrayRefID); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * + * @private + * @function + */ + const readYArray = decoder => new YArray(); + + /** + * @template T + * Event that describes the changes on a YMap. + */ + class YMapEvent extends YEvent { + /** + * @param {YMap} ymap The YArray that changed. + * @param {Transaction} transaction + * @param {Set} subs The keys that changed. + */ + constructor (ymap, transaction, subs) { + super(ymap, transaction); + this.keysChanged = subs; + } + } + + /** + * @template T number|string|Object|Array|Uint8Array + * A shared Map implementation. + * + * @extends AbstractType> + * @implements {Iterable} + */ + class YMap extends AbstractType { + /** + * + * @param {Iterable=} entries - an optional iterable to initialize the YMap + */ + constructor (entries) { + super(); + /** + * @type {Map?} + * @private + */ + this._prelimContent = null; + + if (entries === undefined) { + this._prelimContent = new Map(); + } else { + this._prelimContent = new Map(entries); + } + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item) + ;/** @type {Map} */ (this._prelimContent).forEach((value, key) => { + this.set(key, value); + }); + this._prelimContent = null; + } + + _copy () { + return new YMap() + } + + /** + * Creates YMapEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs)); + } + + /** + * Transforms this Shared Type to a JSON object. + * + * @return {Object} + */ + toJSON () { + /** + * @type {Object} + */ + const map = {}; + this._map.forEach((item, key) => { + if (!item.deleted) { + const v = item.content.getContent()[item.length - 1]; + map[key] = v instanceof AbstractType ? v.toJSON() : v; + } + }); + return map + } + + /** + * Returns the size of the YMap (count of key/value pairs) + * + * @return {number} + */ + get size () { + return [...createMapIterator(this._map)].length + } + + /** + * Returns the keys for each element in the YMap Type. + * + * @return {IterableIterator} + */ + keys () { + return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[0]) + } + + /** + * Returns the values for each element in the YMap Type. + * + * @return {IterableIterator} + */ + values () { + return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[1].content.getContent()[v[1].length - 1]) + } + + /** + * Returns an Iterator of [key, value] pairs + * + * @return {IterableIterator} + */ + entries () { + return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => [v[0], v[1].content.getContent()[v[1].length - 1]]) + } + + /** + * Executes a provided function on once on every key-value pair. + * + * @param {function(T,string,YMap):void} f A function to execute on every element of this YArray. + */ + forEach (f) { + /** + * @type {Object} + */ + const map = {}; + this._map.forEach((item, key) => { + if (!item.deleted) { + f(item.content.getContent()[item.length - 1], key, this); + } + }); + return map + } + + /** + * @return {IterableIterator} + */ + [Symbol.iterator] () { + return this.entries() + } + + /** + * Remove a specified element from this YMap. + * + * @param {string} key The key of the element to remove. + */ + delete (key) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapDelete(transaction, this, key); + }); + } else { + /** @type {Map} */ (this._prelimContent).delete(key); + } + } + + /** + * Adds or updates an element with a specified key and value. + * + * @param {string} key The key of the element to add to this YMap + * @param {T} value The value of the element to add + */ + set (key, value) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapSet(transaction, this, key, value); + }); + } else { + /** @type {Map} */ (this._prelimContent).set(key, value); + } + return value + } + + /** + * Returns a specified element from this YMap. + * + * @param {string} key + * @return {T|undefined} + */ + get (key) { + return /** @type {any} */ (typeMapGet(this, key)) + } + + /** + * Returns a boolean indicating whether the specified key exists or not. + * + * @param {string} key The key to test. + * @return {boolean} + */ + has (key) { + return typeMapHas(this, key) + } + + /** + * @param {AbstractUpdateEncoder} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YMapRefID); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * + * @private + * @function + */ + const readYMap = decoder => new YMap(); + + /** + * @param {any} a + * @param {any} b + * @return {boolean} + */ + const equalAttrs = (a, b) => a === b || (typeof a === 'object' && typeof b === 'object' && a && b && equalFlat(a, b)); + + class ItemTextListPosition { + /** + * @param {Item|null} left + * @param {Item|null} right + * @param {number} index + * @param {Map} currentAttributes + */ + constructor (left, right, index, currentAttributes) { + this.left = left; + this.right = right; + this.index = index; + this.currentAttributes = currentAttributes; + } + + /** + * Only call this if you know that this.right is defined + */ + forward () { + if (this.right === null) { + unexpectedCase(); + } + switch (this.right.content.constructor) { + case ContentEmbed: + case ContentString: + if (!this.right.deleted) { + this.index += this.right.length; + } + break + case ContentFormat: + if (!this.right.deleted) { + updateCurrentAttributes(this.currentAttributes, /** @type {ContentFormat} */ (this.right.content)); + } + break + } + this.left = this.right; + this.right = this.right.right; + } + } + + /** + * @param {Transaction} transaction + * @param {ItemTextListPosition} pos + * @param {number} count steps to move forward + * @return {ItemTextListPosition} + * + * @private + * @function + */ + const findNextPosition = (transaction, pos, count) => { + while (pos.right !== null && count > 0) { + switch (pos.right.content.constructor) { + case ContentEmbed: + case ContentString: + if (!pos.right.deleted) { + if (count < pos.right.length) { + // split right + getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count)); + } + pos.index += pos.right.length; + count -= pos.right.length; + } + break + case ContentFormat: + if (!pos.right.deleted) { + updateCurrentAttributes(pos.currentAttributes, /** @type {ContentFormat} */ (pos.right.content)); + } + break + } + pos.left = pos.right; + pos.right = pos.right.right; + // pos.forward() - we don't forward because that would halve the performance because we already do the checks above + } + return pos + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {number} index + * @return {ItemTextListPosition} + * + * @private + * @function + */ + const findPosition = (transaction, parent, index) => { + const currentAttributes = new Map(); + const marker = findMarker(parent, index); + if (marker) { + const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes); + return findNextPosition(transaction, pos, index - marker.index) + } else { + const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes); + return findNextPosition(transaction, pos, index) + } + }; + + /** + * Negate applied formats + * + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {Map} negatedAttributes + * + * @private + * @function + */ + const insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => { + // check if we really need to remove attributes + while ( + currPos.right !== null && ( + currPos.right.deleted === true || ( + currPos.right.content.constructor === ContentFormat && + equalAttrs(negatedAttributes.get(/** @type {ContentFormat} */ (currPos.right.content).key), /** @type {ContentFormat} */ (currPos.right.content).value) + ) + ) + ) { + if (!currPos.right.deleted) { + negatedAttributes.delete(/** @type {ContentFormat} */ (currPos.right.content).key); + } + currPos.forward(); + } + const doc = transaction.doc; + const ownClientId = doc.clientID; + let left = currPos.left; + const right = currPos.right; + negatedAttributes.forEach((val, key) => { + left = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val)); + left.integrate(transaction, 0); + }); + }; + + /** + * @param {Map} currentAttributes + * @param {ContentFormat} format + * + * @private + * @function + */ + const updateCurrentAttributes = (currentAttributes, format) => { + const { key, value } = format; + if (value === null) { + currentAttributes.delete(key); + } else { + currentAttributes.set(key, value); + } + }; + + /** + * @param {ItemTextListPosition} currPos + * @param {Object} attributes + * + * @private + * @function + */ + const minimizeAttributeChanges = (currPos, attributes) => { + // go right while attributes[right.key] === right.value (or right is deleted) + while (true) { + if (currPos.right === null) { + break + } else if (currPos.right.deleted || (currPos.right.content.constructor === ContentFormat && equalAttrs(attributes[(/** @type {ContentFormat} */ (currPos.right.content)).key] || null, /** @type {ContentFormat} */ (currPos.right.content).value))) ; else { + break + } + currPos.forward(); + } + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {Object} attributes + * @return {Map} + * + * @private + * @function + **/ + const insertAttributes = (transaction, parent, currPos, attributes) => { + const doc = transaction.doc; + const ownClientId = doc.clientID; + const negatedAttributes = new Map(); + // insert format-start items + for (const key in attributes) { + const val = attributes[key]; + const currentVal = currPos.currentAttributes.get(key) || null; + if (!equalAttrs(currentVal, val)) { + // save negated attribute (set null if currentVal undefined) + negatedAttributes.set(key, currentVal); + const { left, right } = currPos; + currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val)); + currPos.right.integrate(transaction, 0); + currPos.forward(); + } + } + return negatedAttributes + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {string|object} text + * @param {Object} attributes + * + * @private + * @function + **/ + const insertText = (transaction, parent, currPos, text, attributes) => { + currPos.currentAttributes.forEach((val, key) => { + if (attributes[key] === undefined) { + attributes[key] = null; + } + }); + const doc = transaction.doc; + const ownClientId = doc.clientID; + minimizeAttributeChanges(currPos, attributes); + const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes); + // insert content + const content = text.constructor === String ? new ContentString(/** @type {string} */ (text)) : new ContentEmbed(text); + let { left, right, index } = currPos; + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength()); + } + right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content); + right.integrate(transaction, 0); + currPos.right = right; + currPos.index = index; + currPos.forward(); + insertNegatedAttributes(transaction, parent, currPos, negatedAttributes); + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {number} length + * @param {Object} attributes + * + * @private + * @function + */ + const formatText = (transaction, parent, currPos, length, attributes) => { + const doc = transaction.doc; + const ownClientId = doc.clientID; + minimizeAttributeChanges(currPos, attributes); + const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes); + // iterate until first non-format or null is found + // delete all formats with attributes[format.key] != null + while (length > 0 && currPos.right !== null) { + if (!currPos.right.deleted) { + switch (currPos.right.content.constructor) { + case ContentFormat: { + const { key, value } = /** @type {ContentFormat} */ (currPos.right.content); + const attr = attributes[key]; + if (attr !== undefined) { + if (equalAttrs(attr, value)) { + negatedAttributes.delete(key); + } else { + negatedAttributes.set(key, value); + } + currPos.right.delete(transaction); + } + break + } + case ContentEmbed: + case ContentString: + if (length < currPos.right.length) { + getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length)); + } + length -= currPos.right.length; + break + } + } + currPos.forward(); + } + // Quill just assumes that the editor starts with a newline and that it always + // ends with a newline. We only insert that newline when a new newline is + // inserted - i.e when length is bigger than type.length + if (length > 0) { + let newlines = ''; + for (; length > 0; length--) { + newlines += '\n'; + } + currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines)); + currPos.right.integrate(transaction, 0); + currPos.forward(); + } + insertNegatedAttributes(transaction, parent, currPos, negatedAttributes); + }; + + /** + * Call this function after string content has been deleted in order to + * clean up formatting Items. + * + * @param {Transaction} transaction + * @param {Item} start + * @param {Item|null} end exclusive end, automatically iterates to the next Content Item + * @param {Map} startAttributes + * @param {Map} endAttributes This attribute is modified! + * @return {number} The amount of formatting Items deleted. + * + * @function + */ + const cleanupFormattingGap = (transaction, start, end, startAttributes, endAttributes) => { + while (end && end.content.constructor !== ContentString && end.content.constructor !== ContentEmbed) { + if (!end.deleted && end.content.constructor === ContentFormat) { + updateCurrentAttributes(endAttributes, /** @type {ContentFormat} */ (end.content)); + } + end = end.right; + } + let cleanups = 0; + while (start !== end) { + if (!start.deleted) { + const content = start.content; + switch (content.constructor) { + case ContentFormat: { + const { key, value } = /** @type {ContentFormat} */ (content); + if ((endAttributes.get(key) || null) !== value || (startAttributes.get(key) || null) === value) { + // Either this format is overwritten or it is not necessary because the attribute already existed. + start.delete(transaction); + cleanups++; + } + break + } + } + } + start = /** @type {Item} */ (start.right); + } + return cleanups + }; + + /** + * @param {Transaction} transaction + * @param {Item | null} item + */ + const cleanupContextlessFormattingGap = (transaction, item) => { + // iterate until item.right is null or content + while (item && item.right && (item.right.deleted || (item.right.content.constructor !== ContentString && item.right.content.constructor !== ContentEmbed))) { + item = item.right; + } + const attrs = new Set(); + // iterate back until a content item is found + while (item && (item.deleted || (item.content.constructor !== ContentString && item.content.constructor !== ContentEmbed))) { + if (!item.deleted && item.content.constructor === ContentFormat) { + const key = /** @type {ContentFormat} */ (item.content).key; + if (attrs.has(key)) { + item.delete(transaction); + } else { + attrs.add(key); + } + } + item = item.left; + } + }; + + /** + * This function is experimental and subject to change / be removed. + * + * Ideally, we don't need this function at all. Formatting attributes should be cleaned up + * automatically after each change. This function iterates twice over the complete YText type + * and removes unnecessary formatting attributes. This is also helpful for testing. + * + * This function won't be exported anymore as soon as there is confidence that the YText type works as intended. + * + * @param {YText} type + * @return {number} How many formatting attributes have been cleaned up. + */ + const cleanupYTextFormatting = type => { + let res = 0; + transact(/** @type {Doc} */ (type.doc), transaction => { + let start = /** @type {Item} */ (type._start); + let end = type._start; + let startAttributes = create(); + const currentAttributes = copy(startAttributes); + while (end) { + if (end.deleted === false) { + switch (end.content.constructor) { + case ContentFormat: + updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (end.content)); + break + case ContentEmbed: + case ContentString: + res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes); + startAttributes = copy(currentAttributes); + start = end; + break + } + } + end = end.right; + } + }); + return res + }; + + /** + * @param {Transaction} transaction + * @param {ItemTextListPosition} currPos + * @param {number} length + * @return {ItemTextListPosition} + * + * @private + * @function + */ + const deleteText = (transaction, currPos, length) => { + const startLength = length; + const startAttrs = copy(currPos.currentAttributes); + const start = currPos.right; + while (length > 0 && currPos.right !== null) { + if (currPos.right.deleted === false) { + switch (currPos.right.content.constructor) { + case ContentEmbed: + case ContentString: + if (length < currPos.right.length) { + getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length)); + } + length -= currPos.right.length; + currPos.right.delete(transaction); + break + } + } + currPos.forward(); + } + if (start) { + cleanupFormattingGap(transaction, start, currPos.right, startAttrs, copy(currPos.currentAttributes)); + } + const parent = /** @type {AbstractType} */ (/** @type {Item} */ (currPos.left || currPos.right).parent); + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length); + } + return currPos + }; + + /** + * The Quill Delta format represents changes on a text document with + * formatting information. For mor information visit {@link https://quilljs.com/docs/delta/|Quill Delta} + * + * @example + * { + * ops: [ + * { insert: 'Gandalf', attributes: { bold: true } }, + * { insert: ' the ' }, + * { insert: 'Grey', attributes: { color: '#cccccc' } } + * ] + * } + * + */ + + /** + * Attributes that can be assigned to a selection of text. + * + * @example + * { + * bold: true, + * font-size: '40px' + * } + * + * @typedef {Object} TextAttributes + */ + + /** + * @typedef {Object} DeltaItem + * @property {number|undefined} DeltaItem.delete + * @property {number|undefined} DeltaItem.retain + * @property {string|undefined} DeltaItem.insert + * @property {Object} DeltaItem.attributes + */ + + /** + * Event that describes the changes on a YText type. + */ + class YTextEvent extends YEvent { + /** + * @param {YText} ytext + * @param {Transaction} transaction + */ + constructor (ytext, transaction) { + super(ytext, transaction); + /** + * @type {Array|null} + */ + this._delta = null; + } + + /** + * Compute the changes in the delta format. + * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document. + * + * @type {Array} + * + * @public + */ + get delta () { + if (this._delta === null) { + const y = /** @type {Doc} */ (this.target.doc); + this._delta = []; + transact(y, transaction => { + const delta = /** @type {Array} */ (this._delta); + const currentAttributes = new Map(); // saves all current attributes for insert + const oldAttributes = new Map(); + let item = this.target._start; + /** + * @type {string?} + */ + let action = null; + /** + * @type {Object} + */ + const attributes = {}; // counts added or removed new attributes for retain + /** + * @type {string|object} + */ + let insert = ''; + let retain = 0; + let deleteLen = 0; + const addOp = () => { + if (action !== null) { + /** + * @type {any} + */ + let op; + switch (action) { + case 'delete': + op = { delete: deleteLen }; + deleteLen = 0; + break + case 'insert': + op = { insert }; + if (currentAttributes.size > 0) { + op.attributes = {}; + currentAttributes.forEach((value, key) => { + if (value !== null) { + op.attributes[key] = value; + } + }); + } + insert = ''; + break + case 'retain': + op = { retain }; + if (Object.keys(attributes).length > 0) { + op.attributes = {}; + for (const key in attributes) { + op.attributes[key] = attributes[key]; + } + } + retain = 0; + break + } + delta.push(op); + action = null; + } + }; + while (item !== null) { + switch (item.content.constructor) { + case ContentEmbed: + if (this.adds(item)) { + if (!this.deletes(item)) { + addOp(); + action = 'insert'; + insert = /** @type {ContentEmbed} */ (item.content).embed; + addOp(); + } + } else if (this.deletes(item)) { + if (action !== 'delete') { + addOp(); + action = 'delete'; + } + deleteLen += 1; + } else if (!item.deleted) { + if (action !== 'retain') { + addOp(); + action = 'retain'; + } + retain += 1; + } + break + case ContentString: + if (this.adds(item)) { + if (!this.deletes(item)) { + if (action !== 'insert') { + addOp(); + action = 'insert'; + } + insert += /** @type {ContentString} */ (item.content).str; + } + } else if (this.deletes(item)) { + if (action !== 'delete') { + addOp(); + action = 'delete'; + } + deleteLen += item.length; + } else if (!item.deleted) { + if (action !== 'retain') { + addOp(); + action = 'retain'; + } + retain += item.length; + } + break + case ContentFormat: { + const { key, value } = /** @type {ContentFormat} */ (item.content); + if (this.adds(item)) { + if (!this.deletes(item)) { + const curVal = currentAttributes.get(key) || null; + if (!equalAttrs(curVal, value)) { + if (action === 'retain') { + addOp(); + } + if (equalAttrs(value, (oldAttributes.get(key) || null))) { + delete attributes[key]; + } else { + attributes[key] = value; + } + } else { + item.delete(transaction); + } + } + } else if (this.deletes(item)) { + oldAttributes.set(key, value); + const curVal = currentAttributes.get(key) || null; + if (!equalAttrs(curVal, value)) { + if (action === 'retain') { + addOp(); + } + attributes[key] = curVal; + } + } else if (!item.deleted) { + oldAttributes.set(key, value); + const attr = attributes[key]; + if (attr !== undefined) { + if (!equalAttrs(attr, value)) { + if (action === 'retain') { + addOp(); + } + if (value === null) { + attributes[key] = value; + } else { + delete attributes[key]; + } + } else { + item.delete(transaction); + } + } + } + if (!item.deleted) { + if (action === 'insert') { + addOp(); + } + updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (item.content)); + } + break + } + } + item = item.right; + } + addOp(); + while (delta.length > 0) { + const lastOp = delta[delta.length - 1]; + if (lastOp.retain !== undefined && lastOp.attributes === undefined) { + // retain delta's if they don't assign attributes + delta.pop(); + } else { + break + } + } + }); + } + return this._delta + } + } + + /** + * Type that represents text with formatting information. + * + * This type replaces y-richtext as this implementation is able to handle + * block formats (format information on a paragraph), embeds (complex elements + * like pictures and videos), and text formats (**bold**, *italic*). + * + * @extends AbstractType + */ + class YText extends AbstractType { + /** + * @param {String} [string] The initial value of the YText. + */ + constructor (string) { + super(); + /** + * Array of pending operations on this type + * @type {Array?} + */ + this._pending = string !== undefined ? [() => this.insert(0, string)] : []; + /** + * @type {Array} + */ + this._searchMarker = []; + } + + /** + * Number of characters of this text type. + * + * @type {number} + */ + get length () { + return this._length + } + + /** + * @param {Doc} y + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item); + try { + /** @type {Array} */ (this._pending).forEach(f => f()); + } catch (e) { + console.error(e); + } + this._pending = null; + } + + _copy () { + return new YText() + } + + /** + * Creates YTextEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + super._callObserver(transaction, parentSubs); + const event = new YTextEvent(this, transaction); + const doc = transaction.doc; + // If a remote change happened, we try to cleanup potential formatting duplicates. + if (!transaction.local) { + // check if another formatting item was inserted + let foundFormattingItem = false; + for (const [client, afterClock] of transaction.afterState.entries()) { + const clock = transaction.beforeState.get(client) || 0; + if (afterClock === clock) { + continue + } + iterateStructs(transaction, /** @type {Array} */ (doc.store.clients.get(client)), clock, afterClock, item => { + if (!item.deleted && /** @type {Item} */ (item).content.constructor === ContentFormat) { + foundFormattingItem = true; + } + }); + if (foundFormattingItem) { + break + } + } + if (!foundFormattingItem) { + iterateDeletedStructs(transaction, transaction.deleteSet, item => { + if (item instanceof GC || foundFormattingItem) { + return + } + if (item.parent === this && item.content.constructor === ContentFormat) { + foundFormattingItem = true; + } + }); + } + transact(doc, (t) => { + if (foundFormattingItem) { + // If a formatting item was inserted, we simply clean the whole type. + // We need to compute currentAttributes for the current position anyway. + cleanupYTextFormatting(this); + } else { + // If no formatting attribute was inserted, we can make due with contextless + // formatting cleanups. + // Contextless: it is not necessary to compute currentAttributes for the affected position. + iterateDeletedStructs(t, t.deleteSet, item => { + if (item instanceof GC) { + return + } + if (item.parent === this) { + cleanupContextlessFormattingGap(t, item); + } + }); + } + }); + } + callTypeObservers(this, transaction, event); + } + + /** + * Returns the unformatted string representation of this YText type. + * + * @public + */ + toString () { + let str = ''; + /** + * @type {Item|null} + */ + let n = this._start; + while (n !== null) { + if (!n.deleted && n.countable && n.content.constructor === ContentString) { + str += /** @type {ContentString} */ (n.content).str; + } + n = n.right; + } + return str + } + + /** + * Returns the unformatted string representation of this YText type. + * + * @return {string} + * @public + */ + toJSON () { + return this.toString() + } + + /** + * Apply a {@link Delta} on this shared YText type. + * + * @param {any} delta The changes to apply on this element. + * @param {object} [opts] + * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true. + * + * + * @public + */ + applyDelta (delta, { sanitize = true } = {}) { + if (this.doc !== null) { + transact(this.doc, transaction => { + const currPos = new ItemTextListPosition(null, this._start, 0, new Map()); + for (let i = 0; i < delta.length; i++) { + const op = delta[i]; + if (op.insert !== undefined) { + // Quill assumes that the content starts with an empty paragraph. + // Yjs/Y.Text assumes that it starts empty. We always hide that + // there is a newline at the end of the content. + // If we omit this step, clients will see a different number of + // paragraphs, but nothing bad will happen. + const ins = (!sanitize && typeof op.insert === 'string' && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === '\n') ? op.insert.slice(0, -1) : op.insert; + if (typeof ins !== 'string' || ins.length > 0) { + insertText(transaction, this, currPos, ins, op.attributes || {}); + } + } else if (op.retain !== undefined) { + formatText(transaction, this, currPos, op.retain, op.attributes || {}); + } else if (op.delete !== undefined) { + deleteText(transaction, currPos, op.delete); + } + } + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.applyDelta(delta)); + } + } + + /** + * Returns the Delta representation of this YText type. + * + * @param {Snapshot} [snapshot] + * @param {Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', ID):any} [computeYChange] + * @return {any} The Delta representation of this type. + * + * @public + */ + toDelta (snapshot, prevSnapshot, computeYChange) { + /** + * @type{Array} + */ + const ops = []; + const currentAttributes = new Map(); + const doc = /** @type {Doc} */ (this.doc); + let str = ''; + let n = this._start; + function packStr () { + if (str.length > 0) { + // pack str with attributes to ops + /** + * @type {Object} + */ + const attributes = {}; + let addAttributes = false; + currentAttributes.forEach((value, key) => { + addAttributes = true; + attributes[key] = value; + }); + /** + * @type {Object} + */ + const op = { insert: str }; + if (addAttributes) { + op.attributes = attributes; + } + ops.push(op); + str = ''; + } + } + // snapshots are merged again after the transaction, so we need to keep the + // transalive until we are done + transact(doc, transaction => { + if (snapshot) { + splitSnapshotAffectedStructs(transaction, snapshot); + } + if (prevSnapshot) { + splitSnapshotAffectedStructs(transaction, prevSnapshot); + } + while (n !== null) { + if (isVisible(n, snapshot) || (prevSnapshot !== undefined && isVisible(n, prevSnapshot))) { + switch (n.content.constructor) { + case ContentString: { + const cur = currentAttributes.get('ychange'); + if (snapshot !== undefined && !isVisible(n, snapshot)) { + if (cur === undefined || cur.user !== n.id.client || cur.state !== 'removed') { + packStr(); + currentAttributes.set('ychange', computeYChange ? computeYChange('removed', n.id) : { type: 'removed' }); + } + } else if (prevSnapshot !== undefined && !isVisible(n, prevSnapshot)) { + if (cur === undefined || cur.user !== n.id.client || cur.state !== 'added') { + packStr(); + currentAttributes.set('ychange', computeYChange ? computeYChange('added', n.id) : { type: 'added' }); + } + } else if (cur !== undefined) { + packStr(); + currentAttributes.delete('ychange'); + } + str += /** @type {ContentString} */ (n.content).str; + break + } + case ContentEmbed: { + packStr(); + /** + * @type {Object} + */ + const op = { + insert: /** @type {ContentEmbed} */ (n.content).embed + }; + if (currentAttributes.size > 0) { + const attrs = /** @type {Object} */ ({}); + op.attributes = attrs; + currentAttributes.forEach((value, key) => { + attrs[key] = value; + }); + } + ops.push(op); + break + } + case ContentFormat: + if (isVisible(n, snapshot)) { + packStr(); + updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (n.content)); + } + break + } + } + n = n.right; + } + packStr(); + }, splitSnapshotAffectedStructs); + return ops + } + + /** + * Insert text at a given index. + * + * @param {number} index The index at which to start inserting. + * @param {String} text The text to insert at the specified position. + * @param {TextAttributes} [attributes] Optionally define some formatting + * information to apply on the inserted + * Text. + * @public + */ + insert (index, text, attributes) { + if (text.length <= 0) { + return + } + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + const pos = findPosition(transaction, this, index); + if (!attributes) { + attributes = {}; + // @ts-ignore + pos.currentAttributes.forEach((v, k) => { attributes[k] = v; }); + } + insertText(transaction, this, pos, text, attributes); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.insert(index, text, attributes)); + } + } + + /** + * Inserts an embed at a index. + * + * @param {number} index The index to insert the embed at. + * @param {Object} embed The Object that represents the embed. + * @param {TextAttributes} attributes Attribute information to apply on the + * embed + * + * @public + */ + insertEmbed (index, embed, attributes = {}) { + if (embed.constructor !== Object) { + throw new Error('Embed must be an Object') + } + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + const pos = findPosition(transaction, this, index); + insertText(transaction, this, pos, embed, attributes); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.insertEmbed(index, embed, attributes)); + } + } + + /** + * Deletes text starting from an index. + * + * @param {number} index Index at which to start deleting. + * @param {number} length The number of characters to remove. Defaults to 1. + * + * @public + */ + delete (index, length) { + if (length === 0) { + return + } + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + deleteText(transaction, findPosition(transaction, this, index), length); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.delete(index, length)); + } + } + + /** + * Assigns properties to a range of text. + * + * @param {number} index The position where to start formatting. + * @param {number} length The amount of characters to assign properties to. + * @param {TextAttributes} attributes Attribute information to apply on the + * text. + * + * @public + */ + format (index, length, attributes) { + if (length === 0) { + return + } + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + const pos = findPosition(transaction, this, index); + if (pos.right === null) { + return + } + formatText(transaction, this, pos, length, attributes); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.format(index, length, attributes)); + } + } + + /** + * @param {AbstractUpdateEncoder} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YTextRefID); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {YText} + * + * @private + * @function + */ + const readYText = decoder => new YText(); + + /** + * @module YXml + */ + + /** + * Define the elements to which a set of CSS queries apply. + * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors|CSS_Selectors} + * + * @example + * query = '.classSelector' + * query = 'nodeSelector' + * query = '#idSelector' + * + * @typedef {string} CSS_Selector + */ + + /** + * Dom filter function. + * + * @callback domFilter + * @param {string} nodeName The nodeName of the element + * @param {Map} attributes The map of attributes. + * @return {boolean} Whether to include the Dom node in the YXmlElement. + */ + + /** + * Represents a subset of the nodes of a YXmlElement / YXmlFragment and a + * position within them. + * + * Can be created with {@link YXmlFragment#createTreeWalker} + * + * @public + * @implements {Iterable} + */ + class YXmlTreeWalker { + /** + * @param {YXmlFragment | YXmlElement} root + * @param {function(AbstractType):boolean} [f] + */ + constructor (root, f = () => true) { + this._filter = f; + this._root = root; + /** + * @type {Item} + */ + this._currentNode = /** @type {Item} */ (root._start); + this._firstCall = true; + } + + [Symbol.iterator] () { + return this + } + + /** + * Get the next node. + * + * @return {IteratorResult} The next node. + * + * @public + */ + next () { + /** + * @type {Item|null} + */ + let n = this._currentNode; + let type = /** @type {any} */ (n.content).type; + if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { // if first call, we check if we can use the first item + do { + type = /** @type {any} */ (n.content).type; + if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) { + // walk down in the tree + n = type._start; + } else { + // walk right or up in the tree + while (n !== null) { + if (n.right !== null) { + n = n.right; + break + } else if (n.parent === this._root) { + n = null; + } else { + n = /** @type {AbstractType} */ (n.parent)._item; + } + } + } + } while (n !== null && (n.deleted || !this._filter(/** @type {ContentType} */ (n.content).type))) + } + this._firstCall = false; + if (n === null) { + // @ts-ignore + return { value: undefined, done: true } + } + this._currentNode = n; + return { value: /** @type {any} */ (n.content).type, done: false } + } + } + + /** + * Represents a list of {@link YXmlElement}.and {@link YXmlText} types. + * A YxmlFragment is similar to a {@link YXmlElement}, but it does not have a + * nodeName and it does not have attributes. Though it can be bound to a DOM + * element - in this case the attributes and the nodeName are not shared. + * + * @public + * @extends AbstractType + */ + class YXmlFragment extends AbstractType { + constructor () { + super(); + /** + * @type {Array|null} + */ + this._prelimContent = []; + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item); + this.insert(0, /** @type {Array} */ (this._prelimContent)); + this._prelimContent = null; + } + + _copy () { + return new YXmlFragment() + } + + get length () { + return this._prelimContent === null ? this._length : this._prelimContent.length + } + + /** + * Create a subtree of childNodes. + * + * @example + * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div') + * for (let node in walker) { + * // `node` is a div node + * nop(node) + * } + * + * @param {function(AbstractType):boolean} filter Function that is called on each child element and + * returns a Boolean indicating whether the child + * is to be included in the subtree. + * @return {YXmlTreeWalker} A subtree and a position within it. + * + * @public + */ + createTreeWalker (filter) { + return new YXmlTreeWalker(this, filter) + } + + /** + * Returns the first YXmlElement that matches the query. + * Similar to DOM's {@link querySelector}. + * + * Query support: + * - tagname + * TODO: + * - id + * - attribute + * + * @param {CSS_Selector} query The query on the children. + * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null. + * + * @public + */ + querySelector (query) { + query = query.toUpperCase(); + // @ts-ignore + const iterator = new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query); + const next = iterator.next(); + if (next.done) { + return null + } else { + return next.value + } + } + + /** + * Returns all YXmlElements that match the query. + * Similar to Dom's {@link querySelectorAll}. + * + * @todo Does not yet support all queries. Currently only query by tagName. + * + * @param {CSS_Selector} query The query on the children + * @return {Array} The elements that match this query. + * + * @public + */ + querySelectorAll (query) { + query = query.toUpperCase(); + // @ts-ignore + return Array.from(new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query)) + } + + /** + * Creates YXmlEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction)); + } + + /** + * Get the string representation of all the children of this YXmlFragment. + * + * @return {string} The string representation of all children. + */ + toString () { + return typeListMap(this, xml => xml.toString()).join('') + } + + /** + * @return {string} + */ + toJSON () { + return this.toString() + } + + /** + * Creates a Dom Element that mirrors this YXmlElement. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object} [hooks={}] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type. + * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks = {}, binding) { + const fragment = _document.createDocumentFragment(); + if (binding !== undefined) { + binding._createAssociation(fragment, this); + } + typeListForEach(this, xmlType => { + fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null); + }); + return fragment + } + + /** + * Inserts new content at an index. + * + * @example + * // Insert character 'a' at position 0 + * xml.insert(0, [new Y.XmlText('text')]) + * + * @param {number} index The index to insert content at + * @param {Array} content The array of content + */ + insert (index, content) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListInsertGenerics(transaction, this, index, content); + }); + } else { + // @ts-ignore _prelimContent is defined because this is not yet integrated + this._prelimContent.splice(index, 0, ...content); + } + } + + /** + * Deletes elements starting from an index. + * + * @param {number} index Index at which to start deleting elements + * @param {number} [length=1] The number of elements to remove. Defaults to 1. + */ + delete (index, length = 1) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListDelete(transaction, this, index, length); + }); + } else { + // @ts-ignore _prelimContent is defined because this is not yet integrated + this._prelimContent.splice(index, length); + } + } + + /** + * Transforms this YArray to a JavaScript Array. + * + * @return {Array} + */ + toArray () { + return typeListToArray(this) + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {AbstractUpdateEncoder} encoder The encoder to write data to. + */ + _write (encoder) { + encoder.writeTypeRef(YXmlFragmentRefID); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {YXmlFragment} + * + * @private + * @function + */ + const readYXmlFragment = decoder => new YXmlFragment(); + + /** + * An YXmlElement imitates the behavior of a + * {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}. + * + * * An YXmlElement has attributes (key value pairs) + * * An YXmlElement has childElements that must inherit from YXmlElement + */ + class YXmlElement extends YXmlFragment { + constructor (nodeName = 'UNDEFINED') { + super(); + this.nodeName = nodeName; + /** + * @type {Map|null} + */ + this._prelimAttrs = new Map(); + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item) + ;(/** @type {Map} */ (this._prelimAttrs)).forEach((value, key) => { + this.setAttribute(key, value); + }); + this._prelimAttrs = null; + } + + /** + * Creates an Item with the same effect as this Item (without position effect) + * + * @return {YXmlElement} + */ + _copy () { + return new YXmlElement(this.nodeName) + } + + /** + * Returns the XML serialization of this YXmlElement. + * The attributes are ordered by attribute-name, so you can easily use this + * method to compare YXmlElements + * + * @return {string} The string representation of this type. + * + * @public + */ + toString () { + const attrs = this.getAttributes(); + const stringBuilder = []; + const keys = []; + for (const key in attrs) { + keys.push(key); + } + keys.sort(); + const keysLen = keys.length; + for (let i = 0; i < keysLen; i++) { + const key = keys[i]; + stringBuilder.push(key + '="' + attrs[key] + '"'); + } + const nodeName = this.nodeName.toLocaleLowerCase(); + const attrsString = stringBuilder.length > 0 ? ' ' + stringBuilder.join(' ') : ''; + return `<${nodeName}${attrsString}>${super.toString()}` + } + + /** + * Removes an attribute from this YXmlElement. + * + * @param {String} attributeName The attribute name that is to be removed. + * + * @public + */ + removeAttribute (attributeName) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapDelete(transaction, this, attributeName); + }); + } else { + /** @type {Map} */ (this._prelimAttrs).delete(attributeName); + } + } + + /** + * Sets or updates an attribute. + * + * @param {String} attributeName The attribute name that is to be set. + * @param {String} attributeValue The attribute value that is to be set. + * + * @public + */ + setAttribute (attributeName, attributeValue) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapSet(transaction, this, attributeName, attributeValue); + }); + } else { + /** @type {Map} */ (this._prelimAttrs).set(attributeName, attributeValue); + } + } + + /** + * Returns an attribute value that belongs to the attribute name. + * + * @param {String} attributeName The attribute name that identifies the + * queried value. + * @return {String} The queried attribute value. + * + * @public + */ + getAttribute (attributeName) { + return /** @type {any} */ (typeMapGet(this, attributeName)) + } + + /** + * Returns all attribute name/value pairs in a JSON Object. + * + * @param {Snapshot} [snapshot] + * @return {Object} A JSON Object that describes the attributes. + * + * @public + */ + getAttributes (snapshot) { + return typeMapGetAll(this) + } + + /** + * Creates a Dom Element that mirrors this YXmlElement. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object} [hooks={}] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type. + * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks = {}, binding) { + const dom = _document.createElement(this.nodeName); + const attrs = this.getAttributes(); + for (const key in attrs) { + dom.setAttribute(key, attrs[key]); + } + typeListForEach(this, yxml => { + dom.appendChild(yxml.toDOM(_document, hooks, binding)); + }); + if (binding !== undefined) { + binding._createAssociation(dom, this); + } + return dom + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {AbstractUpdateEncoder} encoder The encoder to write data to. + */ + _write (encoder) { + encoder.writeTypeRef(YXmlElementRefID); + encoder.writeKey(this.nodeName); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {YXmlElement} + * + * @function + */ + const readYXmlElement = decoder => new YXmlElement(decoder.readKey()); + + /** + * An Event that describes changes on a YXml Element or Yxml Fragment + */ + class YXmlEvent extends YEvent { + /** + * @param {YXmlElement|YXmlFragment} target The target on which the event is created. + * @param {Set} subs The set of changed attributes. `null` is included if the + * child list changed. + * @param {Transaction} transaction The transaction instance with wich the + * change was created. + */ + constructor (target, subs, transaction) { + super(target, transaction); + /** + * Whether the children changed. + * @type {Boolean} + * @private + */ + this.childListChanged = false; + /** + * Set of all changed attributes. + * @type {Set} + */ + this.attributesChanged = new Set(); + subs.forEach((sub) => { + if (sub === null) { + this.childListChanged = true; + } else { + this.attributesChanged.add(sub); + } + }); + } + } + + /** + * You can manage binding to a custom type with YXmlHook. + * + * @extends {YMap} + */ + class YXmlHook extends YMap { + /** + * @param {string} hookName nodeName of the Dom Node. + */ + constructor (hookName) { + super(); + /** + * @type {string} + */ + this.hookName = hookName; + } + + /** + * Creates an Item with the same effect as this Item (without position effect) + */ + _copy () { + return new YXmlHook(this.hookName) + } + + /** + * Creates a Dom Element that mirrors this YXmlElement. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object.} [hooks] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type + * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks = {}, binding) { + const hook = hooks[this.hookName]; + let dom; + if (hook !== undefined) { + dom = hook.createDom(this); + } else { + dom = document.createElement(this.hookName); + } + dom.setAttribute('data-yjs-hook', this.hookName); + if (binding !== undefined) { + binding._createAssociation(dom, this); + } + return dom + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {AbstractUpdateEncoder} encoder The encoder to write data to. + */ + _write (encoder) { + encoder.writeTypeRef(YXmlHookRefID); + encoder.writeKey(this.hookName); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {YXmlHook} + * + * @private + * @function + */ + const readYXmlHook = decoder => + new YXmlHook(decoder.readKey()); + + /** + * Represents text in a Dom Element. In the future this type will also handle + * simple formatting information like bold and italic. + */ + class YXmlText extends YText { + _copy () { + return new YXmlText() + } + + /** + * Creates a Dom Element that mirrors this YXmlText. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object} [hooks] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type. + * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks, binding) { + const dom = _document.createTextNode(this.toString()); + if (binding !== undefined) { + binding._createAssociation(dom, this); + } + return dom + } + + toString () { + // @ts-ignore + return this.toDelta().map(delta => { + const nestedNodes = []; + for (const nodeName in delta.attributes) { + const attrs = []; + for (const key in delta.attributes[nodeName]) { + attrs.push({ key, value: delta.attributes[nodeName][key] }); + } + // sort attributes to get a unique order + attrs.sort((a, b) => a.key < b.key ? -1 : 1); + nestedNodes.push({ nodeName, attrs }); + } + // sort node order to get a unique order + nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1); + // now convert to dom string + let str = ''; + for (let i = 0; i < nestedNodes.length; i++) { + const node = nestedNodes[i]; + str += `<${node.nodeName}`; + for (let j = 0; j < node.attrs.length; j++) { + const attr = node.attrs[j]; + str += ` ${attr.key}="${attr.value}"`; + } + str += '>'; + } + str += delta.insert; + for (let i = nestedNodes.length - 1; i >= 0; i--) { + str += ``; + } + return str + }).join('') + } + + /** + * @return {string} + */ + toJSON () { + return this.toString() + } + + /** + * @param {AbstractUpdateEncoder} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YXmlTextRefID); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {YXmlText} + * + * @private + * @function + */ + const readYXmlText = decoder => new YXmlText(); + + class AbstractStruct { + /** + * @param {ID} id + * @param {number} length + */ + constructor (id, length) { + this.id = id; + this.length = length; + } + + /** + * @type {boolean} + */ + get deleted () { + throw methodUnimplemented() + } + + /** + * Merge this struct with the item to the right. + * This method is already assuming that `this.id.clock + this.length === this.id.clock`. + * Also this method does *not* remove right from StructStore! + * @param {AbstractStruct} right + * @return {boolean} wether this merged with right + */ + mergeWith (right) { + return false + } + + /** + * @param {AbstractUpdateEncoder} encoder The encoder to write data to. + * @param {number} offset + * @param {number} encodingRef + */ + write (encoder, offset, encodingRef) { + throw methodUnimplemented() + } + + /** + * @param {Transaction} transaction + * @param {number} offset + */ + integrate (transaction, offset) { + throw methodUnimplemented() + } + } + + const structGCRefNumber = 0; + + /** + * @private + */ + class GC extends AbstractStruct { + get deleted () { + return true + } + + delete () {} + + /** + * @param {GC} right + * @return {boolean} + */ + mergeWith (right) { + this.length += right.length; + return true + } + + /** + * @param {Transaction} transaction + * @param {number} offset + */ + integrate (transaction, offset) { + if (offset > 0) { + this.id.clock += offset; + this.length -= offset; + } + addStruct(transaction.doc.store, this); + } + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeInfo(structGCRefNumber); + encoder.writeLen(this.length - offset); + } + + /** + * @param {Transaction} transaction + * @param {StructStore} store + * @return {null | number} + */ + getMissing (transaction, store) { + return null + } + } + + class ContentBinary { + /** + * @param {Uint8Array} content + */ + constructor (content) { + this.content = content; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.content] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentBinary} + */ + copy () { + return new ContentBinary(this.content) + } + + /** + * @param {number} offset + * @return {ContentBinary} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {ContentBinary} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeBuf(this.content); + } + + /** + * @return {number} + */ + getRef () { + return 3 + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {ContentBinary} + */ + const readContentBinary = decoder => new ContentBinary(decoder.readBuf()); + + class ContentDeleted { + /** + * @param {number} len + */ + constructor (len) { + this.len = len; + } + + /** + * @return {number} + */ + getLength () { + return this.len + } + + /** + * @return {Array} + */ + getContent () { + return [] + } + + /** + * @return {boolean} + */ + isCountable () { + return false + } + + /** + * @return {ContentDeleted} + */ + copy () { + return new ContentDeleted(this.len) + } + + /** + * @param {number} offset + * @return {ContentDeleted} + */ + splice (offset) { + const right = new ContentDeleted(this.len - offset); + this.len = offset; + return right + } + + /** + * @param {ContentDeleted} right + * @return {boolean} + */ + mergeWith (right) { + this.len += right.len; + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len); + item.markDeleted(); + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeLen(this.len - offset); + } + + /** + * @return {number} + */ + getRef () { + return 1 + } + } + + /** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentDeleted} + */ + const readContentDeleted = decoder => new ContentDeleted(decoder.readLen()); + + /** + * @private + */ + class ContentDoc { + /** + * @param {Doc} doc + */ + constructor (doc) { + if (doc._item) { + console.error('This document was already integrated as a sub-document. You should create a second instance instead with the same guid.'); + } + /** + * @type {Doc} + */ + this.doc = doc; + /** + * @type {any} + */ + const opts = {}; + this.opts = opts; + if (!doc.gc) { + opts.gc = false; + } + if (doc.autoLoad) { + opts.autoLoad = true; + } + if (doc.meta !== null) { + opts.meta = doc.meta; + } + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.doc] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentDoc} + */ + copy () { + return new ContentDoc(this.doc) + } + + /** + * @param {number} offset + * @return {ContentDoc} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {ContentDoc} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + // this needs to be reflected in doc.destroy as well + this.doc._item = item; + transaction.subdocsAdded.add(this.doc); + if (this.doc.shouldLoad) { + transaction.subdocsLoaded.add(this.doc); + } + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) { + if (transaction.subdocsAdded.has(this.doc)) { + transaction.subdocsAdded.delete(this.doc); + } else { + transaction.subdocsRemoved.add(this.doc); + } + } + + /** + * @param {StructStore} store + */ + gc (store) { } + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeString(this.doc.guid); + encoder.writeAny(this.opts); + } + + /** + * @return {number} + */ + getRef () { + return 9 + } + } + + /** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentDoc} + */ + const readContentDoc = decoder => new ContentDoc(new Doc({ guid: decoder.readString(), ...decoder.readAny() })); + + /** + * @private + */ + class ContentEmbed { + /** + * @param {Object} embed + */ + constructor (embed) { + this.embed = embed; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.embed] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentEmbed} + */ + copy () { + return new ContentEmbed(this.embed) + } + + /** + * @param {number} offset + * @return {ContentEmbed} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {ContentEmbed} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeJSON(this.embed); + } + + /** + * @return {number} + */ + getRef () { + return 5 + } + } + + /** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentEmbed} + */ + const readContentEmbed = decoder => new ContentEmbed(decoder.readJSON()); + + /** + * @private + */ + class ContentFormat { + /** + * @param {string} key + * @param {Object} value + */ + constructor (key, value) { + this.key = key; + this.value = value; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [] + } + + /** + * @return {boolean} + */ + isCountable () { + return false + } + + /** + * @return {ContentFormat} + */ + copy () { + return new ContentFormat(this.key, this.value) + } + + /** + * @param {number} offset + * @return {ContentFormat} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {ContentFormat} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + // @todo searchmarker are currently unsupported for rich text documents + /** @type {AbstractType} */ (item.parent)._searchMarker = null; + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeKey(this.key); + encoder.writeJSON(this.value); + } + + /** + * @return {number} + */ + getRef () { + return 6 + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {ContentFormat} + */ + const readContentFormat = decoder => new ContentFormat(decoder.readString(), decoder.readJSON()); + + /** + * @private + */ + class ContentJSON { + /** + * @param {Array} arr + */ + constructor (arr) { + /** + * @type {Array} + */ + this.arr = arr; + } + + /** + * @return {number} + */ + getLength () { + return this.arr.length + } + + /** + * @return {Array} + */ + getContent () { + return this.arr + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentJSON} + */ + copy () { + return new ContentJSON(this.arr) + } + + /** + * @param {number} offset + * @return {ContentJSON} + */ + splice (offset) { + const right = new ContentJSON(this.arr.slice(offset)); + this.arr = this.arr.slice(0, offset); + return right + } + + /** + * @param {ContentJSON} right + * @return {boolean} + */ + mergeWith (right) { + this.arr = this.arr.concat(right.arr); + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + const len = this.arr.length; + encoder.writeLen(len - offset); + for (let i = offset; i < len; i++) { + const c = this.arr[i]; + encoder.writeString(c === undefined ? 'undefined' : JSON.stringify(c)); + } + } + + /** + * @return {number} + */ + getRef () { + return 2 + } + } + + /** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentJSON} + */ + const readContentJSON = decoder => { + const len = decoder.readLen(); + const cs = []; + for (let i = 0; i < len; i++) { + const c = decoder.readString(); + if (c === 'undefined') { + cs.push(undefined); + } else { + cs.push(JSON.parse(c)); + } + } + return new ContentJSON(cs) + }; + + class ContentAny { + /** + * @param {Array} arr + */ + constructor (arr) { + /** + * @type {Array} + */ + this.arr = arr; + } + + /** + * @return {number} + */ + getLength () { + return this.arr.length + } + + /** + * @return {Array} + */ + getContent () { + return this.arr + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentAny} + */ + copy () { + return new ContentAny(this.arr) + } + + /** + * @param {number} offset + * @return {ContentAny} + */ + splice (offset) { + const right = new ContentAny(this.arr.slice(offset)); + this.arr = this.arr.slice(0, offset); + return right + } + + /** + * @param {ContentAny} right + * @return {boolean} + */ + mergeWith (right) { + this.arr = this.arr.concat(right.arr); + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + const len = this.arr.length; + encoder.writeLen(len - offset); + for (let i = offset; i < len; i++) { + const c = this.arr[i]; + encoder.writeAny(c); + } + } + + /** + * @return {number} + */ + getRef () { + return 8 + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {ContentAny} + */ + const readContentAny = decoder => { + const len = decoder.readLen(); + const cs = []; + for (let i = 0; i < len; i++) { + cs.push(decoder.readAny()); + } + return new ContentAny(cs) + }; + + /** + * @private + */ + class ContentString { + /** + * @param {string} str + */ + constructor (str) { + /** + * @type {string} + */ + this.str = str; + } + + /** + * @return {number} + */ + getLength () { + return this.str.length + } + + /** + * @return {Array} + */ + getContent () { + return this.str.split('') + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentString} + */ + copy () { + return new ContentString(this.str) + } + + /** + * @param {number} offset + * @return {ContentString} + */ + splice (offset) { + const right = new ContentString(this.str.slice(offset)); + this.str = this.str.slice(0, offset); + + // Prevent encoding invalid documents because of splitting of surrogate pairs: https://github.com/yjs/yjs/issues/248 + const firstCharCode = this.str.charCodeAt(offset - 1); + if (firstCharCode >= 0xD800 && firstCharCode <= 0xDBFF) { + // Last character of the left split is the start of a surrogate utf16/ucs2 pair. + // We don't support splitting of surrogate pairs because this may lead to invalid documents. + // Replace the invalid character with a unicode replacement character (� / U+FFFD) + this.str = this.str.slice(0, offset - 1) + '�'; + // replace right as well + right.str = '�' + right.str.slice(1); + } + return right + } + + /** + * @param {ContentString} right + * @return {boolean} + */ + mergeWith (right) { + this.str += right.str; + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeString(offset === 0 ? this.str : this.str.slice(offset)); + } + + /** + * @return {number} + */ + getRef () { + return 4 + } + } + + /** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentString} + */ + const readContentString = decoder => new ContentString(decoder.readString()); + + /** + * @type {Array>} + * @private + */ + const typeRefs = [ + readYArray, + readYMap, + readYText, + readYXmlElement, + readYXmlFragment, + readYXmlHook, + readYXmlText + ]; + + const YArrayRefID = 0; + const YMapRefID = 1; + const YTextRefID = 2; + const YXmlElementRefID = 3; + const YXmlFragmentRefID = 4; + const YXmlHookRefID = 5; + const YXmlTextRefID = 6; + + /** + * @private + */ + class ContentType { + /** + * @param {AbstractType} type + */ + constructor (type) { + /** + * @type {AbstractType} + */ + this.type = type; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.type] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentType} + */ + copy () { + return new ContentType(this.type._copy()) + } + + /** + * @param {number} offset + * @return {ContentType} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {ContentType} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + this.type._integrate(transaction.doc, item); + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) { + let item = this.type._start; + while (item !== null) { + if (!item.deleted) { + item.delete(transaction); + } else { + // Whis will be gc'd later and we want to merge it if possible + // We try to merge all deleted items after each transaction, + // but we have no knowledge about that this needs to be merged + // since it is not in transaction.ds. Hence we add it to transaction._mergeStructs + transaction._mergeStructs.push(item); + } + item = item.right; + } + this.type._map.forEach(item => { + if (!item.deleted) { + item.delete(transaction); + } else { + // same as above + transaction._mergeStructs.push(item); + } + }); + transaction.changed.delete(this.type); + } + + /** + * @param {StructStore} store + */ + gc (store) { + let item = this.type._start; + while (item !== null) { + item.gc(store, true); + item = item.right; + } + this.type._start = null; + this.type._map.forEach(/** @param {Item | null} item */ (item) => { + while (item !== null) { + item.gc(store, true); + item = item.left; + } + }); + this.type._map = new Map(); + } + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + this.type._write(encoder); + } + + /** + * @return {number} + */ + getRef () { + return 7 + } + } + + /** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentType} + */ + const readContentType = decoder => new ContentType(typeRefs[decoder.readTypeRef()](decoder)); + + /** + * @todo This should return several items + * + * @param {StructStore} store + * @param {ID} id + * @return {{item:Item, diff:number}} + */ + const followRedone = (store, id) => { + /** + * @type {ID|null} + */ + let nextID = id; + let diff = 0; + let item; + do { + if (diff > 0) { + nextID = createID(nextID.client, nextID.clock + diff); + } + item = getItem(store, nextID); + diff = nextID.clock - item.id.clock; + nextID = item.redone; + } while (nextID !== null && item instanceof Item) + return { + item, diff + } + }; + + /** + * Make sure that neither item nor any of its parents is ever deleted. + * + * This property does not persist when storing it into a database or when + * sending it to other peers + * + * @param {Item|null} item + * @param {boolean} keep + */ + const keepItem = (item, keep) => { + while (item !== null && item.keep !== keep) { + item.keep = keep; + item = /** @type {AbstractType} */ (item.parent)._item; + } + }; + + /** + * Split leftItem into two items + * @param {Transaction} transaction + * @param {Item} leftItem + * @param {number} diff + * @return {Item} + * + * @function + * @private + */ + const splitItem = (transaction, leftItem, diff) => { + // create rightItem + const { client, clock } = leftItem.id; + const rightItem = new Item( + createID(client, clock + diff), + leftItem, + createID(client, clock + diff - 1), + leftItem.right, + leftItem.rightOrigin, + leftItem.parent, + leftItem.parentSub, + leftItem.content.splice(diff) + ); + if (leftItem.deleted) { + rightItem.markDeleted(); + } + if (leftItem.keep) { + rightItem.keep = true; + } + if (leftItem.redone !== null) { + rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff); + } + // update left (do not set leftItem.rightOrigin as it will lead to problems when syncing) + leftItem.right = rightItem; + // update right + if (rightItem.right !== null) { + rightItem.right.left = rightItem; + } + // right is more specific. + transaction._mergeStructs.push(rightItem); + // update parent._map + if (rightItem.parentSub !== null && rightItem.right === null) { + /** @type {AbstractType} */ (rightItem.parent)._map.set(rightItem.parentSub, rightItem); + } + leftItem.length = diff; + return rightItem + }; + + /** + * Redoes the effect of this operation. + * + * @param {Transaction} transaction The Yjs instance. + * @param {Item} item + * @param {Set} redoitems + * + * @return {Item|null} + * + * @private + */ + const redoItem = (transaction, item, redoitems) => { + const doc = transaction.doc; + const store = doc.store; + const ownClientID = doc.clientID; + const redone = item.redone; + if (redone !== null) { + return getItemCleanStart(transaction, redone) + } + let parentItem = /** @type {AbstractType} */ (item.parent)._item; + /** + * @type {Item|null} + */ + let left; + /** + * @type {Item|null} + */ + let right; + if (item.parentSub === null) { + // Is an array item. Insert at the old position + left = item.left; + right = item; + } else { + // Is a map item. Insert as current value + left = item; + while (left.right !== null) { + left = left.right; + if (left.id.client !== ownClientID) { + // It is not possible to redo this item because it conflicts with a + // change from another client + return null + } + } + if (left.right !== null) { + left = /** @type {Item} */ (/** @type {AbstractType} */ (item.parent)._map.get(item.parentSub)); + } + right = null; + } + // make sure that parent is redone + if (parentItem !== null && parentItem.deleted === true && parentItem.redone === null) { + // try to undo parent if it will be undone anyway + if (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems) === null) { + return null + } + } + if (parentItem !== null && parentItem.redone !== null) { + while (parentItem.redone !== null) { + parentItem = getItemCleanStart(transaction, parentItem.redone); + } + // find next cloned_redo items + while (left !== null) { + /** + * @type {Item|null} + */ + let leftTrace = left; + // trace redone until parent matches + while (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item !== parentItem) { + leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone); + } + if (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item === parentItem) { + left = leftTrace; + break + } + left = left.left; + } + while (right !== null) { + /** + * @type {Item|null} + */ + let rightTrace = right; + // trace redone until parent matches + while (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item !== parentItem) { + rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone); + } + if (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item === parentItem) { + right = rightTrace; + break + } + right = right.right; + } + } + const nextClock = getState(store, ownClientID); + const nextId = createID(ownClientID, nextClock); + const redoneItem = new Item( + nextId, + left, left && left.lastId, + right, right && right.id, + parentItem === null ? item.parent : /** @type {ContentType} */ (parentItem.content).type, + item.parentSub, + item.content.copy() + ); + item.redone = nextId; + keepItem(redoneItem, true); + redoneItem.integrate(transaction, 0); + return redoneItem + }; + + /** + * Abstract class that represents any content. + */ + class Item extends AbstractStruct { + /** + * @param {ID} id + * @param {Item | null} left + * @param {ID | null} origin + * @param {Item | null} right + * @param {ID | null} rightOrigin + * @param {AbstractType|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it. + * @param {string | null} parentSub + * @param {AbstractContent} content + */ + constructor (id, left, origin, right, rightOrigin, parent, parentSub, content) { + super(id, content.getLength()); + /** + * The item that was originally to the left of this item. + * @type {ID | null} + */ + this.origin = origin; + /** + * The item that is currently to the left of this item. + * @type {Item | null} + */ + this.left = left; + /** + * The item that is currently to the right of this item. + * @type {Item | null} + */ + this.right = right; + /** + * The item that was originally to the right of this item. + * @type {ID | null} + */ + this.rightOrigin = rightOrigin; + /** + * @type {AbstractType|ID|null} + */ + this.parent = parent; + /** + * If the parent refers to this item with some kind of key (e.g. YMap, the + * key is specified here. The key is then used to refer to the list in which + * to insert this item. If `parentSub = null` type._start is the list in + * which to insert to. Otherwise it is `parent._map`. + * @type {String | null} + */ + this.parentSub = parentSub; + /** + * If this type's effect is reundone this type refers to the type that undid + * this operation. + * @type {ID | null} + */ + this.redone = null; + /** + * @type {AbstractContent} + */ + this.content = content; + /** + * bit1: keep + * bit2: countable + * bit3: deleted + * bit4: mark - mark node as fast-search-marker + * @type {number} byte + */ + this.info = this.content.isCountable() ? BIT2 : 0; + } + + /** + * This is used to mark the item as an indexed fast-search marker + * + * @type {boolean} + */ + set marker (isMarked) { + if (((this.info & BIT4) > 0) !== isMarked) { + this.info ^= BIT4; + } + } + + get marker () { + return (this.info & BIT4) > 0 + } + + /** + * If true, do not garbage collect this Item. + */ + get keep () { + return (this.info & BIT1) > 0 + } + + set keep (doKeep) { + if (this.keep !== doKeep) { + this.info ^= BIT1; + } + } + + get countable () { + return (this.info & BIT2) > 0 + } + + /** + * Whether this item was deleted or not. + * @type {Boolean} + */ + get deleted () { + return (this.info & BIT3) > 0 + } + + set deleted (doDelete) { + if (this.deleted !== doDelete) { + this.info ^= BIT3; + } + } + + markDeleted () { + this.info |= BIT3; + } + + /** + * Return the creator clientID of the missing op or define missing items and return null. + * + * @param {Transaction} transaction + * @param {StructStore} store + * @return {null | number} + */ + getMissing (transaction, store) { + if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) { + return this.origin.client + } + if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) { + return this.rightOrigin.client + } + if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) { + return this.parent.client + } + + // We have all missing ids, now find the items + + if (this.origin) { + this.left = getItemCleanEnd(transaction, store, this.origin); + this.origin = this.left.lastId; + } + if (this.rightOrigin) { + this.right = getItemCleanStart(transaction, this.rightOrigin); + this.rightOrigin = this.right.id; + } + if ((this.left && this.left.constructor === GC) || (this.right && this.right.constructor === GC)) { + this.parent = null; + } + // only set parent if this shouldn't be garbage collected + if (!this.parent) { + if (this.left && this.left.constructor === Item) { + this.parent = this.left.parent; + this.parentSub = this.left.parentSub; + } + if (this.right && this.right.constructor === Item) { + this.parent = this.right.parent; + this.parentSub = this.right.parentSub; + } + } else if (this.parent.constructor === ID) { + const parentItem = getItem(store, this.parent); + if (parentItem.constructor === GC) { + this.parent = null; + } else { + this.parent = /** @type {ContentType} */ (parentItem.content).type; + } + } + return null + } + + /** + * @param {Transaction} transaction + * @param {number} offset + */ + integrate (transaction, offset) { + if (offset > 0) { + this.id.clock += offset; + this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1)); + this.origin = this.left.lastId; + this.content = this.content.splice(offset); + this.length -= offset; + } + + if (this.parent) { + if ((!this.left && (!this.right || this.right.left !== null)) || (this.left && this.left.right !== this.right)) { + /** + * @type {Item|null} + */ + let left = this.left; + + /** + * @type {Item|null} + */ + let o; + // set o to the first conflicting item + if (left !== null) { + o = left.right; + } else if (this.parentSub !== null) { + o = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null; + while (o !== null && o.left !== null) { + o = o.left; + } + } else { + o = /** @type {AbstractType} */ (this.parent)._start; + } + // TODO: use something like DeleteSet here (a tree implementation would be best) + // @todo use global set definitions + /** + * @type {Set} + */ + const conflictingItems = new Set(); + /** + * @type {Set} + */ + const itemsBeforeOrigin = new Set(); + // Let c in conflictingItems, b in itemsBeforeOrigin + // ***{origin}bbbb{this}{c,b}{c,b}{o}*** + // Note that conflictingItems is a subset of itemsBeforeOrigin + while (o !== null && o !== this.right) { + itemsBeforeOrigin.add(o); + conflictingItems.add(o); + if (compareIDs(this.origin, o.origin)) { + // case 1 + if (o.id.client < this.id.client) { + left = o; + conflictingItems.clear(); + } else if (compareIDs(this.rightOrigin, o.rightOrigin)) { + // this and o are conflicting and point to the same integration points. The id decides which item comes first. + // Since this is to the left of o, we can break here + break + } // else, o might be integrated before an item that this conflicts with. If so, we will find it in the next iterations + } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) { // use getItem instead of getItemCleanEnd because we don't want / need to split items. + // case 2 + if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) { + left = o; + conflictingItems.clear(); + } + } else { + break + } + o = o.right; + } + this.left = left; + } + // reconnect left/right + update parent map/start if necessary + if (this.left !== null) { + const right = this.left.right; + this.right = right; + this.left.right = this; + } else { + let r; + if (this.parentSub !== null) { + r = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null; + while (r !== null && r.left !== null) { + r = r.left; + } + } else { + r = /** @type {AbstractType} */ (this.parent)._start + ;/** @type {AbstractType} */ (this.parent)._start = this; + } + this.right = r; + } + if (this.right !== null) { + this.right.left = this; + } else if (this.parentSub !== null) { + // set as current parent value if right === null and this is parentSub + /** @type {AbstractType} */ (this.parent)._map.set(this.parentSub, this); + if (this.left !== null) { + // this is the current attribute value of parent. delete right + this.left.delete(transaction); + } + } + // adjust length of parent + if (this.parentSub === null && this.countable && !this.deleted) { + /** @type {AbstractType} */ (this.parent)._length += this.length; + } + addStruct(transaction.doc.store, this); + this.content.integrate(transaction, this); + // add parent to transaction.changed + addChangedTypeToTransaction(transaction, /** @type {AbstractType} */ (this.parent), this.parentSub); + if ((/** @type {AbstractType} */ (this.parent)._item !== null && /** @type {AbstractType} */ (this.parent)._item.deleted) || (this.parentSub !== null && this.right !== null)) { + // delete if parent is deleted or if this is not the current attribute value of parent + this.delete(transaction); + } + } else { + // parent is not defined. Integrate GC struct instead + new GC(this.id, this.length).integrate(transaction, 0); + } + } + + /** + * Returns the next non-deleted item + */ + get next () { + let n = this.right; + while (n !== null && n.deleted) { + n = n.right; + } + return n + } + + /** + * Returns the previous non-deleted item + */ + get prev () { + let n = this.left; + while (n !== null && n.deleted) { + n = n.left; + } + return n + } + + /** + * Computes the last content address of this Item. + */ + get lastId () { + // allocating ids is pretty costly because of the amount of ids created, so we try to reuse whenever possible + return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1) + } + + /** + * Try to merge two items + * + * @param {Item} right + * @return {boolean} + */ + mergeWith (right) { + if ( + compareIDs(right.origin, this.lastId) && + this.right === right && + compareIDs(this.rightOrigin, right.rightOrigin) && + this.id.client === right.id.client && + this.id.clock + this.length === right.id.clock && + this.deleted === right.deleted && + this.redone === null && + right.redone === null && + this.content.constructor === right.content.constructor && + this.content.mergeWith(right.content) + ) { + if (right.keep) { + this.keep = true; + } + this.right = right.right; + if (this.right !== null) { + this.right.left = this; + } + this.length += right.length; + return true + } + return false + } + + /** + * Mark this Item as deleted. + * + * @param {Transaction} transaction + */ + delete (transaction) { + if (!this.deleted) { + const parent = /** @type {AbstractType} */ (this.parent); + // adjust the length of parent + if (this.countable && this.parentSub === null) { + parent._length -= this.length; + } + this.markDeleted(); + addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length); + addChangedTypeToTransaction(transaction, parent, this.parentSub); + this.content.delete(transaction); + } + } + + /** + * @param {StructStore} store + * @param {boolean} parentGCd + */ + gc (store, parentGCd) { + if (!this.deleted) { + throw unexpectedCase() + } + this.content.gc(store); + if (parentGCd) { + replaceStruct(store, this, new GC(this.id, this.length)); + } else { + this.content = new ContentDeleted(this.length); + } + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {AbstractUpdateEncoder} encoder The encoder to write data to. + * @param {number} offset + */ + write (encoder, offset) { + const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin; + const rightOrigin = this.rightOrigin; + const parentSub = this.parentSub; + const info = (this.content.getRef() & BITS5) | + (origin === null ? 0 : BIT8) | // origin is defined + (rightOrigin === null ? 0 : BIT7) | // right origin is defined + (parentSub === null ? 0 : BIT6); // parentSub is non-null + encoder.writeInfo(info); + if (origin !== null) { + encoder.writeLeftID(origin); + } + if (rightOrigin !== null) { + encoder.writeRightID(rightOrigin); + } + if (origin === null && rightOrigin === null) { + const parent = /** @type {AbstractType} */ (this.parent); + const parentItem = parent._item; + if (parentItem === null) { + // parent type on y._map + // find the correct key + const ykey = findRootTypeKey(parent); + encoder.writeParentInfo(true); // write parentYKey + encoder.writeString(ykey); + } else { + encoder.writeParentInfo(false); // write parent id + encoder.writeLeftID(parentItem.id); + } + if (parentSub !== null) { + encoder.writeString(parentSub); + } + } + this.content.write(encoder, offset); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @param {number} info + */ + const readItemContent = (decoder, info) => contentRefs[info & BITS5](decoder); + + /** + * A lookup map for reading Item content. + * + * @type {Array} + */ + const contentRefs = [ + () => { throw unexpectedCase() }, // GC is not ItemContent + readContentDeleted, // 1 + readContentJSON, // 2 + readContentBinary, // 3 + readContentString, // 4 + readContentEmbed, // 5 + readContentFormat, // 6 + readContentType, // 7 + readContentAny, // 8 + readContentDoc // 9 + ]; + + /** + * Do not implement this class! + */ + class AbstractContent { + /** + * @return {number} + */ + getLength () { + throw methodUnimplemented() + } + + /** + * @return {Array} + */ + getContent () { + throw methodUnimplemented() + } + + /** + * Should return false if this Item is some kind of meta information + * (e.g. format information). + * + * * Whether this Item should be addressable via `yarray.get(i)` + * * Whether this Item should be counted when computing yarray.length + * + * @return {boolean} + */ + isCountable () { + throw methodUnimplemented() + } + + /** + * @return {AbstractContent} + */ + copy () { + throw methodUnimplemented() + } + + /** + * @param {number} offset + * @return {AbstractContent} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {AbstractContent} right + * @return {boolean} + */ + mergeWith (right) { + throw methodUnimplemented() + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + throw methodUnimplemented() + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) { + throw methodUnimplemented() + } + + /** + * @param {StructStore} store + */ + gc (store) { + throw methodUnimplemented() + } + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + throw methodUnimplemented() + } + + /** + * @return {number} + */ + getRef () { + throw methodUnimplemented() + } + } + + var Y = /*#__PURE__*/Object.freeze({ + __proto__: null, + AbstractConnector: AbstractConnector, + DeleteItem: DeleteItem, + DeleteSet: DeleteSet, + iterateDeletedStructs: iterateDeletedStructs, + findIndexDS: findIndexDS, + isDeleted: isDeleted, + sortAndMergeDeleteSet: sortAndMergeDeleteSet, + mergeDeleteSets: mergeDeleteSets, + addToDeleteSet: addToDeleteSet, + createDeleteSet: createDeleteSet, + createDeleteSetFromStructStore: createDeleteSetFromStructStore, + writeDeleteSet: writeDeleteSet, + readDeleteSet: readDeleteSet, + readAndApplyDeleteSet: readAndApplyDeleteSet, + generateNewClientId: generateNewClientId, + Doc: Doc, + AbstractDSDecoder: AbstractDSDecoder, + AbstractUpdateDecoder: AbstractUpdateDecoder, + DSDecoderV1: DSDecoderV1, + UpdateDecoderV1: UpdateDecoderV1, + DSDecoderV2: DSDecoderV2, + UpdateDecoderV2: UpdateDecoderV2, + AbstractDSEncoder: AbstractDSEncoder, + AbstractUpdateEncoder: AbstractUpdateEncoder, + DSEncoderV1: DSEncoderV1, + UpdateEncoderV1: UpdateEncoderV1, + DSEncoderV2: DSEncoderV2, + UpdateEncoderV2: UpdateEncoderV2, + get DefaultDSEncoder () { return DefaultDSEncoder; }, + get DefaultDSDecoder () { return DefaultDSDecoder; }, + get DefaultUpdateEncoder () { return DefaultUpdateEncoder; }, + get DefaultUpdateDecoder () { return DefaultUpdateDecoder; }, + useV1Encoding: useV1Encoding, + useV2Encoding: useV2Encoding, + writeClientsStructs: writeClientsStructs, + readClientsStructRefs: readClientsStructRefs, + tryResumePendingDeleteReaders: tryResumePendingDeleteReaders, + writeStructsFromTransaction: writeStructsFromTransaction, + readStructs: readStructs, + readUpdateV2: readUpdateV2, + readUpdate: readUpdate, + applyUpdateV2: applyUpdateV2, + applyUpdate: applyUpdate, + writeStateAsUpdate: writeStateAsUpdate, + encodeStateAsUpdateV2: encodeStateAsUpdateV2, + encodeStateAsUpdate: encodeStateAsUpdate, + readStateVector: readStateVector, + decodeStateVectorV2: decodeStateVectorV2, + decodeStateVector: decodeStateVector, + writeStateVector: writeStateVector, + writeDocumentStateVector: writeDocumentStateVector, + encodeStateVectorV2: encodeStateVectorV2, + encodeStateVector: encodeStateVector, + EventHandler: EventHandler, + createEventHandler: createEventHandler, + addEventHandlerListener: addEventHandlerListener, + removeEventHandlerListener: removeEventHandlerListener, + removeAllEventHandlerListeners: removeAllEventHandlerListeners, + callEventHandlerListeners: callEventHandlerListeners, + ID: ID, + compareIDs: compareIDs, + createID: createID, + writeID: writeID, + readID: readID, + findRootTypeKey: findRootTypeKey, + isParentOf: isParentOf, + logType: logType, + PermanentUserData: PermanentUserData, + RelativePosition: RelativePosition, + createRelativePositionFromJSON: createRelativePositionFromJSON, + AbsolutePosition: AbsolutePosition, + createAbsolutePosition: createAbsolutePosition, + createRelativePosition: createRelativePosition, + createRelativePositionFromTypeIndex: createRelativePositionFromTypeIndex, + writeRelativePosition: writeRelativePosition, + encodeRelativePosition: encodeRelativePosition, + readRelativePosition: readRelativePosition, + decodeRelativePosition: decodeRelativePosition, + createAbsolutePositionFromRelativePosition: createAbsolutePositionFromRelativePosition, + compareRelativePositions: compareRelativePositions, + Snapshot: Snapshot, + equalSnapshots: equalSnapshots, + encodeSnapshotV2: encodeSnapshotV2, + encodeSnapshot: encodeSnapshot, + decodeSnapshotV2: decodeSnapshotV2, + decodeSnapshot: decodeSnapshot, + createSnapshot: createSnapshot, + emptySnapshot: emptySnapshot, + snapshot: snapshot, + isVisible: isVisible, + splitSnapshotAffectedStructs: splitSnapshotAffectedStructs, + createDocFromSnapshot: createDocFromSnapshot, + StructStore: StructStore, + getStateVector: getStateVector, + getState: getState, + integretyCheck: integretyCheck, + addStruct: addStruct, + findIndexSS: findIndexSS, + find: find, + getItem: getItem, + findIndexCleanStart: findIndexCleanStart, + getItemCleanStart: getItemCleanStart, + getItemCleanEnd: getItemCleanEnd, + replaceStruct: replaceStruct, + iterateStructs: iterateStructs, + Transaction: Transaction, + writeUpdateMessageFromTransaction: writeUpdateMessageFromTransaction, + nextID: nextID, + addChangedTypeToTransaction: addChangedTypeToTransaction, + tryGc: tryGc, + transact: transact, + UndoManager: UndoManager, + YEvent: YEvent, + ArraySearchMarker: ArraySearchMarker, + findMarker: findMarker, + updateMarkerChanges: updateMarkerChanges, + getTypeChildren: getTypeChildren, + callTypeObservers: callTypeObservers, + AbstractType: AbstractType, + typeListToArray: typeListToArray, + typeListToArraySnapshot: typeListToArraySnapshot, + typeListForEach: typeListForEach, + typeListMap: typeListMap, + typeListCreateIterator: typeListCreateIterator, + typeListForEachSnapshot: typeListForEachSnapshot, + typeListGet: typeListGet, + typeListInsertGenericsAfter: typeListInsertGenericsAfter, + typeListInsertGenerics: typeListInsertGenerics, + typeListDelete: typeListDelete, + typeMapDelete: typeMapDelete, + typeMapSet: typeMapSet, + typeMapGet: typeMapGet, + typeMapGetAll: typeMapGetAll, + typeMapHas: typeMapHas, + typeMapGetSnapshot: typeMapGetSnapshot, + createMapIterator: createMapIterator, + YArrayEvent: YArrayEvent, + YArray: YArray, + readYArray: readYArray, + YMapEvent: YMapEvent, + YMap: YMap, + readYMap: readYMap, + ItemTextListPosition: ItemTextListPosition, + cleanupYTextFormatting: cleanupYTextFormatting, + YTextEvent: YTextEvent, + YText: YText, + readYText: readYText, + YXmlTreeWalker: YXmlTreeWalker, + YXmlFragment: YXmlFragment, + readYXmlFragment: readYXmlFragment, + YXmlElement: YXmlElement, + readYXmlElement: readYXmlElement, + YXmlEvent: YXmlEvent, + YXmlHook: YXmlHook, + readYXmlHook: readYXmlHook, + YXmlText: YXmlText, + readYXmlText: readYXmlText, + AbstractStruct: AbstractStruct, + structGCRefNumber: structGCRefNumber, + GC: GC, + ContentBinary: ContentBinary, + readContentBinary: readContentBinary, + ContentDeleted: ContentDeleted, + readContentDeleted: readContentDeleted, + ContentDoc: ContentDoc, + readContentDoc: readContentDoc, + ContentEmbed: ContentEmbed, + readContentEmbed: readContentEmbed, + ContentFormat: ContentFormat, + readContentFormat: readContentFormat, + ContentJSON: ContentJSON, + readContentJSON: readContentJSON, + ContentAny: ContentAny, + readContentAny: readContentAny, + ContentString: ContentString, + readContentString: readContentString, + typeRefs: typeRefs, + YArrayRefID: YArrayRefID, + YMapRefID: YMapRefID, + YTextRefID: YTextRefID, + YXmlElementRefID: YXmlElementRefID, + YXmlFragmentRefID: YXmlFragmentRefID, + YXmlHookRefID: YXmlHookRefID, + YXmlTextRefID: YXmlTextRefID, + ContentType: ContentType, + readContentType: readContentType, + followRedone: followRedone, + keepItem: keepItem, + splitItem: splitItem, + redoItem: redoItem, + Item: Item, + readItemContent: readItemContent, + contentRefs: contentRefs, + AbstractContent: AbstractContent + }); + + /** + * @module sync-protocol + */ + + /** + * @typedef {Map} StateMap + */ + + /** + * Core Yjs defines three message types: + * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2. + * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the the client is assured that + * it received all information from the remote client. + * + * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection + * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both + * SyncStep2 and SyncDone, it is assured that it is synced to the remote client. + * + * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1. + * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies + * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the + * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can + * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them. + * Therefore it is necesarry that the client initiates the sync. + * + * Construction of a message: + * [messageType : varUint, message definition..] + * + * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol! + * + * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer) + */ + + const messageYjsSyncStep1 = 0; + const messageYjsSyncStep2 = 1; + const messageYjsUpdate = 2; + + /** + * Create a sync step 1 message based on the state of the current shared document. + * + * @param {encoding.Encoder} encoder + * @param {Y.Doc} doc + */ + const writeSyncStep1 = (encoder, doc) => { + writeVarUint(encoder, messageYjsSyncStep1); + const sv = encodeStateVector(doc); + writeVarUint8Array(encoder, sv); + }; + + /** + * @param {encoding.Encoder} encoder + * @param {Y.Doc} doc + * @param {Uint8Array} [encodedStateVector] + */ + const writeSyncStep2 = (encoder, doc, encodedStateVector) => { + writeVarUint(encoder, messageYjsSyncStep2); + writeVarUint8Array(encoder, encodeStateAsUpdate(doc, encodedStateVector)); + }; + + /** + * Read SyncStep1 message and reply with SyncStep2. + * + * @param {decoding.Decoder} decoder The reply to the received message + * @param {encoding.Encoder} encoder The received message + * @param {Y.Doc} doc + */ + const readSyncStep1 = (decoder, encoder, doc) => + writeSyncStep2(encoder, doc, readVarUint8Array(decoder)); + + /** + * Read and apply Structs and then DeleteStore to a y instance. + * + * @param {decoding.Decoder} decoder + * @param {Y.Doc} doc + * @param {any} transactionOrigin + */ + const readSyncStep2 = (decoder, doc, transactionOrigin) => { + applyUpdate(doc, readVarUint8Array(decoder), transactionOrigin); + }; + + /** + * @param {encoding.Encoder} encoder + * @param {Uint8Array} update + */ + const writeUpdate = (encoder, update) => { + writeVarUint(encoder, messageYjsUpdate); + writeVarUint8Array(encoder, update); + }; + + /** + * Read and apply Structs and then DeleteStore to a y instance. + * + * @param {decoding.Decoder} decoder + * @param {Y.Doc} doc + * @param {any} transactionOrigin + */ + const readUpdate$1 = readSyncStep2; + + /** + * @param {decoding.Decoder} decoder A message received from another client + * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty. + * @param {Y.Doc} doc + * @param {any} transactionOrigin + */ + const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => { + const messageType = readVarUint(decoder); + switch (messageType) { + case messageYjsSyncStep1: + readSyncStep1(decoder, encoder, doc); + break + case messageYjsSyncStep2: + readSyncStep2(decoder, doc, transactionOrigin); + break + case messageYjsUpdate: + readUpdate$1(decoder, doc, transactionOrigin); + break + default: + throw new Error('Unknown message type') + } + return messageType + }; + + if (typeof window !== 'undefined') { + // @ts-ignore + window.Y = Y; // eslint-disable-line + } + + /** + * @param {TestYInstance} y // publish message created by `y` to all other online clients + * @param {Uint8Array} m + */ + const broadcastMessage = (y, m) => { + if (y.tc.onlineConns.has(y)) { + y.tc.onlineConns.forEach(remoteYInstance => { + if (remoteYInstance !== y) { + remoteYInstance._receive(m, y); + } + }); + } + }; + + class TestYInstance extends Doc { + /** + * @param {TestConnector} testConnector + * @param {number} clientID + */ + constructor (testConnector, clientID) { + super(); + this.userID = clientID; // overwriting clientID + /** + * @type {TestConnector} + */ + this.tc = testConnector; + /** + * @type {Map>} + */ + this.receiving = new Map(); + testConnector.allConns.add(this); + // set up observe on local model + this.on('update', /** @param {Uint8Array} update @param {any} origin */ (update, origin) => { + if (origin !== testConnector) { + const encoder = createEncoder(); + writeUpdate(encoder, update); + broadcastMessage(this, toUint8Array(encoder)); + } + }); + this.connect(); + } + + /** + * Disconnect from TestConnector. + */ + disconnect () { + this.receiving = new Map(); + this.tc.onlineConns.delete(this); + } + + /** + * Append yourself to the list of known Y instances in testconnector. + * Also initiate sync with all clients. + */ + connect () { + if (!this.tc.onlineConns.has(this)) { + this.tc.onlineConns.add(this); + const encoder = createEncoder(); + writeSyncStep1(encoder, this); + // publish SyncStep1 + broadcastMessage(this, toUint8Array(encoder)); + this.tc.onlineConns.forEach(remoteYInstance => { + if (remoteYInstance !== this) { + // remote instance sends instance to this instance + const encoder = createEncoder(); + writeSyncStep1(encoder, remoteYInstance); + this._receive(toUint8Array(encoder), remoteYInstance); + } + }); + } + } + + /** + * Receive a message from another client. This message is only appended to the list of receiving messages. + * TestConnector decides when this client actually reads this message. + * + * @param {Uint8Array} message + * @param {TestYInstance} remoteClient + */ + _receive (message, remoteClient) { + let messages = this.receiving.get(remoteClient); + if (messages === undefined) { + messages = []; + this.receiving.set(remoteClient, messages); + } + messages.push(message); + } + } + + /** + * Keeps track of TestYInstances. + * + * The TestYInstances add/remove themselves from the list of connections maiained in this object. + * I think it makes sense. Deal with it. + */ + class TestConnector { + /** + * @param {prng.PRNG} gen + */ + constructor (gen) { + /** + * @type {Set} + */ + this.allConns = new Set(); + /** + * @type {Set} + */ + this.onlineConns = new Set(); + /** + * @type {prng.PRNG} + */ + this.prng = gen; + } + + /** + * Create a new Y instance and add it to the list of connections + * @param {number} clientID + */ + createY (clientID) { + return new TestYInstance(this, clientID) + } + + /** + * Choose random connection and flush a random message from a random sender. + * + * If this function was unable to flush a message, because there are no more messages to flush, it returns false. true otherwise. + * @return {boolean} + */ + flushRandomMessage () { + const gen = this.prng; + const conns = Array.from(this.onlineConns).filter(conn => conn.receiving.size > 0); + if (conns.length > 0) { + const receiver = oneOf(gen, conns); + const [sender, messages] = oneOf(gen, Array.from(receiver.receiving)); + const m = messages.shift(); + if (messages.length === 0) { + receiver.receiving.delete(sender); + } + if (m === undefined) { + return this.flushRandomMessage() + } + const encoder = createEncoder(); + // console.log('receive (' + sender.userID + '->' + receiver.userID + '):\n', syncProtocol.stringifySyncMessage(decoding.createDecoder(m), receiver)) + // do not publish data created when this function is executed (could be ss2 or update message) + readSyncMessage(createDecoder(m), encoder, receiver, receiver.tc); + if (length$1(encoder) > 0) { + // send reply message + sender._receive(toUint8Array(encoder), receiver); + } + return true + } + return false + } + + /** + * @return {boolean} True iff this function actually flushed something + */ + flushAllMessages () { + let didSomething = false; + while (this.flushRandomMessage()) { + didSomething = true; + } + return didSomething + } + + reconnectAll () { + this.allConns.forEach(conn => conn.connect()); + } + + disconnectAll () { + this.allConns.forEach(conn => conn.disconnect()); + } + + syncAll () { + this.reconnectAll(); + this.flushAllMessages(); + } + + /** + * @return {boolean} Whether it was possible to disconnect a randon connection. + */ + disconnectRandom () { + if (this.onlineConns.size === 0) { + return false + } + oneOf(this.prng, Array.from(this.onlineConns)).disconnect(); + return true + } + + /** + * @return {boolean} Whether it was possible to reconnect a random connection. + */ + reconnectRandom () { + /** + * @type {Array} + */ + const reconnectable = []; + this.allConns.forEach(conn => { + if (!this.onlineConns.has(conn)) { + reconnectable.push(conn); + } + }); + if (reconnectable.length === 0) { + return false + } + oneOf(this.prng, reconnectable).connect(); + return true + } + } + + /** + * @template T + * @param {t.TestCase} tc + * @param {{users?:number}} conf + * @param {InitTestObjectCallback} [initTestObject] + * @return {{testObjects:Array,testConnector:TestConnector,users:Array,array0:Y.YArray,array1:Y.YArray,array2:Y.YArray,map0:Y.YMap,map1:Y.YMap,map2:Y.YMap,map3:Y.YMap,text0:Y.YText,text1:Y.YText,text2:Y.YText,xml0:Y.YXmlElement,xml1:Y.YXmlElement,xml2:Y.YXmlElement}} + */ + const init = (tc, { users = 5 } = {}, initTestObject) => { + /** + * @type {Object} + */ + const result = { + users: [] + }; + const gen = tc.prng; + // choose an encoding approach at random + if (bool(gen)) { + useV2Encoding(); + } else { + useV1Encoding(); + } + + const testConnector = new TestConnector(gen); + result.testConnector = testConnector; + for (let i = 0; i < users; i++) { + const y = testConnector.createY(i); + y.clientID = i; + result.users.push(y); + result['array' + i] = y.getArray('array'); + result['map' + i] = y.getMap('map'); + result['xml' + i] = y.get('xml', YXmlElement); + result['text' + i] = y.getText('text'); + } + testConnector.syncAll(); + result.testObjects = result.users.map(initTestObject || (() => null)); + useV1Encoding(); + return /** @type {any} */ (result) + }; + + /** + * 1. reconnect and flush all + * 2. user 0 gc + * 3. get type content + * 4. disconnect & reconnect all (so gc is propagated) + * 5. compare os, ds, ss + * + * @param {Array} users + */ + const compare$1 = users => { + users.forEach(u => u.connect()); + while (users[0].tc.flushAllMessages()) {} + const userArrayValues = users.map(u => u.getArray('array').toJSON()); + const userMapValues = users.map(u => u.getMap('map').toJSON()); + const userXmlValues = users.map(u => u.get('xml', YXmlElement).toString()); + const userTextValues = users.map(u => u.getText('text').toDelta()); + for (const u of users) { + assert(u.store.pendingDeleteReaders.length === 0); + assert(u.store.pendingStack.length === 0); + assert(u.store.pendingClientsStructRefs.size === 0); + } + // Test Array iterator + compare(users[0].getArray('array').toArray(), Array.from(users[0].getArray('array'))); + // Test Map iterator + const ymapkeys = Array.from(users[0].getMap('map').keys()); + assert(ymapkeys.length === Object.keys(userMapValues[0]).length); + ymapkeys.forEach(key => assert(hasProperty(userMapValues[0], key))); + /** + * @type {Object} + */ + const mapRes = {}; + for (const [k, v] of users[0].getMap('map')) { + mapRes[k] = v instanceof AbstractType ? v.toJSON() : v; + } + compare(userMapValues[0], mapRes); + // Compare all users + for (let i = 0; i < users.length - 1; i++) { + compare(userArrayValues[i].length, users[i].getArray('array').length); + compare(userArrayValues[i], userArrayValues[i + 1]); + compare(userMapValues[i], userMapValues[i + 1]); + compare(userXmlValues[i], userXmlValues[i + 1]); + compare(userTextValues[i].map(/** @param {any} a */ a => typeof a.insert === 'string' ? a.insert : ' ').join('').length, users[i].getText('text').length); + compare(userTextValues[i], userTextValues[i + 1]); + compare(getStateVector(users[i].store), getStateVector(users[i + 1].store)); + compareDS(createDeleteSetFromStructStore(users[i].store), createDeleteSetFromStructStore(users[i + 1].store)); + compareStructStores(users[i].store, users[i + 1].store); + } + users.map(u => u.destroy()); + }; + + /** + * @param {Y.Item?} a + * @param {Y.Item?} b + * @return {boolean} + */ + const compareItemIDs = (a, b) => a === b || (a !== null && b != null && compareIDs(a.id, b.id)); + + /** + * @param {Y.StructStore} ss1 + * @param {Y.StructStore} ss2 + */ + const compareStructStores = (ss1, ss2) => { + assert(ss1.clients.size === ss2.clients.size); + for (const [client, structs1] of ss1.clients) { + const structs2 = /** @type {Array} */ (ss2.clients.get(client)); + assert(structs2 !== undefined && structs1.length === structs2.length); + for (let i = 0; i < structs1.length; i++) { + const s1 = structs1[i]; + const s2 = structs2[i]; + // checks for abstract struct + if ( + s1.constructor !== s2.constructor || + !compareIDs(s1.id, s2.id) || + s1.deleted !== s2.deleted || + // @ts-ignore + s1.length !== s2.length + ) { + fail('Structs dont match'); + } + if (s1 instanceof Item) { + if ( + !(s2 instanceof Item) || + !((s1.left === null && s2.left === null) || (s1.left !== null && s2.left !== null && compareIDs(s1.left.lastId, s2.left.lastId))) || + !compareItemIDs(s1.right, s2.right) || + !compareIDs(s1.origin, s2.origin) || + !compareIDs(s1.rightOrigin, s2.rightOrigin) || + s1.parentSub !== s2.parentSub + ) { + return fail('Items dont match') + } + // make sure that items are connected correctly + assert(s1.left === null || s1.left.right === s1); + assert(s1.right === null || s1.right.left === s1); + assert(s2.left === null || s2.left.right === s2); + assert(s2.right === null || s2.right.left === s2); + } + } + } + }; + + /** + * @param {Y.DeleteSet} ds1 + * @param {Y.DeleteSet} ds2 + */ + const compareDS = (ds1, ds2) => { + assert(ds1.clients.size === ds2.clients.size); + ds1.clients.forEach((deleteItems1, client) => { + const deleteItems2 = /** @type {Array} */ (ds2.clients.get(client)); + assert(deleteItems2 !== undefined && deleteItems1.length === deleteItems2.length); + for (let i = 0; i < deleteItems1.length; i++) { + const di1 = deleteItems1[i]; + const di2 = deleteItems2[i]; + if (di1.clock !== di2.clock || di1.len !== di2.len) { + fail('DeleteSets dont match'); + } + } + }); + }; + + /** + * @template T + * @callback InitTestObjectCallback + * @param {TestYInstance} y + * @return {T} + */ + + /** + * @template T + * @param {t.TestCase} tc + * @param {Array} mods + * @param {number} iterations + * @param {InitTestObjectCallback} [initTestObject] + */ + const applyRandomTests = (tc, mods, iterations, initTestObject) => { + const gen = tc.prng; + const result = init(tc, { users: 5 }, initTestObject); + const { testConnector, users } = result; + for (let i = 0; i < iterations; i++) { + if (int32(gen, 0, 100) <= 2) { + // 2% chance to disconnect/reconnect a random user + if (bool(gen)) { + testConnector.disconnectRandom(); + } else { + testConnector.reconnectRandom(); + } + } else if (int32(gen, 0, 100) <= 1) { + // 1% chance to flush all + testConnector.flushAllMessages(); + } else if (int32(gen, 0, 100) <= 50) { + // 50% chance to flush a random message + testConnector.flushRandomMessage(); + } + const user = int32(gen, 0, users.length - 1); + const test = oneOf(gen, mods); + test(users[user], gen, result.testObjects[user]); + } + compare$1(users); + return result + }; + + // ::- Persistent data structure representing an ordered mapping from + // strings to values, with some convenient update methods. + function OrderedMap(content) { + this.content = content; + } + + OrderedMap.prototype = { + constructor: OrderedMap, + + find: function(key) { + for (var i = 0; i < this.content.length; i += 2) + if (this.content[i] === key) return i + return -1 + }, + + // :: (string) → ?any + // Retrieve the value stored under `key`, or return undefined when + // no such key exists. + get: function(key) { + var found = this.find(key); + return found == -1 ? undefined : this.content[found + 1] + }, + + // :: (string, any, ?string) → OrderedMap + // Create a new map by replacing the value of `key` with a new + // value, or adding a binding to the end of the map. If `newKey` is + // given, the key of the binding will be replaced with that key. + update: function(key, value, newKey) { + var self = newKey && newKey != key ? this.remove(newKey) : this; + var found = self.find(key), content = self.content.slice(); + if (found == -1) { + content.push(newKey || key, value); + } else { + content[found + 1] = value; + if (newKey) content[found] = newKey; + } + return new OrderedMap(content) + }, + + // :: (string) → OrderedMap + // Return a map with the given key removed, if it existed. + remove: function(key) { + var found = this.find(key); + if (found == -1) return this + var content = this.content.slice(); + content.splice(found, 2); + return new OrderedMap(content) + }, + + // :: (string, any) → OrderedMap + // Add a new key to the start of the map. + addToStart: function(key, value) { + return new OrderedMap([key, value].concat(this.remove(key).content)) + }, + + // :: (string, any) → OrderedMap + // Add a new key to the end of the map. + addToEnd: function(key, value) { + var content = this.remove(key).content.slice(); + content.push(key, value); + return new OrderedMap(content) + }, + + // :: (string, string, any) → OrderedMap + // Add a key after the given key. If `place` is not found, the new + // key is added to the end. + addBefore: function(place, key, value) { + var without = this.remove(key), content = without.content.slice(); + var found = without.find(place); + content.splice(found == -1 ? content.length : found, 0, key, value); + return new OrderedMap(content) + }, + + // :: ((key: string, value: any)) + // Call the given function for each key/value pair in the map, in + // order. + forEach: function(f) { + for (var i = 0; i < this.content.length; i += 2) + f(this.content[i], this.content[i + 1]); + }, + + // :: (union) → OrderedMap + // Create a new map by prepending the keys in this map that don't + // appear in `map` before the keys in `map`. + prepend: function(map) { + map = OrderedMap.from(map); + if (!map.size) return this + return new OrderedMap(map.content.concat(this.subtract(map).content)) + }, + + // :: (union) → OrderedMap + // Create a new map by appending the keys in this map that don't + // appear in `map` after the keys in `map`. + append: function(map) { + map = OrderedMap.from(map); + if (!map.size) return this + return new OrderedMap(this.subtract(map).content.concat(map.content)) + }, + + // :: (union) → OrderedMap + // Create a map containing all the keys in this map that don't + // appear in `map`. + subtract: function(map) { + var result = this; + map = OrderedMap.from(map); + for (var i = 0; i < map.content.length; i += 2) + result = result.remove(map.content[i]); + return result + }, + + // :: number + // The amount of keys in this map. + get size() { + return this.content.length >> 1 + } + }; + + // :: (?union) → OrderedMap + // Return a map with the given content. If null, create an empty + // map. If given an ordered map, return that map itself. If given an + // object, create a map from the object's properties. + OrderedMap.from = function(value) { + if (value instanceof OrderedMap) return value + var content = []; + if (value) for (var prop in value) content.push(prop, value[prop]); + return new OrderedMap(content) + }; + + var orderedmap = OrderedMap; + + function findDiffStart(a, b, pos) { + for (var i = 0;; i++) { + if (i == a.childCount || i == b.childCount) + { return a.childCount == b.childCount ? null : pos } + + var childA = a.child(i), childB = b.child(i); + if (childA == childB) { pos += childA.nodeSize; continue } + + if (!childA.sameMarkup(childB)) { return pos } + + if (childA.isText && childA.text != childB.text) { + for (var j = 0; childA.text[j] == childB.text[j]; j++) + { pos++; } + return pos + } + if (childA.content.size || childB.content.size) { + var inner = findDiffStart(childA.content, childB.content, pos + 1); + if (inner != null) { return inner } + } + pos += childA.nodeSize; + } + } + + function findDiffEnd(a, b, posA, posB) { + for (var iA = a.childCount, iB = b.childCount;;) { + if (iA == 0 || iB == 0) + { return iA == iB ? null : {a: posA, b: posB} } + + var childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize; + if (childA == childB) { + posA -= size; posB -= size; + continue + } + + if (!childA.sameMarkup(childB)) { return {a: posA, b: posB} } + + if (childA.isText && childA.text != childB.text) { + var same = 0, minSize = Math.min(childA.text.length, childB.text.length); + while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) { + same++; posA--; posB--; + } + return {a: posA, b: posB} + } + if (childA.content.size || childB.content.size) { + var inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1); + if (inner) { return inner } + } + posA -= size; posB -= size; + } + } + + // ::- A fragment represents a node's collection of child nodes. + // + // Like nodes, fragments are persistent data structures, and you + // should not mutate them or their content. Rather, you create new + // instances whenever needed. The API tries to make this easy. + var Fragment = function Fragment(content, size) { + this.content = content; + // :: number + // The size of the fragment, which is the total of the size of its + // content nodes. + this.size = size || 0; + if (size == null) { for (var i = 0; i < content.length; i++) + { this.size += content[i].nodeSize; } } + }; + + var prototypeAccessors = { firstChild: { configurable: true },lastChild: { configurable: true },childCount: { configurable: true } }; + + // :: (number, number, (node: Node, start: number, parent: Node, index: number) → ?bool, ?number) + // Invoke a callback for all descendant nodes between the given two + // positions (relative to start of this fragment). Doesn't descend + // into a node when the callback returns `false`. + Fragment.prototype.nodesBetween = function nodesBetween (from, to, f, nodeStart, parent) { + if ( nodeStart === void 0 ) nodeStart = 0; + + for (var i = 0, pos = 0; pos < to; i++) { + var child = this.content[i], end = pos + child.nodeSize; + if (end > from && f(child, nodeStart + pos, parent, i) !== false && child.content.size) { + var start = pos + 1; + child.nodesBetween(Math.max(0, from - start), + Math.min(child.content.size, to - start), + f, nodeStart + start); + } + pos = end; + } + }; + + // :: ((node: Node, pos: number, parent: Node) → ?bool) + // Call the given callback for every descendant node. The callback + // may return `false` to prevent traversal of a given node's children. + Fragment.prototype.descendants = function descendants (f) { + this.nodesBetween(0, this.size, f); + }; + + // : (number, number, ?string, ?string) → string + Fragment.prototype.textBetween = function textBetween (from, to, blockSeparator, leafText) { + var text = "", separated = true; + this.nodesBetween(from, to, function (node, pos) { + if (node.isText) { + text += node.text.slice(Math.max(from, pos) - pos, to - pos); + separated = !blockSeparator; + } else if (node.isLeaf && leafText) { + text += leafText; + separated = !blockSeparator; + } else if (!separated && node.isBlock) { + text += blockSeparator; + separated = true; + } + }, 0); + return text + }; + + // :: (Fragment) → Fragment + // Create a new fragment containing the combined content of this + // fragment and the other. + Fragment.prototype.append = function append (other) { + if (!other.size) { return this } + if (!this.size) { return other } + var last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0; + if (last.isText && last.sameMarkup(first)) { + content[content.length - 1] = last.withText(last.text + first.text); + i = 1; + } + for (; i < other.content.length; i++) { content.push(other.content[i]); } + return new Fragment(content, this.size + other.size) + }; + + // :: (number, ?number) → Fragment + // Cut out the sub-fragment between the two given positions. + Fragment.prototype.cut = function cut (from, to) { + if (to == null) { to = this.size; } + if (from == 0 && to == this.size) { return this } + var result = [], size = 0; + if (to > from) { for (var i = 0, pos = 0; pos < to; i++) { + var child = this.content[i], end = pos + child.nodeSize; + if (end > from) { + if (pos < from || end > to) { + if (child.isText) + { child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos)); } + else + { child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1)); } + } + result.push(child); + size += child.nodeSize; + } + pos = end; + } } + return new Fragment(result, size) + }; + + Fragment.prototype.cutByIndex = function cutByIndex (from, to) { + if (from == to) { return Fragment.empty } + if (from == 0 && to == this.content.length) { return this } + return new Fragment(this.content.slice(from, to)) + }; + + // :: (number, Node) → Fragment + // Create a new fragment in which the node at the given index is + // replaced by the given node. + Fragment.prototype.replaceChild = function replaceChild (index, node) { + var current = this.content[index]; + if (current == node) { return this } + var copy = this.content.slice(); + var size = this.size + node.nodeSize - current.nodeSize; + copy[index] = node; + return new Fragment(copy, size) + }; + + // : (Node) → Fragment + // Create a new fragment by prepending the given node to this + // fragment. + Fragment.prototype.addToStart = function addToStart (node) { + return new Fragment([node].concat(this.content), this.size + node.nodeSize) + }; + + // : (Node) → Fragment + // Create a new fragment by appending the given node to this + // fragment. + Fragment.prototype.addToEnd = function addToEnd (node) { + return new Fragment(this.content.concat(node), this.size + node.nodeSize) + }; + + // :: (Fragment) → bool + // Compare this fragment to another one. + Fragment.prototype.eq = function eq (other) { + if (this.content.length != other.content.length) { return false } + for (var i = 0; i < this.content.length; i++) + { if (!this.content[i].eq(other.content[i])) { return false } } + return true + }; + + // :: ?Node + // The first child of the fragment, or `null` if it is empty. + prototypeAccessors.firstChild.get = function () { return this.content.length ? this.content[0] : null }; + + // :: ?Node + // The last child of the fragment, or `null` if it is empty. + prototypeAccessors.lastChild.get = function () { return this.content.length ? this.content[this.content.length - 1] : null }; + + // :: number + // The number of child nodes in this fragment. + prototypeAccessors.childCount.get = function () { return this.content.length }; + + // :: (number) → Node + // Get the child node at the given index. Raise an error when the + // index is out of range. + Fragment.prototype.child = function child (index) { + var found = this.content[index]; + if (!found) { throw new RangeError("Index " + index + " out of range for " + this) } + return found + }; + + // :: (number) → ?Node + // Get the child node at the given index, if it exists. + Fragment.prototype.maybeChild = function maybeChild (index) { + return this.content[index] + }; + + // :: ((node: Node, offset: number, index: number)) + // Call `f` for every child node, passing the node, its offset + // into this parent node, and its index. + Fragment.prototype.forEach = function forEach (f) { + for (var i = 0, p = 0; i < this.content.length; i++) { + var child = this.content[i]; + f(child, p, i); + p += child.nodeSize; + } + }; + + // :: (Fragment) → ?number + // Find the first position at which this fragment and another + // fragment differ, or `null` if they are the same. + Fragment.prototype.findDiffStart = function findDiffStart$1 (other, pos) { + if ( pos === void 0 ) pos = 0; + + return findDiffStart(this, other, pos) + }; + + // :: (Fragment) → ?{a: number, b: number} + // Find the first position, searching from the end, at which this + // fragment and the given fragment differ, or `null` if they are the + // same. Since this position will not be the same in both nodes, an + // object with two separate positions is returned. + Fragment.prototype.findDiffEnd = function findDiffEnd$1 (other, pos, otherPos) { + if ( pos === void 0 ) pos = this.size; + if ( otherPos === void 0 ) otherPos = other.size; + + return findDiffEnd(this, other, pos, otherPos) + }; + + // : (number, ?number) → {index: number, offset: number} + // Find the index and inner offset corresponding to a given relative + // position in this fragment. The result object will be reused + // (overwritten) the next time the function is called. (Not public.) + Fragment.prototype.findIndex = function findIndex (pos, round) { + if ( round === void 0 ) round = -1; + + if (pos == 0) { return retIndex(0, pos) } + if (pos == this.size) { return retIndex(this.content.length, pos) } + if (pos > this.size || pos < 0) { throw new RangeError(("Position " + pos + " outside of fragment (" + (this) + ")")) } + for (var i = 0, curPos = 0;; i++) { + var cur = this.child(i), end = curPos + cur.nodeSize; + if (end >= pos) { + if (end == pos || round > 0) { return retIndex(i + 1, end) } + return retIndex(i, curPos) + } + curPos = end; + } + }; + + // :: () → string + // Return a debugging string that describes this fragment. + Fragment.prototype.toString = function toString () { return "<" + this.toStringInner() + ">" }; + + Fragment.prototype.toStringInner = function toStringInner () { return this.content.join(", ") }; + + // :: () → ?Object + // Create a JSON-serializeable representation of this fragment. + Fragment.prototype.toJSON = function toJSON () { + return this.content.length ? this.content.map(function (n) { return n.toJSON(); }) : null + }; + + // :: (Schema, ?Object) → Fragment + // Deserialize a fragment from its JSON representation. + Fragment.fromJSON = function fromJSON (schema, value) { + if (!value) { return Fragment.empty } + if (!Array.isArray(value)) { throw new RangeError("Invalid input for Fragment.fromJSON") } + return new Fragment(value.map(schema.nodeFromJSON)) + }; + + // :: ([Node]) → Fragment + // Build a fragment from an array of nodes. Ensures that adjacent + // text nodes with the same marks are joined together. + Fragment.fromArray = function fromArray (array) { + if (!array.length) { return Fragment.empty } + var joined, size = 0; + for (var i = 0; i < array.length; i++) { + var node = array[i]; + size += node.nodeSize; + if (i && node.isText && array[i - 1].sameMarkup(node)) { + if (!joined) { joined = array.slice(0, i); } + joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text); + } else if (joined) { + joined.push(node); + } + } + return new Fragment(joined || array, size) + }; + + // :: (?union) → Fragment + // Create a fragment from something that can be interpreted as a set + // of nodes. For `null`, it returns the empty fragment. For a + // fragment, the fragment itself. For a node or array of nodes, a + // fragment containing those nodes. + Fragment.from = function from (nodes) { + if (!nodes) { return Fragment.empty } + if (nodes instanceof Fragment) { return nodes } + if (Array.isArray(nodes)) { return this.fromArray(nodes) } + if (nodes.attrs) { return new Fragment([nodes], nodes.nodeSize) } + throw new RangeError("Can not convert " + nodes + " to a Fragment" + + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : "")) + }; + + Object.defineProperties( Fragment.prototype, prototypeAccessors ); + + var found = {index: 0, offset: 0}; + function retIndex(index, offset) { + found.index = index; + found.offset = offset; + return found + } + + // :: Fragment + // An empty fragment. Intended to be reused whenever a node doesn't + // contain anything (rather than allocating a new empty fragment for + // each leaf node). + Fragment.empty = new Fragment([], 0); + + function compareDeep(a, b) { + if (a === b) { return true } + if (!(a && typeof a == "object") || + !(b && typeof b == "object")) { return false } + var array = Array.isArray(a); + if (Array.isArray(b) != array) { return false } + if (array) { + if (a.length != b.length) { return false } + for (var i = 0; i < a.length; i++) { if (!compareDeep(a[i], b[i])) { return false } } + } else { + for (var p in a) { if (!(p in b) || !compareDeep(a[p], b[p])) { return false } } + for (var p$1 in b) { if (!(p$1 in a)) { return false } } + } + return true + } + + // ::- A mark is a piece of information that can be attached to a node, + // such as it being emphasized, in code font, or a link. It has a type + // and optionally a set of attributes that provide further information + // (such as the target of the link). Marks are created through a + // `Schema`, which controls which types exist and which + // attributes they have. + var Mark = function Mark(type, attrs) { + // :: MarkType + // The type of this mark. + this.type = type; + // :: Object + // The attributes associated with this mark. + this.attrs = attrs; + }; + + // :: ([Mark]) → [Mark] + // Given a set of marks, create a new set which contains this one as + // well, in the right position. If this mark is already in the set, + // the set itself is returned. If any marks that are set to be + // [exclusive](#model.MarkSpec.excludes) with this mark are present, + // those are replaced by this one. + Mark.prototype.addToSet = function addToSet (set) { + var copy, placed = false; + for (var i = 0; i < set.length; i++) { + var other = set[i]; + if (this.eq(other)) { return set } + if (this.type.excludes(other.type)) { + if (!copy) { copy = set.slice(0, i); } + } else if (other.type.excludes(this.type)) { + return set + } else { + if (!placed && other.type.rank > this.type.rank) { + if (!copy) { copy = set.slice(0, i); } + copy.push(this); + placed = true; + } + if (copy) { copy.push(other); } + } + } + if (!copy) { copy = set.slice(); } + if (!placed) { copy.push(this); } + return copy + }; + + // :: ([Mark]) → [Mark] + // Remove this mark from the given set, returning a new set. If this + // mark is not in the set, the set itself is returned. + Mark.prototype.removeFromSet = function removeFromSet (set) { + for (var i = 0; i < set.length; i++) + { if (this.eq(set[i])) + { return set.slice(0, i).concat(set.slice(i + 1)) } } + return set + }; + + // :: ([Mark]) → bool + // Test whether this mark is in the given set of marks. + Mark.prototype.isInSet = function isInSet (set) { + for (var i = 0; i < set.length; i++) + { if (this.eq(set[i])) { return true } } + return false + }; + + // :: (Mark) → bool + // Test whether this mark has the same type and attributes as + // another mark. + Mark.prototype.eq = function eq (other) { + return this == other || + (this.type == other.type && compareDeep(this.attrs, other.attrs)) + }; + + // :: () → Object + // Convert this mark to a JSON-serializeable representation. + Mark.prototype.toJSON = function toJSON () { + var obj = {type: this.type.name}; + for (var _ in this.attrs) { + obj.attrs = this.attrs; + break + } + return obj + }; + + // :: (Schema, Object) → Mark + Mark.fromJSON = function fromJSON (schema, json) { + if (!json) { throw new RangeError("Invalid input for Mark.fromJSON") } + var type = schema.marks[json.type]; + if (!type) { throw new RangeError(("There is no mark type " + (json.type) + " in this schema")) } + return type.create(json.attrs) + }; + + // :: ([Mark], [Mark]) → bool + // Test whether two sets of marks are identical. + Mark.sameSet = function sameSet (a, b) { + if (a == b) { return true } + if (a.length != b.length) { return false } + for (var i = 0; i < a.length; i++) + { if (!a[i].eq(b[i])) { return false } } + return true + }; + + // :: (?union) → [Mark] + // Create a properly sorted mark set from null, a single mark, or an + // unsorted array of marks. + Mark.setFrom = function setFrom (marks) { + if (!marks || marks.length == 0) { return Mark.none } + if (marks instanceof Mark) { return [marks] } + var copy = marks.slice(); + copy.sort(function (a, b) { return a.type.rank - b.type.rank; }); + return copy + }; + + // :: [Mark] The empty set of marks. + Mark.none = []; + + // ReplaceError:: class extends Error + // Error type raised by [`Node.replace`](#model.Node.replace) when + // given an invalid replacement. + + function ReplaceError(message) { + var err = Error.call(this, message); + err.__proto__ = ReplaceError.prototype; + return err + } + + ReplaceError.prototype = Object.create(Error.prototype); + ReplaceError.prototype.constructor = ReplaceError; + ReplaceError.prototype.name = "ReplaceError"; + + // ::- A slice represents a piece cut out of a larger document. It + // stores not only a fragment, but also the depth up to which nodes on + // both side are ‘open’ (cut through). + var Slice = function Slice(content, openStart, openEnd) { + // :: Fragment The slice's content. + this.content = content; + // :: number The open depth at the start. + this.openStart = openStart; + // :: number The open depth at the end. + this.openEnd = openEnd; + }; + + var prototypeAccessors$1 = { size: { configurable: true } }; + + // :: number + // The size this slice would add when inserted into a document. + prototypeAccessors$1.size.get = function () { + return this.content.size - this.openStart - this.openEnd + }; + + Slice.prototype.insertAt = function insertAt (pos, fragment) { + var content = insertInto(this.content, pos + this.openStart, fragment, null); + return content && new Slice(content, this.openStart, this.openEnd) + }; + + Slice.prototype.removeBetween = function removeBetween (from, to) { + return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd) + }; + + // :: (Slice) → bool + // Tests whether this slice is equal to another slice. + Slice.prototype.eq = function eq (other) { + return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd + }; + + Slice.prototype.toString = function toString () { + return this.content + "(" + this.openStart + "," + this.openEnd + ")" + }; + + // :: () → ?Object + // Convert a slice to a JSON-serializable representation. + Slice.prototype.toJSON = function toJSON () { + if (!this.content.size) { return null } + var json = {content: this.content.toJSON()}; + if (this.openStart > 0) { json.openStart = this.openStart; } + if (this.openEnd > 0) { json.openEnd = this.openEnd; } + return json + }; + + // :: (Schema, ?Object) → Slice + // Deserialize a slice from its JSON representation. + Slice.fromJSON = function fromJSON (schema, json) { + if (!json) { return Slice.empty } + var openStart = json.openStart || 0, openEnd = json.openEnd || 0; + if (typeof openStart != "number" || typeof openEnd != "number") + { throw new RangeError("Invalid input for Slice.fromJSON") } + return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd) + }; + + // :: (Fragment, ?bool) → Slice + // Create a slice from a fragment by taking the maximum possible + // open value on both side of the fragment. + Slice.maxOpen = function maxOpen (fragment, openIsolating) { + if ( openIsolating === void 0 ) openIsolating=true; + + var openStart = 0, openEnd = 0; + for (var n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild) { openStart++; } + for (var n$1 = fragment.lastChild; n$1 && !n$1.isLeaf && (openIsolating || !n$1.type.spec.isolating); n$1 = n$1.lastChild) { openEnd++; } + return new Slice(fragment, openStart, openEnd) + }; + + Object.defineProperties( Slice.prototype, prototypeAccessors$1 ); + + function removeRange(content, from, to) { + var ref = content.findIndex(from); + var index = ref.index; + var offset = ref.offset; + var child = content.maybeChild(index); + var ref$1 = content.findIndex(to); + var indexTo = ref$1.index; + var offsetTo = ref$1.offset; + if (offset == from || child.isText) { + if (offsetTo != to && !content.child(indexTo).isText) { throw new RangeError("Removing non-flat range") } + return content.cut(0, from).append(content.cut(to)) + } + if (index != indexTo) { throw new RangeError("Removing non-flat range") } + return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1))) + } + + function insertInto(content, dist, insert, parent) { + var ref = content.findIndex(dist); + var index = ref.index; + var offset = ref.offset; + var child = content.maybeChild(index); + if (offset == dist || child.isText) { + if (parent && !parent.canReplace(index, index, insert)) { return null } + return content.cut(0, dist).append(insert).append(content.cut(dist)) + } + var inner = insertInto(child.content, dist - offset - 1, insert); + return inner && content.replaceChild(index, child.copy(inner)) + } + + // :: Slice + // The empty slice. + Slice.empty = new Slice(Fragment.empty, 0, 0); + + function replace($from, $to, slice) { + if (slice.openStart > $from.depth) + { throw new ReplaceError("Inserted content deeper than insertion position") } + if ($from.depth - slice.openStart != $to.depth - slice.openEnd) + { throw new ReplaceError("Inconsistent open depths") } + return replaceOuter($from, $to, slice, 0) + } + + function replaceOuter($from, $to, slice, depth) { + var index = $from.index(depth), node = $from.node(depth); + if (index == $to.index(depth) && depth < $from.depth - slice.openStart) { + var inner = replaceOuter($from, $to, slice, depth + 1); + return node.copy(node.content.replaceChild(index, inner)) + } else if (!slice.content.size) { + return close(node, replaceTwoWay($from, $to, depth)) + } else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case + var parent = $from.parent, content = parent.content; + return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset))) + } else { + var ref = prepareSliceForReplace(slice, $from); + var start = ref.start; + var end = ref.end; + return close(node, replaceThreeWay($from, start, end, $to, depth)) + } + } + + function checkJoin(main, sub) { + if (!sub.type.compatibleContent(main.type)) + { throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name) } + } + + function joinable($before, $after, depth) { + var node = $before.node(depth); + checkJoin(node, $after.node(depth)); + return node + } + + function addNode(child, target) { + var last = target.length - 1; + if (last >= 0 && child.isText && child.sameMarkup(target[last])) + { target[last] = child.withText(target[last].text + child.text); } + else + { target.push(child); } + } + + function addRange($start, $end, depth, target) { + var node = ($end || $start).node(depth); + var startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount; + if ($start) { + startIndex = $start.index(depth); + if ($start.depth > depth) { + startIndex++; + } else if ($start.textOffset) { + addNode($start.nodeAfter, target); + startIndex++; + } + } + for (var i = startIndex; i < endIndex; i++) { addNode(node.child(i), target); } + if ($end && $end.depth == depth && $end.textOffset) + { addNode($end.nodeBefore, target); } + } + + function close(node, content) { + if (!node.type.validContent(content)) + { throw new ReplaceError("Invalid content for node " + node.type.name) } + return node.copy(content) + } + + function replaceThreeWay($from, $start, $end, $to, depth) { + var openStart = $from.depth > depth && joinable($from, $start, depth + 1); + var openEnd = $to.depth > depth && joinable($end, $to, depth + 1); + + var content = []; + addRange(null, $from, depth, content); + if (openStart && openEnd && $start.index(depth) == $end.index(depth)) { + checkJoin(openStart, openEnd); + addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content); + } else { + if (openStart) + { addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content); } + addRange($start, $end, depth, content); + if (openEnd) + { addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content); } + } + addRange($to, null, depth, content); + return new Fragment(content) + } + + function replaceTwoWay($from, $to, depth) { + var content = []; + addRange(null, $from, depth, content); + if ($from.depth > depth) { + var type = joinable($from, $to, depth + 1); + addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content); + } + addRange($to, null, depth, content); + return new Fragment(content) + } + + function prepareSliceForReplace(slice, $along) { + var extra = $along.depth - slice.openStart, parent = $along.node(extra); + var node = parent.copy(slice.content); + for (var i = extra - 1; i >= 0; i--) + { node = $along.node(i).copy(Fragment.from(node)); } + return {start: node.resolveNoCache(slice.openStart + extra), + end: node.resolveNoCache(node.content.size - slice.openEnd - extra)} + } + + // ::- You can [_resolve_](#model.Node.resolve) a position to get more + // information about it. Objects of this class represent such a + // resolved position, providing various pieces of context information, + // and some helper methods. + // + // Throughout this interface, methods that take an optional `depth` + // parameter will interpret undefined as `this.depth` and negative + // numbers as `this.depth + value`. + var ResolvedPos = function ResolvedPos(pos, path, parentOffset) { + // :: number The position that was resolved. + this.pos = pos; + this.path = path; + // :: number + // The number of levels the parent node is from the root. If this + // position points directly into the root node, it is 0. If it + // points into a top-level paragraph, 1, and so on. + this.depth = path.length / 3 - 1; + // :: number The offset this position has into its parent node. + this.parentOffset = parentOffset; + }; + + var prototypeAccessors$2 = { parent: { configurable: true },doc: { configurable: true },textOffset: { configurable: true },nodeAfter: { configurable: true },nodeBefore: { configurable: true } }; + + ResolvedPos.prototype.resolveDepth = function resolveDepth (val) { + if (val == null) { return this.depth } + if (val < 0) { return this.depth + val } + return val + }; + + // :: Node + // The parent node that the position points into. Note that even if + // a position points into a text node, that node is not considered + // the parent—text nodes are ‘flat’ in this model, and have no content. + prototypeAccessors$2.parent.get = function () { return this.node(this.depth) }; + + // :: Node + // The root node in which the position was resolved. + prototypeAccessors$2.doc.get = function () { return this.node(0) }; + + // :: (?number) → Node + // The ancestor node at the given level. `p.node(p.depth)` is the + // same as `p.parent`. + ResolvedPos.prototype.node = function node (depth) { return this.path[this.resolveDepth(depth) * 3] }; + + // :: (?number) → number + // The index into the ancestor at the given level. If this points at + // the 3rd node in the 2nd paragraph on the top level, for example, + // `p.index(0)` is 1 and `p.index(1)` is 2. + ResolvedPos.prototype.index = function index (depth) { return this.path[this.resolveDepth(depth) * 3 + 1] }; + + // :: (?number) → number + // The index pointing after this position into the ancestor at the + // given level. + ResolvedPos.prototype.indexAfter = function indexAfter (depth) { + depth = this.resolveDepth(depth); + return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1) + }; + + // :: (?number) → number + // The (absolute) position at the start of the node at the given + // level. + ResolvedPos.prototype.start = function start (depth) { + depth = this.resolveDepth(depth); + return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1 + }; + + // :: (?number) → number + // The (absolute) position at the end of the node at the given + // level. + ResolvedPos.prototype.end = function end (depth) { + depth = this.resolveDepth(depth); + return this.start(depth) + this.node(depth).content.size + }; + + // :: (?number) → number + // The (absolute) position directly before the wrapping node at the + // given level, or, when `depth` is `this.depth + 1`, the original + // position. + ResolvedPos.prototype.before = function before (depth) { + depth = this.resolveDepth(depth); + if (!depth) { throw new RangeError("There is no position before the top-level node") } + return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + }; + + // :: (?number) → number + // The (absolute) position directly after the wrapping node at the + // given level, or the original position when `depth` is `this.depth + 1`. + ResolvedPos.prototype.after = function after (depth) { + depth = this.resolveDepth(depth); + if (!depth) { throw new RangeError("There is no position after the top-level node") } + return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize + }; + + // :: number + // When this position points into a text node, this returns the + // distance between the position and the start of the text node. + // Will be zero for positions that point between nodes. + prototypeAccessors$2.textOffset.get = function () { return this.pos - this.path[this.path.length - 1] }; + + // :: ?Node + // Get the node directly after the position, if any. If the position + // points into a text node, only the part of that node after the + // position is returned. + prototypeAccessors$2.nodeAfter.get = function () { + var parent = this.parent, index = this.index(this.depth); + if (index == parent.childCount) { return null } + var dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index); + return dOff ? parent.child(index).cut(dOff) : child + }; + + // :: ?Node + // Get the node directly before the position, if any. If the + // position points into a text node, only the part of that node + // before the position is returned. + prototypeAccessors$2.nodeBefore.get = function () { + var index = this.index(this.depth); + var dOff = this.pos - this.path[this.path.length - 1]; + if (dOff) { return this.parent.child(index).cut(0, dOff) } + return index == 0 ? null : this.parent.child(index - 1) + }; + + // :: (number, ?number) → number + // Get the position at the given index in the parent node at the + // given depth (which defaults to `this.depth`). + ResolvedPos.prototype.posAtIndex = function posAtIndex (index, depth) { + depth = this.resolveDepth(depth); + var node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1; + for (var i = 0; i < index; i++) { pos += node.child(i).nodeSize; } + return pos + }; + + // :: () → [Mark] + // Get the marks at this position, factoring in the surrounding + // marks' [`inclusive`](#model.MarkSpec.inclusive) property. If the + // position is at the start of a non-empty node, the marks of the + // node after it (if any) are returned. + ResolvedPos.prototype.marks = function marks () { + var parent = this.parent, index = this.index(); + + // In an empty parent, return the empty array + if (parent.content.size == 0) { return Mark.none } + + // When inside a text node, just return the text node's marks + if (this.textOffset) { return parent.child(index).marks } + + var main = parent.maybeChild(index - 1), other = parent.maybeChild(index); + // If the `after` flag is true of there is no node before, make + // the node after this position the main reference. + if (!main) { var tmp = main; main = other; other = tmp; } + + // Use all marks in the main node, except those that have + // `inclusive` set to false and are not present in the other node. + var marks = main.marks; + for (var i = 0; i < marks.length; i++) + { if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks))) + { marks = marks[i--].removeFromSet(marks); } } + + return marks + }; + + // :: (ResolvedPos) → ?[Mark] + // Get the marks after the current position, if any, except those + // that are non-inclusive and not present at position `$end`. This + // is mostly useful for getting the set of marks to preserve after a + // deletion. Will return `null` if this position is at the end of + // its parent node or its parent node isn't a textblock (in which + // case no marks should be preserved). + ResolvedPos.prototype.marksAcross = function marksAcross ($end) { + var after = this.parent.maybeChild(this.index()); + if (!after || !after.isInline) { return null } + + var marks = after.marks, next = $end.parent.maybeChild($end.index()); + for (var i = 0; i < marks.length; i++) + { if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks))) + { marks = marks[i--].removeFromSet(marks); } } + return marks + }; + + // :: (number) → number + // The depth up to which this position and the given (non-resolved) + // position share the same parent nodes. + ResolvedPos.prototype.sharedDepth = function sharedDepth (pos) { + for (var depth = this.depth; depth > 0; depth--) + { if (this.start(depth) <= pos && this.end(depth) >= pos) { return depth } } + return 0 + }; + + // :: (?ResolvedPos, ?(Node) → bool) → ?NodeRange + // Returns a range based on the place where this position and the + // given position diverge around block content. If both point into + // the same textblock, for example, a range around that textblock + // will be returned. If they point into different blocks, the range + // around those blocks in their shared ancestor is returned. You can + // pass in an optional predicate that will be called with a parent + // node to see if a range into that parent is acceptable. + ResolvedPos.prototype.blockRange = function blockRange (other, pred) { + if ( other === void 0 ) other = this; + + if (other.pos < this.pos) { return other.blockRange(this) } + for (var d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--) + { if (other.pos <= this.end(d) && (!pred || pred(this.node(d)))) + { return new NodeRange(this, other, d) } } + }; + + // :: (ResolvedPos) → bool + // Query whether the given position shares the same parent node. + ResolvedPos.prototype.sameParent = function sameParent (other) { + return this.pos - this.parentOffset == other.pos - other.parentOffset + }; + + // :: (ResolvedPos) → ResolvedPos + // Return the greater of this and the given position. + ResolvedPos.prototype.max = function max (other) { + return other.pos > this.pos ? other : this + }; + + // :: (ResolvedPos) → ResolvedPos + // Return the smaller of this and the given position. + ResolvedPos.prototype.min = function min (other) { + return other.pos < this.pos ? other : this + }; + + ResolvedPos.prototype.toString = function toString () { + var str = ""; + for (var i = 1; i <= this.depth; i++) + { str += (str ? "/" : "") + this.node(i).type.name + "_" + this.index(i - 1); } + return str + ":" + this.parentOffset + }; + + ResolvedPos.resolve = function resolve (doc, pos) { + if (!(pos >= 0 && pos <= doc.content.size)) { throw new RangeError("Position " + pos + " out of range") } + var path = []; + var start = 0, parentOffset = pos; + for (var node = doc;;) { + var ref = node.content.findIndex(parentOffset); + var index = ref.index; + var offset = ref.offset; + var rem = parentOffset - offset; + path.push(node, index, start + offset); + if (!rem) { break } + node = node.child(index); + if (node.isText) { break } + parentOffset = rem - 1; + start += offset + 1; + } + return new ResolvedPos(pos, path, parentOffset) + }; + + ResolvedPos.resolveCached = function resolveCached (doc, pos) { + for (var i = 0; i < resolveCache.length; i++) { + var cached = resolveCache[i]; + if (cached.pos == pos && cached.doc == doc) { return cached } + } + var result = resolveCache[resolveCachePos] = ResolvedPos.resolve(doc, pos); + resolveCachePos = (resolveCachePos + 1) % resolveCacheSize; + return result + }; + + Object.defineProperties( ResolvedPos.prototype, prototypeAccessors$2 ); + + var resolveCache = [], resolveCachePos = 0, resolveCacheSize = 12; + + // ::- Represents a flat range of content, i.e. one that starts and + // ends in the same node. + var NodeRange = function NodeRange($from, $to, depth) { + // :: ResolvedPos A resolved position along the start of the + // content. May have a `depth` greater than this object's `depth` + // property, since these are the positions that were used to + // compute the range, not re-resolved positions directly at its + // boundaries. + this.$from = $from; + // :: ResolvedPos A position along the end of the content. See + // caveat for [`$from`](#model.NodeRange.$from). + this.$to = $to; + // :: number The depth of the node that this range points into. + this.depth = depth; + }; + + var prototypeAccessors$1$1 = { start: { configurable: true },end: { configurable: true },parent: { configurable: true },startIndex: { configurable: true },endIndex: { configurable: true } }; + + // :: number The position at the start of the range. + prototypeAccessors$1$1.start.get = function () { return this.$from.before(this.depth + 1) }; + // :: number The position at the end of the range. + prototypeAccessors$1$1.end.get = function () { return this.$to.after(this.depth + 1) }; + + // :: Node The parent node that the range points into. + prototypeAccessors$1$1.parent.get = function () { return this.$from.node(this.depth) }; + // :: number The start index of the range in the parent node. + prototypeAccessors$1$1.startIndex.get = function () { return this.$from.index(this.depth) }; + // :: number The end index of the range in the parent node. + prototypeAccessors$1$1.endIndex.get = function () { return this.$to.indexAfter(this.depth) }; + + Object.defineProperties( NodeRange.prototype, prototypeAccessors$1$1 ); + + var emptyAttrs = Object.create(null); + + // ::- This class represents a node in the tree that makes up a + // ProseMirror document. So a document is an instance of `Node`, with + // children that are also instances of `Node`. + // + // Nodes are persistent data structures. Instead of changing them, you + // create new ones with the content you want. Old ones keep pointing + // at the old document shape. This is made cheaper by sharing + // structure between the old and new data as much as possible, which a + // tree shape like this (without back pointers) makes easy. + // + // **Do not** directly mutate the properties of a `Node` object. See + // [the guide](/docs/guide/#doc) for more information. + var Node = function Node(type, attrs, content, marks) { + // :: NodeType + // The type of node that this is. + this.type = type; + + // :: Object + // An object mapping attribute names to values. The kind of + // attributes allowed and required are + // [determined](#model.NodeSpec.attrs) by the node type. + this.attrs = attrs; + + // :: Fragment + // A container holding the node's children. + this.content = content || Fragment.empty; + + // :: [Mark] + // The marks (things like whether it is emphasized or part of a + // link) applied to this node. + this.marks = marks || Mark.none; + }; + + var prototypeAccessors$3 = { nodeSize: { configurable: true },childCount: { configurable: true },textContent: { configurable: true },firstChild: { configurable: true },lastChild: { configurable: true },isBlock: { configurable: true },isTextblock: { configurable: true },inlineContent: { configurable: true },isInline: { configurable: true },isText: { configurable: true },isLeaf: { configurable: true },isAtom: { configurable: true } }; + + // text:: ?string + // For text nodes, this contains the node's text content. + + // :: number + // The size of this node, as defined by the integer-based [indexing + // scheme](/docs/guide/#doc.indexing). For text nodes, this is the + // amount of characters. For other leaf nodes, it is one. For + // non-leaf nodes, it is the size of the content plus two (the start + // and end token). + prototypeAccessors$3.nodeSize.get = function () { return this.isLeaf ? 1 : 2 + this.content.size }; + + // :: number + // The number of children that the node has. + prototypeAccessors$3.childCount.get = function () { return this.content.childCount }; + + // :: (number) → Node + // Get the child node at the given index. Raises an error when the + // index is out of range. + Node.prototype.child = function child (index) { return this.content.child(index) }; + + // :: (number) → ?Node + // Get the child node at the given index, if it exists. + Node.prototype.maybeChild = function maybeChild (index) { return this.content.maybeChild(index) }; + + // :: ((node: Node, offset: number, index: number)) + // Call `f` for every child node, passing the node, its offset + // into this parent node, and its index. + Node.prototype.forEach = function forEach (f) { this.content.forEach(f); }; + + // :: (number, number, (node: Node, pos: number, parent: Node, index: number) → ?bool, ?number) + // Invoke a callback for all descendant nodes recursively between + // the given two positions that are relative to start of this node's + // content. The callback is invoked with the node, its + // parent-relative position, its parent node, and its child index. + // When the callback returns false for a given node, that node's + // children will not be recursed over. The last parameter can be + // used to specify a starting position to count from. + Node.prototype.nodesBetween = function nodesBetween (from, to, f, startPos) { + if ( startPos === void 0 ) startPos = 0; + + this.content.nodesBetween(from, to, f, startPos, this); + }; + + // :: ((node: Node, pos: number, parent: Node) → ?bool) + // Call the given callback for every descendant node. Doesn't + // descend into a node when the callback returns `false`. + Node.prototype.descendants = function descendants (f) { + this.nodesBetween(0, this.content.size, f); + }; + + // :: string + // Concatenates all the text nodes found in this fragment and its + // children. + prototypeAccessors$3.textContent.get = function () { return this.textBetween(0, this.content.size, "") }; + + // :: (number, number, ?string, ?string) → string + // Get all text between positions `from` and `to`. When + // `blockSeparator` is given, it will be inserted whenever a new + // block node is started. When `leafText` is given, it'll be + // inserted for every non-text leaf node encountered. + Node.prototype.textBetween = function textBetween (from, to, blockSeparator, leafText) { + return this.content.textBetween(from, to, blockSeparator, leafText) + }; + + // :: ?Node + // Returns this node's first child, or `null` if there are no + // children. + prototypeAccessors$3.firstChild.get = function () { return this.content.firstChild }; + + // :: ?Node + // Returns this node's last child, or `null` if there are no + // children. + prototypeAccessors$3.lastChild.get = function () { return this.content.lastChild }; + + // :: (Node) → bool + // Test whether two nodes represent the same piece of document. + Node.prototype.eq = function eq (other) { + return this == other || (this.sameMarkup(other) && this.content.eq(other.content)) + }; + + // :: (Node) → bool + // Compare the markup (type, attributes, and marks) of this node to + // those of another. Returns `true` if both have the same markup. + Node.prototype.sameMarkup = function sameMarkup (other) { + return this.hasMarkup(other.type, other.attrs, other.marks) + }; + + // :: (NodeType, ?Object, ?[Mark]) → bool + // Check whether this node's markup correspond to the given type, + // attributes, and marks. + Node.prototype.hasMarkup = function hasMarkup (type, attrs, marks) { + return this.type == type && + compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) && + Mark.sameSet(this.marks, marks || Mark.none) + }; + + // :: (?Fragment) → Node + // Create a new node with the same markup as this node, containing + // the given content (or empty, if no content is given). + Node.prototype.copy = function copy (content) { + if ( content === void 0 ) content = null; + + if (content == this.content) { return this } + return new this.constructor(this.type, this.attrs, content, this.marks) + }; + + // :: ([Mark]) → Node + // Create a copy of this node, with the given set of marks instead + // of the node's own marks. + Node.prototype.mark = function mark (marks) { + return marks == this.marks ? this : new this.constructor(this.type, this.attrs, this.content, marks) + }; + + // :: (number, ?number) → Node + // Create a copy of this node with only the content between the + // given positions. If `to` is not given, it defaults to the end of + // the node. + Node.prototype.cut = function cut (from, to) { + if (from == 0 && to == this.content.size) { return this } + return this.copy(this.content.cut(from, to)) + }; + + // :: (number, ?number) → Slice + // Cut out the part of the document between the given positions, and + // return it as a `Slice` object. + Node.prototype.slice = function slice (from, to, includeParents) { + if ( to === void 0 ) to = this.content.size; + if ( includeParents === void 0 ) includeParents = false; + + if (from == to) { return Slice.empty } + + var $from = this.resolve(from), $to = this.resolve(to); + var depth = includeParents ? 0 : $from.sharedDepth(to); + var start = $from.start(depth), node = $from.node(depth); + var content = node.content.cut($from.pos - start, $to.pos - start); + return new Slice(content, $from.depth - depth, $to.depth - depth) + }; + + // :: (number, number, Slice) → Node + // Replace the part of the document between the given positions with + // the given slice. The slice must 'fit', meaning its open sides + // must be able to connect to the surrounding content, and its + // content nodes must be valid children for the node they are placed + // into. If any of this is violated, an error of type + // [`ReplaceError`](#model.ReplaceError) is thrown. + Node.prototype.replace = function replace$1 (from, to, slice) { + return replace(this.resolve(from), this.resolve(to), slice) + }; + + // :: (number) → ?Node + // Find the node directly after the given position. + Node.prototype.nodeAt = function nodeAt (pos) { + for (var node = this;;) { + var ref = node.content.findIndex(pos); + var index = ref.index; + var offset = ref.offset; + node = node.maybeChild(index); + if (!node) { return null } + if (offset == pos || node.isText) { return node } + pos -= offset + 1; + } + }; + + // :: (number) → {node: ?Node, index: number, offset: number} + // Find the (direct) child node after the given offset, if any, + // and return it along with its index and offset relative to this + // node. + Node.prototype.childAfter = function childAfter (pos) { + var ref = this.content.findIndex(pos); + var index = ref.index; + var offset = ref.offset; + return {node: this.content.maybeChild(index), index: index, offset: offset} + }; + + // :: (number) → {node: ?Node, index: number, offset: number} + // Find the (direct) child node before the given offset, if any, + // and return it along with its index and offset relative to this + // node. + Node.prototype.childBefore = function childBefore (pos) { + if (pos == 0) { return {node: null, index: 0, offset: 0} } + var ref = this.content.findIndex(pos); + var index = ref.index; + var offset = ref.offset; + if (offset < pos) { return {node: this.content.child(index), index: index, offset: offset} } + var node = this.content.child(index - 1); + return {node: node, index: index - 1, offset: offset - node.nodeSize} + }; + + // :: (number) → ResolvedPos + // Resolve the given position in the document, returning an + // [object](#model.ResolvedPos) with information about its context. + Node.prototype.resolve = function resolve (pos) { return ResolvedPos.resolveCached(this, pos) }; + + Node.prototype.resolveNoCache = function resolveNoCache (pos) { return ResolvedPos.resolve(this, pos) }; + + // :: (number, number, union) → bool + // Test whether a given mark or mark type occurs in this document + // between the two given positions. + Node.prototype.rangeHasMark = function rangeHasMark (from, to, type) { + var found = false; + if (to > from) { this.nodesBetween(from, to, function (node) { + if (type.isInSet(node.marks)) { found = true; } + return !found + }); } + return found + }; + + // :: bool + // True when this is a block (non-inline node) + prototypeAccessors$3.isBlock.get = function () { return this.type.isBlock }; + + // :: bool + // True when this is a textblock node, a block node with inline + // content. + prototypeAccessors$3.isTextblock.get = function () { return this.type.isTextblock }; + + // :: bool + // True when this node allows inline content. + prototypeAccessors$3.inlineContent.get = function () { return this.type.inlineContent }; + + // :: bool + // True when this is an inline node (a text node or a node that can + // appear among text). + prototypeAccessors$3.isInline.get = function () { return this.type.isInline }; + + // :: bool + // True when this is a text node. + prototypeAccessors$3.isText.get = function () { return this.type.isText }; + + // :: bool + // True when this is a leaf node. + prototypeAccessors$3.isLeaf.get = function () { return this.type.isLeaf }; + + // :: bool + // True when this is an atom, i.e. when it does not have directly + // editable content. This is usually the same as `isLeaf`, but can + // be configured with the [`atom` property](#model.NodeSpec.atom) on + // a node's spec (typically used when the node is displayed as an + // uneditable [node view](#view.NodeView)). + prototypeAccessors$3.isAtom.get = function () { return this.type.isAtom }; + + // :: () → string + // Return a string representation of this node for debugging + // purposes. + Node.prototype.toString = function toString () { + if (this.type.spec.toDebugString) { return this.type.spec.toDebugString(this) } + var name = this.type.name; + if (this.content.size) + { name += "(" + this.content.toStringInner() + ")"; } + return wrapMarks(this.marks, name) + }; + + // :: (number) → ContentMatch + // Get the content match in this node at the given index. + Node.prototype.contentMatchAt = function contentMatchAt (index) { + var match = this.type.contentMatch.matchFragment(this.content, 0, index); + if (!match) { throw new Error("Called contentMatchAt on a node with invalid content") } + return match + }; + + // :: (number, number, ?Fragment, ?number, ?number) → bool + // Test whether replacing the range between `from` and `to` (by + // child index) with the given replacement fragment (which defaults + // to the empty fragment) would leave the node's content valid. You + // can optionally pass `start` and `end` indices into the + // replacement fragment. + Node.prototype.canReplace = function canReplace (from, to, replacement, start, end) { + if ( replacement === void 0 ) replacement = Fragment.empty; + if ( start === void 0 ) start = 0; + if ( end === void 0 ) end = replacement.childCount; + + var one = this.contentMatchAt(from).matchFragment(replacement, start, end); + var two = one && one.matchFragment(this.content, to); + if (!two || !two.validEnd) { return false } + for (var i = start; i < end; i++) { if (!this.type.allowsMarks(replacement.child(i).marks)) { return false } } + return true + }; + + // :: (number, number, NodeType, ?[Mark]) → bool + // Test whether replacing the range `from` to `to` (by index) with a + // node of the given type would leave the node's content valid. + Node.prototype.canReplaceWith = function canReplaceWith (from, to, type, marks) { + if (marks && !this.type.allowsMarks(marks)) { return false } + var start = this.contentMatchAt(from).matchType(type); + var end = start && start.matchFragment(this.content, to); + return end ? end.validEnd : false + }; + + // :: (Node) → bool + // Test whether the given node's content could be appended to this + // node. If that node is empty, this will only return true if there + // is at least one node type that can appear in both nodes (to avoid + // merging completely incompatible nodes). + Node.prototype.canAppend = function canAppend (other) { + if (other.content.size) { return this.canReplace(this.childCount, this.childCount, other.content) } + else { return this.type.compatibleContent(other.type) } + }; + + // :: () + // Check whether this node and its descendants conform to the + // schema, and raise error when they do not. + Node.prototype.check = function check () { + if (!this.type.validContent(this.content)) + { throw new RangeError(("Invalid content for node " + (this.type.name) + ": " + (this.content.toString().slice(0, 50)))) } + this.content.forEach(function (node) { return node.check(); }); + }; + + // :: () → Object + // Return a JSON-serializeable representation of this node. + Node.prototype.toJSON = function toJSON () { + var obj = {type: this.type.name}; + for (var _ in this.attrs) { + obj.attrs = this.attrs; + break + } + if (this.content.size) + { obj.content = this.content.toJSON(); } + if (this.marks.length) + { obj.marks = this.marks.map(function (n) { return n.toJSON(); }); } + return obj + }; + + // :: (Schema, Object) → Node + // Deserialize a node from its JSON representation. + Node.fromJSON = function fromJSON (schema, json) { + if (!json) { throw new RangeError("Invalid input for Node.fromJSON") } + var marks = null; + if (json.marks) { + if (!Array.isArray(json.marks)) { throw new RangeError("Invalid mark data for Node.fromJSON") } + marks = json.marks.map(schema.markFromJSON); + } + if (json.type == "text") { + if (typeof json.text != "string") { throw new RangeError("Invalid text node in JSON") } + return schema.text(json.text, marks) + } + var content = Fragment.fromJSON(schema, json.content); + return schema.nodeType(json.type).create(json.attrs, content, marks) + }; + + Object.defineProperties( Node.prototype, prototypeAccessors$3 ); + + var TextNode = /*@__PURE__*/(function (Node) { + function TextNode(type, attrs, content, marks) { + Node.call(this, type, attrs, null, marks); + + if (!content) { throw new RangeError("Empty text nodes are not allowed") } + + this.text = content; + } + + if ( Node ) TextNode.__proto__ = Node; + TextNode.prototype = Object.create( Node && Node.prototype ); + TextNode.prototype.constructor = TextNode; + + var prototypeAccessors$1 = { textContent: { configurable: true },nodeSize: { configurable: true } }; + + TextNode.prototype.toString = function toString () { + if (this.type.spec.toDebugString) { return this.type.spec.toDebugString(this) } + return wrapMarks(this.marks, JSON.stringify(this.text)) + }; + + prototypeAccessors$1.textContent.get = function () { return this.text }; + + TextNode.prototype.textBetween = function textBetween (from, to) { return this.text.slice(from, to) }; + + prototypeAccessors$1.nodeSize.get = function () { return this.text.length }; + + TextNode.prototype.mark = function mark (marks) { + return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks) + }; + + TextNode.prototype.withText = function withText (text) { + if (text == this.text) { return this } + return new TextNode(this.type, this.attrs, text, this.marks) + }; + + TextNode.prototype.cut = function cut (from, to) { + if ( from === void 0 ) from = 0; + if ( to === void 0 ) to = this.text.length; + + if (from == 0 && to == this.text.length) { return this } + return this.withText(this.text.slice(from, to)) + }; + + TextNode.prototype.eq = function eq (other) { + return this.sameMarkup(other) && this.text == other.text + }; + + TextNode.prototype.toJSON = function toJSON () { + var base = Node.prototype.toJSON.call(this); + base.text = this.text; + return base + }; + + Object.defineProperties( TextNode.prototype, prototypeAccessors$1 ); + + return TextNode; + }(Node)); + + function wrapMarks(marks, str) { + for (var i = marks.length - 1; i >= 0; i--) + { str = marks[i].type.name + "(" + str + ")"; } + return str + } + + // ::- Instances of this class represent a match state of a node + // type's [content expression](#model.NodeSpec.content), and can be + // used to find out whether further content matches here, and whether + // a given position is a valid end of the node. + var ContentMatch = function ContentMatch(validEnd) { + // :: bool + // True when this match state represents a valid end of the node. + this.validEnd = validEnd; + this.next = []; + this.wrapCache = []; + }; + + var prototypeAccessors$4 = { inlineContent: { configurable: true },defaultType: { configurable: true },edgeCount: { configurable: true } }; + + ContentMatch.parse = function parse (string, nodeTypes) { + var stream = new TokenStream(string, nodeTypes); + if (stream.next == null) { return ContentMatch.empty } + var expr = parseExpr(stream); + if (stream.next) { stream.err("Unexpected trailing text"); } + var match = dfa(nfa(expr)); + checkForDeadEnds(match, stream); + return match + }; + + // :: (NodeType) → ?ContentMatch + // Match a node type, returning a match after that node if + // successful. + ContentMatch.prototype.matchType = function matchType (type) { + for (var i = 0; i < this.next.length; i += 2) + { if (this.next[i] == type) { return this.next[i + 1] } } + return null + }; + + // :: (Fragment, ?number, ?number) → ?ContentMatch + // Try to match a fragment. Returns the resulting match when + // successful. + ContentMatch.prototype.matchFragment = function matchFragment (frag, start, end) { + if ( start === void 0 ) start = 0; + if ( end === void 0 ) end = frag.childCount; + + var cur = this; + for (var i = start; cur && i < end; i++) + { cur = cur.matchType(frag.child(i).type); } + return cur + }; + + prototypeAccessors$4.inlineContent.get = function () { + var first = this.next[0]; + return first ? first.isInline : false + }; + + // :: ?NodeType + // Get the first matching node type at this match position that can + // be generated. + prototypeAccessors$4.defaultType.get = function () { + for (var i = 0; i < this.next.length; i += 2) { + var type = this.next[i]; + if (!(type.isText || type.hasRequiredAttrs())) { return type } + } + }; + + ContentMatch.prototype.compatible = function compatible (other) { + for (var i = 0; i < this.next.length; i += 2) + { for (var j = 0; j < other.next.length; j += 2) + { if (this.next[i] == other.next[j]) { return true } } } + return false + }; + + // :: (Fragment, bool, ?number) → ?Fragment + // Try to match the given fragment, and if that fails, see if it can + // be made to match by inserting nodes in front of it. When + // successful, return a fragment of inserted nodes (which may be + // empty if nothing had to be inserted). When `toEnd` is true, only + // return a fragment if the resulting match goes to the end of the + // content expression. + ContentMatch.prototype.fillBefore = function fillBefore (after, toEnd, startIndex) { + if ( toEnd === void 0 ) toEnd = false; + if ( startIndex === void 0 ) startIndex = 0; + + var seen = [this]; + function search(match, types) { + var finished = match.matchFragment(after, startIndex); + if (finished && (!toEnd || finished.validEnd)) + { return Fragment.from(types.map(function (tp) { return tp.createAndFill(); })) } + + for (var i = 0; i < match.next.length; i += 2) { + var type = match.next[i], next = match.next[i + 1]; + if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) { + seen.push(next); + var found = search(next, types.concat(type)); + if (found) { return found } + } + } + } + + return search(this, []) + }; + + // :: (NodeType) → ?[NodeType] + // Find a set of wrapping node types that would allow a node of the + // given type to appear at this position. The result may be empty + // (when it fits directly) and will be null when no such wrapping + // exists. + ContentMatch.prototype.findWrapping = function findWrapping (target) { + for (var i = 0; i < this.wrapCache.length; i += 2) + { if (this.wrapCache[i] == target) { return this.wrapCache[i + 1] } } + var computed = this.computeWrapping(target); + this.wrapCache.push(target, computed); + return computed + }; + + ContentMatch.prototype.computeWrapping = function computeWrapping (target) { + var seen = Object.create(null), active = [{match: this, type: null, via: null}]; + while (active.length) { + var current = active.shift(), match = current.match; + if (match.matchType(target)) { + var result = []; + for (var obj = current; obj.type; obj = obj.via) + { result.push(obj.type); } + return result.reverse() + } + for (var i = 0; i < match.next.length; i += 2) { + var type = match.next[i]; + if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || match.next[i + 1].validEnd)) { + active.push({match: type.contentMatch, type: type, via: current}); + seen[type.name] = true; + } + } + } + }; + + // :: number + // The number of outgoing edges this node has in the finite + // automaton that describes the content expression. + prototypeAccessors$4.edgeCount.get = function () { + return this.next.length >> 1 + }; + + // :: (number) → {type: NodeType, next: ContentMatch} + // Get the _n_​th outgoing edge from this node in the finite + // automaton that describes the content expression. + ContentMatch.prototype.edge = function edge (n) { + var i = n << 1; + if (i >= this.next.length) { throw new RangeError(("There's no " + n + "th edge in this content match")) } + return {type: this.next[i], next: this.next[i + 1]} + }; + + ContentMatch.prototype.toString = function toString () { + var seen = []; + function scan(m) { + seen.push(m); + for (var i = 1; i < m.next.length; i += 2) + { if (seen.indexOf(m.next[i]) == -1) { scan(m.next[i]); } } + } + scan(this); + return seen.map(function (m, i) { + var out = i + (m.validEnd ? "*" : " ") + " "; + for (var i$1 = 0; i$1 < m.next.length; i$1 += 2) + { out += (i$1 ? ", " : "") + m.next[i$1].name + "->" + seen.indexOf(m.next[i$1 + 1]); } + return out + }).join("\n") + }; + + Object.defineProperties( ContentMatch.prototype, prototypeAccessors$4 ); + + ContentMatch.empty = new ContentMatch(true); + + var TokenStream = function TokenStream(string, nodeTypes) { + this.string = string; + this.nodeTypes = nodeTypes; + this.inline = null; + this.pos = 0; + this.tokens = string.split(/\s*(?=\b|\W|$)/); + if (this.tokens[this.tokens.length - 1] == "") { this.tokens.pop(); } + if (this.tokens[0] == "") { this.tokens.unshift(); } + }; + + var prototypeAccessors$1$2 = { next: { configurable: true } }; + + prototypeAccessors$1$2.next.get = function () { return this.tokens[this.pos] }; + + TokenStream.prototype.eat = function eat (tok) { return this.next == tok && (this.pos++ || true) }; + + TokenStream.prototype.err = function err (str) { throw new SyntaxError(str + " (in content expression '" + this.string + "')") }; + + Object.defineProperties( TokenStream.prototype, prototypeAccessors$1$2 ); + + function parseExpr(stream) { + var exprs = []; + do { exprs.push(parseExprSeq(stream)); } + while (stream.eat("|")) + return exprs.length == 1 ? exprs[0] : {type: "choice", exprs: exprs} + } + + function parseExprSeq(stream) { + var exprs = []; + do { exprs.push(parseExprSubscript(stream)); } + while (stream.next && stream.next != ")" && stream.next != "|") + return exprs.length == 1 ? exprs[0] : {type: "seq", exprs: exprs} + } + + function parseExprSubscript(stream) { + var expr = parseExprAtom(stream); + for (;;) { + if (stream.eat("+")) + { expr = {type: "plus", expr: expr}; } + else if (stream.eat("*")) + { expr = {type: "star", expr: expr}; } + else if (stream.eat("?")) + { expr = {type: "opt", expr: expr}; } + else if (stream.eat("{")) + { expr = parseExprRange(stream, expr); } + else { break } + } + return expr + } + + function parseNum(stream) { + if (/\D/.test(stream.next)) { stream.err("Expected number, got '" + stream.next + "'"); } + var result = Number(stream.next); + stream.pos++; + return result + } + + function parseExprRange(stream, expr) { + var min = parseNum(stream), max = min; + if (stream.eat(",")) { + if (stream.next != "}") { max = parseNum(stream); } + else { max = -1; } + } + if (!stream.eat("}")) { stream.err("Unclosed braced range"); } + return {type: "range", min: min, max: max, expr: expr} + } + + function resolveName(stream, name) { + var types = stream.nodeTypes, type = types[name]; + if (type) { return [type] } + var result = []; + for (var typeName in types) { + var type$1 = types[typeName]; + if (type$1.groups.indexOf(name) > -1) { result.push(type$1); } + } + if (result.length == 0) { stream.err("No node type or group '" + name + "' found"); } + return result + } + + function parseExprAtom(stream) { + if (stream.eat("(")) { + var expr = parseExpr(stream); + if (!stream.eat(")")) { stream.err("Missing closing paren"); } + return expr + } else if (!/\W/.test(stream.next)) { + var exprs = resolveName(stream, stream.next).map(function (type) { + if (stream.inline == null) { stream.inline = type.isInline; } + else if (stream.inline != type.isInline) { stream.err("Mixing inline and block content"); } + return {type: "name", value: type} + }); + stream.pos++; + return exprs.length == 1 ? exprs[0] : {type: "choice", exprs: exprs} + } else { + stream.err("Unexpected token '" + stream.next + "'"); + } + } + + // The code below helps compile a regular-expression-like language + // into a deterministic finite automaton. For a good introduction to + // these concepts, see https://swtch.com/~rsc/regexp/regexp1.html + + // : (Object) → [[{term: ?any, to: number}]] + // Construct an NFA from an expression as returned by the parser. The + // NFA is represented as an array of states, which are themselves + // arrays of edges, which are `{term, to}` objects. The first state is + // the entry state and the last node is the success state. + // + // Note that unlike typical NFAs, the edge ordering in this one is + // significant, in that it is used to contruct filler content when + // necessary. + function nfa(expr) { + var nfa = [[]]; + connect(compile(expr, 0), node()); + return nfa + + function node() { return nfa.push([]) - 1 } + function edge(from, to, term) { + var edge = {term: term, to: to}; + nfa[from].push(edge); + return edge + } + function connect(edges, to) { edges.forEach(function (edge) { return edge.to = to; }); } + + function compile(expr, from) { + if (expr.type == "choice") { + return expr.exprs.reduce(function (out, expr) { return out.concat(compile(expr, from)); }, []) + } else if (expr.type == "seq") { + for (var i = 0;; i++) { + var next = compile(expr.exprs[i], from); + if (i == expr.exprs.length - 1) { return next } + connect(next, from = node()); + } + } else if (expr.type == "star") { + var loop = node(); + edge(from, loop); + connect(compile(expr.expr, loop), loop); + return [edge(loop)] + } else if (expr.type == "plus") { + var loop$1 = node(); + connect(compile(expr.expr, from), loop$1); + connect(compile(expr.expr, loop$1), loop$1); + return [edge(loop$1)] + } else if (expr.type == "opt") { + return [edge(from)].concat(compile(expr.expr, from)) + } else if (expr.type == "range") { + var cur = from; + for (var i$1 = 0; i$1 < expr.min; i$1++) { + var next$1 = node(); + connect(compile(expr.expr, cur), next$1); + cur = next$1; + } + if (expr.max == -1) { + connect(compile(expr.expr, cur), cur); + } else { + for (var i$2 = expr.min; i$2 < expr.max; i$2++) { + var next$2 = node(); + edge(cur, next$2); + connect(compile(expr.expr, cur), next$2); + cur = next$2; + } + } + return [edge(cur)] + } else if (expr.type == "name") { + return [edge(from, null, expr.value)] + } + } + } + + function cmp(a, b) { return b - a } + + // Get the set of nodes reachable by null edges from `node`. Omit + // nodes with only a single null-out-edge, since they may lead to + // needless duplicated nodes. + function nullFrom(nfa, node) { + var result = []; + scan(node); + return result.sort(cmp) + + function scan(node) { + var edges = nfa[node]; + if (edges.length == 1 && !edges[0].term) { return scan(edges[0].to) } + result.push(node); + for (var i = 0; i < edges.length; i++) { + var ref = edges[i]; + var term = ref.term; + var to = ref.to; + if (!term && result.indexOf(to) == -1) { scan(to); } + } + } + } + + // : ([[{term: ?any, to: number}]]) → ContentMatch + // Compiles an NFA as produced by `nfa` into a DFA, modeled as a set + // of state objects (`ContentMatch` instances) with transitions + // between them. + function dfa(nfa) { + var labeled = Object.create(null); + return explore(nullFrom(nfa, 0)) + + function explore(states) { + var out = []; + states.forEach(function (node) { + nfa[node].forEach(function (ref) { + var term = ref.term; + var to = ref.to; + + if (!term) { return } + var known = out.indexOf(term), set = known > -1 && out[known + 1]; + nullFrom(nfa, to).forEach(function (node) { + if (!set) { out.push(term, set = []); } + if (set.indexOf(node) == -1) { set.push(node); } + }); + }); + }); + var state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1); + for (var i = 0; i < out.length; i += 2) { + var states$1 = out[i + 1].sort(cmp); + state.next.push(out[i], labeled[states$1.join(",")] || explore(states$1)); + } + return state + } + } + + function checkForDeadEnds(match, stream) { + for (var i = 0, work = [match]; i < work.length; i++) { + var state = work[i], dead = !state.validEnd, nodes = []; + for (var j = 0; j < state.next.length; j += 2) { + var node = state.next[j], next = state.next[j + 1]; + nodes.push(node.name); + if (dead && !(node.isText || node.hasRequiredAttrs())) { dead = false; } + if (work.indexOf(next) == -1) { work.push(next); } + } + if (dead) { stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)"); } + } + } + + // For node types where all attrs have a default value (or which don't + // have any attributes), build up a single reusable default attribute + // object, and use it for all nodes that don't specify specific + // attributes. + function defaultAttrs(attrs) { + var defaults = Object.create(null); + for (var attrName in attrs) { + var attr = attrs[attrName]; + if (!attr.hasDefault) { return null } + defaults[attrName] = attr.default; + } + return defaults + } + + function computeAttrs(attrs, value) { + var built = Object.create(null); + for (var name in attrs) { + var given = value && value[name]; + if (given === undefined) { + var attr = attrs[name]; + if (attr.hasDefault) { given = attr.default; } + else { throw new RangeError("No value supplied for attribute " + name) } + } + built[name] = given; + } + return built + } + + function initAttrs(attrs) { + var result = Object.create(null); + if (attrs) { for (var name in attrs) { result[name] = new Attribute(attrs[name]); } } + return result + } + + // ::- Node types are objects allocated once per `Schema` and used to + // [tag](#model.Node.type) `Node` instances. They contain information + // about the node type, such as its name and what kind of node it + // represents. + var NodeType = function NodeType(name, schema, spec) { + // :: string + // The name the node type has in this schema. + this.name = name; + + // :: Schema + // A link back to the `Schema` the node type belongs to. + this.schema = schema; + + // :: NodeSpec + // The spec that this type is based on + this.spec = spec; + + this.groups = spec.group ? spec.group.split(" ") : []; + this.attrs = initAttrs(spec.attrs); + + this.defaultAttrs = defaultAttrs(this.attrs); + + // :: ContentMatch + // The starting match of the node type's content expression. + this.contentMatch = null; + + // : ?[MarkType] + // The set of marks allowed in this node. `null` means all marks + // are allowed. + this.markSet = null; + + // :: bool + // True if this node type has inline content. + this.inlineContent = null; + + // :: bool + // True if this is a block type + this.isBlock = !(spec.inline || name == "text"); + + // :: bool + // True if this is the text node type. + this.isText = name == "text"; + }; + + var prototypeAccessors$5 = { isInline: { configurable: true },isTextblock: { configurable: true },isLeaf: { configurable: true },isAtom: { configurable: true } }; + + // :: bool + // True if this is an inline type. + prototypeAccessors$5.isInline.get = function () { return !this.isBlock }; + + // :: bool + // True if this is a textblock type, a block that contains inline + // content. + prototypeAccessors$5.isTextblock.get = function () { return this.isBlock && this.inlineContent }; + + // :: bool + // True for node types that allow no content. + prototypeAccessors$5.isLeaf.get = function () { return this.contentMatch == ContentMatch.empty }; + + // :: bool + // True when this node is an atom, i.e. when it does not have + // directly editable content. + prototypeAccessors$5.isAtom.get = function () { return this.isLeaf || this.spec.atom }; + + // :: () → bool + // Tells you whether this node type has any required attributes. + NodeType.prototype.hasRequiredAttrs = function hasRequiredAttrs () { + for (var n in this.attrs) { if (this.attrs[n].isRequired) { return true } } + return false + }; + + NodeType.prototype.compatibleContent = function compatibleContent (other) { + return this == other || this.contentMatch.compatible(other.contentMatch) + }; + + NodeType.prototype.computeAttrs = function computeAttrs$1 (attrs) { + if (!attrs && this.defaultAttrs) { return this.defaultAttrs } + else { return computeAttrs(this.attrs, attrs) } + }; + + // :: (?Object, ?union, ?[Mark]) → Node + // Create a `Node` of this type. The given attributes are + // checked and defaulted (you can pass `null` to use the type's + // defaults entirely, if no required attributes exist). `content` + // may be a `Fragment`, a node, an array of nodes, or + // `null`. Similarly `marks` may be `null` to default to the empty + // set of marks. + NodeType.prototype.create = function create (attrs, content, marks) { + if (this.isText) { throw new Error("NodeType.create can't construct text nodes") } + return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks)) + }; + + // :: (?Object, ?union, ?[Mark]) → Node + // Like [`create`](#model.NodeType.create), but check the given content + // against the node type's content restrictions, and throw an error + // if it doesn't match. + NodeType.prototype.createChecked = function createChecked (attrs, content, marks) { + content = Fragment.from(content); + if (!this.validContent(content)) + { throw new RangeError("Invalid content for node " + this.name) } + return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks)) + }; + + // :: (?Object, ?union, ?[Mark]) → ?Node + // Like [`create`](#model.NodeType.create), but see if it is necessary to + // add nodes to the start or end of the given fragment to make it + // fit the node. If no fitting wrapping can be found, return null. + // Note that, due to the fact that required nodes can always be + // created, this will always succeed if you pass null or + // `Fragment.empty` as content. + NodeType.prototype.createAndFill = function createAndFill (attrs, content, marks) { + attrs = this.computeAttrs(attrs); + content = Fragment.from(content); + if (content.size) { + var before = this.contentMatch.fillBefore(content); + if (!before) { return null } + content = before.append(content); + } + var after = this.contentMatch.matchFragment(content).fillBefore(Fragment.empty, true); + if (!after) { return null } + return new Node(this, attrs, content.append(after), Mark.setFrom(marks)) + }; + + // :: (Fragment) → bool + // Returns true if the given fragment is valid content for this node + // type with the given attributes. + NodeType.prototype.validContent = function validContent (content) { + var result = this.contentMatch.matchFragment(content); + if (!result || !result.validEnd) { return false } + for (var i = 0; i < content.childCount; i++) + { if (!this.allowsMarks(content.child(i).marks)) { return false } } + return true + }; + + // :: (MarkType) → bool + // Check whether the given mark type is allowed in this node. + NodeType.prototype.allowsMarkType = function allowsMarkType (markType) { + return this.markSet == null || this.markSet.indexOf(markType) > -1 + }; + + // :: ([Mark]) → bool + // Test whether the given set of marks are allowed in this node. + NodeType.prototype.allowsMarks = function allowsMarks (marks) { + if (this.markSet == null) { return true } + for (var i = 0; i < marks.length; i++) { if (!this.allowsMarkType(marks[i].type)) { return false } } + return true + }; + + // :: ([Mark]) → [Mark] + // Removes the marks that are not allowed in this node from the given set. + NodeType.prototype.allowedMarks = function allowedMarks (marks) { + if (this.markSet == null) { return marks } + var copy; + for (var i = 0; i < marks.length; i++) { + if (!this.allowsMarkType(marks[i].type)) { + if (!copy) { copy = marks.slice(0, i); } + } else if (copy) { + copy.push(marks[i]); + } + } + return !copy ? marks : copy.length ? copy : Mark.empty + }; + + NodeType.compile = function compile (nodes, schema) { + var result = Object.create(null); + nodes.forEach(function (name, spec) { return result[name] = new NodeType(name, schema, spec); }); + + var topType = schema.spec.topNode || "doc"; + if (!result[topType]) { throw new RangeError("Schema is missing its top node type ('" + topType + "')") } + if (!result.text) { throw new RangeError("Every schema needs a 'text' type") } + for (var _ in result.text.attrs) { throw new RangeError("The text node type should not have attributes") } + + return result + }; + + Object.defineProperties( NodeType.prototype, prototypeAccessors$5 ); + + // Attribute descriptors + + var Attribute = function Attribute(options) { + this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default"); + this.default = options.default; + }; + + var prototypeAccessors$1$3 = { isRequired: { configurable: true } }; + + prototypeAccessors$1$3.isRequired.get = function () { + return !this.hasDefault + }; + + Object.defineProperties( Attribute.prototype, prototypeAccessors$1$3 ); + + // Marks + + // ::- Like nodes, marks (which are associated with nodes to signify + // things like emphasis or being part of a link) are + // [tagged](#model.Mark.type) with type objects, which are + // instantiated once per `Schema`. + var MarkType = function MarkType(name, rank, schema, spec) { + // :: string + // The name of the mark type. + this.name = name; + + // :: Schema + // The schema that this mark type instance is part of. + this.schema = schema; + + // :: MarkSpec + // The spec on which the type is based. + this.spec = spec; + + this.attrs = initAttrs(spec.attrs); + + this.rank = rank; + this.excluded = null; + var defaults = defaultAttrs(this.attrs); + this.instance = defaults && new Mark(this, defaults); + }; + + // :: (?Object) → Mark + // Create a mark of this type. `attrs` may be `null` or an object + // containing only some of the mark's attributes. The others, if + // they have defaults, will be added. + MarkType.prototype.create = function create (attrs) { + if (!attrs && this.instance) { return this.instance } + return new Mark(this, computeAttrs(this.attrs, attrs)) + }; + + MarkType.compile = function compile (marks, schema) { + var result = Object.create(null), rank = 0; + marks.forEach(function (name, spec) { return result[name] = new MarkType(name, rank++, schema, spec); }); + return result + }; + + // :: ([Mark]) → [Mark] + // When there is a mark of this type in the given set, a new set + // without it is returned. Otherwise, the input set is returned. + MarkType.prototype.removeFromSet = function removeFromSet (set) { + for (var i = 0; i < set.length; i++) + { if (set[i].type == this) + { return set.slice(0, i).concat(set.slice(i + 1)) } } + return set + }; + + // :: ([Mark]) → ?Mark + // Tests whether there is a mark of this type in the given set. + MarkType.prototype.isInSet = function isInSet (set) { + for (var i = 0; i < set.length; i++) + { if (set[i].type == this) { return set[i] } } + }; + + // :: (MarkType) → bool + // Queries whether a given mark type is + // [excluded](#model.MarkSpec.excludes) by this one. + MarkType.prototype.excludes = function excludes (other) { + return this.excluded.indexOf(other) > -1 + }; + + // SchemaSpec:: interface + // An object describing a schema, as passed to the [`Schema`](#model.Schema) + // constructor. + // + // nodes:: union, OrderedMap> + // The node types in this schema. Maps names to + // [`NodeSpec`](#model.NodeSpec) objects that describe the node type + // associated with that name. Their order is significant—it + // determines which [parse rules](#model.NodeSpec.parseDOM) take + // precedence by default, and which nodes come first in a given + // [group](#model.NodeSpec.group). + // + // marks:: ?union, OrderedMap> + // The mark types that exist in this schema. The order in which they + // are provided determines the order in which [mark + // sets](#model.Mark.addToSet) are sorted and in which [parse + // rules](#model.MarkSpec.parseDOM) are tried. + // + // topNode:: ?string + // The name of the default top-level node for the schema. Defaults + // to `"doc"`. + + // NodeSpec:: interface + // + // content:: ?string + // The content expression for this node, as described in the [schema + // guide](/docs/guide/#schema.content_expressions). When not given, + // the node does not allow any content. + // + // marks:: ?string + // The marks that are allowed inside of this node. May be a + // space-separated string referring to mark names or groups, `"_"` + // to explicitly allow all marks, or `""` to disallow marks. When + // not given, nodes with inline content default to allowing all + // marks, other nodes default to not allowing marks. + // + // group:: ?string + // The group or space-separated groups to which this node belongs, + // which can be referred to in the content expressions for the + // schema. + // + // inline:: ?bool + // Should be set to true for inline nodes. (Implied for text nodes.) + // + // atom:: ?bool + // Can be set to true to indicate that, though this isn't a [leaf + // node](#model.NodeType.isLeaf), it doesn't have directly editable + // content and should be treated as a single unit in the view. + // + // attrs:: ?Object + // The attributes that nodes of this type get. + // + // selectable:: ?bool + // Controls whether nodes of this type can be selected as a [node + // selection](#state.NodeSelection). Defaults to true for non-text + // nodes. + // + // draggable:: ?bool + // Determines whether nodes of this type can be dragged without + // being selected. Defaults to false. + // + // code:: ?bool + // Can be used to indicate that this node contains code, which + // causes some commands to behave differently. + // + // defining:: ?bool + // Determines whether this node is considered an important parent + // node during replace operations (such as paste). Non-defining (the + // default) nodes get dropped when their entire content is replaced, + // whereas defining nodes persist and wrap the inserted content. + // Likewise, in _inserted_ content the defining parents of the + // content are preserved when possible. Typically, + // non-default-paragraph textblock types, and possibly list items, + // are marked as defining. + // + // isolating:: ?bool + // When enabled (default is false), the sides of nodes of this type + // count as boundaries that regular editing operations, like + // backspacing or lifting, won't cross. An example of a node that + // should probably have this enabled is a table cell. + // + // toDOM:: ?(node: Node) → DOMOutputSpec + // Defines the default way a node of this type should be serialized + // to DOM/HTML (as used by + // [`DOMSerializer.fromSchema`](#model.DOMSerializer^fromSchema)). + // Should return a DOM node or an [array + // structure](#model.DOMOutputSpec) that describes one, with an + // optional number zero (“hole”) in it to indicate where the node's + // content should be inserted. + // + // For text nodes, the default is to create a text DOM node. Though + // it is possible to create a serializer where text is rendered + // differently, this is not supported inside the editor, so you + // shouldn't override that in your text node spec. + // + // parseDOM:: ?[ParseRule] + // Associates DOM parser information with this node, which can be + // used by [`DOMParser.fromSchema`](#model.DOMParser^fromSchema) to + // automatically derive a parser. The `node` field in the rules is + // implied (the name of this node will be filled in automatically). + // If you supply your own parser, you do not need to also specify + // parsing rules in your schema. + // + // toDebugString:: ?(node: Node) -> string + // Defines the default way a node of this type should be serialized + // to a string representation for debugging (e.g. in error messages). + + // MarkSpec:: interface + // + // attrs:: ?Object + // The attributes that marks of this type get. + // + // inclusive:: ?bool + // Whether this mark should be active when the cursor is positioned + // at its end (or at its start when that is also the start of the + // parent node). Defaults to true. + // + // excludes:: ?string + // Determines which other marks this mark can coexist with. Should + // be a space-separated strings naming other marks or groups of marks. + // When a mark is [added](#model.Mark.addToSet) to a set, all marks + // that it excludes are removed in the process. If the set contains + // any mark that excludes the new mark but is not, itself, excluded + // by the new mark, the mark can not be added an the set. You can + // use the value `"_"` to indicate that the mark excludes all + // marks in the schema. + // + // Defaults to only being exclusive with marks of the same type. You + // can set it to an empty string (or any string not containing the + // mark's own name) to allow multiple marks of a given type to + // coexist (as long as they have different attributes). + // + // group:: ?string + // The group or space-separated groups to which this mark belongs. + // + // spanning:: ?bool + // Determines whether marks of this type can span multiple adjacent + // nodes when serialized to DOM/HTML. Defaults to true. + // + // toDOM:: ?(mark: Mark, inline: bool) → DOMOutputSpec + // Defines the default way marks of this type should be serialized + // to DOM/HTML. When the resulting spec contains a hole, that is + // where the marked content is placed. Otherwise, it is appended to + // the top node. + // + // parseDOM:: ?[ParseRule] + // Associates DOM parser information with this mark (see the + // corresponding [node spec field](#model.NodeSpec.parseDOM)). The + // `mark` field in the rules is implied. + + // AttributeSpec:: interface + // + // Used to [define](#model.NodeSpec.attrs) attributes on nodes or + // marks. + // + // default:: ?any + // The default value for this attribute, to use when no explicit + // value is provided. Attributes that have no default must be + // provided whenever a node or mark of a type that has them is + // created. + + // ::- A document schema. Holds [node](#model.NodeType) and [mark + // type](#model.MarkType) objects for the nodes and marks that may + // occur in conforming documents, and provides functionality for + // creating and deserializing such documents. + var Schema = function Schema(spec) { + // :: SchemaSpec + // The [spec](#model.SchemaSpec) on which the schema is based, + // with the added guarantee that its `nodes` and `marks` + // properties are + // [`OrderedMap`](https://github.com/marijnh/orderedmap) instances + // (not raw objects). + this.spec = {}; + for (var prop in spec) { this.spec[prop] = spec[prop]; } + this.spec.nodes = orderedmap.from(spec.nodes); + this.spec.marks = orderedmap.from(spec.marks); + + // :: Object + // An object mapping the schema's node names to node type objects. + this.nodes = NodeType.compile(this.spec.nodes, this); + + // :: Object + // A map from mark names to mark type objects. + this.marks = MarkType.compile(this.spec.marks, this); + + var contentExprCache = Object.create(null); + for (var prop$1 in this.nodes) { + if (prop$1 in this.marks) + { throw new RangeError(prop$1 + " can not be both a node and a mark") } + var type = this.nodes[prop$1], contentExpr = type.spec.content || "", markExpr = type.spec.marks; + type.contentMatch = contentExprCache[contentExpr] || + (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes)); + type.inlineContent = type.contentMatch.inlineContent; + type.markSet = markExpr == "_" ? null : + markExpr ? gatherMarks(this, markExpr.split(" ")) : + markExpr == "" || !type.inlineContent ? [] : null; + } + for (var prop$2 in this.marks) { + var type$1 = this.marks[prop$2], excl = type$1.spec.excludes; + type$1.excluded = excl == null ? [type$1] : excl == "" ? [] : gatherMarks(this, excl.split(" ")); + } + + this.nodeFromJSON = this.nodeFromJSON.bind(this); + this.markFromJSON = this.markFromJSON.bind(this); + + // :: NodeType + // The type of the [default top node](#model.SchemaSpec.topNode) + // for this schema. + this.topNodeType = this.nodes[this.spec.topNode || "doc"]; + + // :: Object + // An object for storing whatever values modules may want to + // compute and cache per schema. (If you want to store something + // in it, try to use property names unlikely to clash.) + this.cached = Object.create(null); + this.cached.wrappings = Object.create(null); + }; + + // :: (union, ?Object, ?union, ?[Mark]) → Node + // Create a node in this schema. The `type` may be a string or a + // `NodeType` instance. Attributes will be extended + // with defaults, `content` may be a `Fragment`, + // `null`, a `Node`, or an array of nodes. + Schema.prototype.node = function node (type, attrs, content, marks) { + if (typeof type == "string") + { type = this.nodeType(type); } + else if (!(type instanceof NodeType)) + { throw new RangeError("Invalid node type: " + type) } + else if (type.schema != this) + { throw new RangeError("Node type from different schema used (" + type.name + ")") } + + return type.createChecked(attrs, content, marks) + }; + + // :: (string, ?[Mark]) → Node + // Create a text node in the schema. Empty text nodes are not + // allowed. + Schema.prototype.text = function text (text$1, marks) { + var type = this.nodes.text; + return new TextNode(type, type.defaultAttrs, text$1, Mark.setFrom(marks)) + }; + + // :: (union, ?Object) → Mark + // Create a mark with the given type and attributes. + Schema.prototype.mark = function mark (type, attrs) { + if (typeof type == "string") { type = this.marks[type]; } + return type.create(attrs) + }; + + // :: (Object) → Node + // Deserialize a node from its JSON representation. This method is + // bound. + Schema.prototype.nodeFromJSON = function nodeFromJSON (json) { + return Node.fromJSON(this, json) + }; + + // :: (Object) → Mark + // Deserialize a mark from its JSON representation. This method is + // bound. + Schema.prototype.markFromJSON = function markFromJSON (json) { + return Mark.fromJSON(this, json) + }; + + Schema.prototype.nodeType = function nodeType (name) { + var found = this.nodes[name]; + if (!found) { throw new RangeError("Unknown node type: " + name) } + return found + }; + + function gatherMarks(schema, marks) { + var found = []; + for (var i = 0; i < marks.length; i++) { + var name = marks[i], mark = schema.marks[name], ok = mark; + if (mark) { + found.push(mark); + } else { + for (var prop in schema.marks) { + var mark$1 = schema.marks[prop]; + if (name == "_" || (mark$1.spec.group && mark$1.spec.group.split(" ").indexOf(name) > -1)) + { found.push(ok = mark$1); } + } + } + if (!ok) { throw new SyntaxError("Unknown mark type: '" + marks[i] + "'") } + } + return found + } + + // ParseOptions:: interface + // These are the options recognized by the + // [`parse`](#model.DOMParser.parse) and + // [`parseSlice`](#model.DOMParser.parseSlice) methods. + // + // preserveWhitespace:: ?union + // By default, whitespace is collapsed as per HTML's rules. Pass + // `true` to preserve whitespace, but normalize newlines to + // spaces, and `"full"` to preserve whitespace entirely. + // + // findPositions:: ?[{node: dom.Node, offset: number}] + // When given, the parser will, beside parsing the content, + // record the document positions of the given DOM positions. It + // will do so by writing to the objects, adding a `pos` property + // that holds the document position. DOM positions that are not + // in the parsed content will not be written to. + // + // from:: ?number + // The child node index to start parsing from. + // + // to:: ?number + // The child node index to stop parsing at. + // + // topNode:: ?Node + // By default, the content is parsed into the schema's default + // [top node type](#model.Schema.topNodeType). You can pass this + // option to use the type and attributes from a different node + // as the top container. + // + // topMatch:: ?ContentMatch + // Provide the starting content match that content parsed into the + // top node is matched against. + // + // context:: ?ResolvedPos + // A set of additional nodes to count as + // [context](#model.ParseRule.context) when parsing, above the + // given [top node](#model.ParseOptions.topNode). + + // ParseRule:: interface + // A value that describes how to parse a given DOM node or inline + // style as a ProseMirror node or mark. + // + // tag:: ?string + // A CSS selector describing the kind of DOM elements to match. A + // single rule should have _either_ a `tag` or a `style` property. + // + // namespace:: ?string + // The namespace to match. This should be used with `tag`. + // Nodes are only matched when the namespace matches or this property + // is null. + // + // style:: ?string + // A CSS property name to match. When given, this rule matches + // inline styles that list that property. May also have the form + // `"property=value"`, in which case the rule only matches if the + // property's value exactly matches the given value. (For more + // complicated filters, use [`getAttrs`](#model.ParseRule.getAttrs) + // and return false to indicate that the match failed.) + // + // priority:: ?number + // Can be used to change the order in which the parse rules in a + // schema are tried. Those with higher priority come first. Rules + // without a priority are counted as having priority 50. This + // property is only meaningful in a schema—when directly + // constructing a parser, the order of the rule array is used. + // + // context:: ?string + // When given, restricts this rule to only match when the current + // context—the parent nodes into which the content is being + // parsed—matches this expression. Should contain one or more node + // names or node group names followed by single or double slashes. + // For example `"paragraph/"` means the rule only matches when the + // parent node is a paragraph, `"blockquote/paragraph/"` restricts + // it to be in a paragraph that is inside a blockquote, and + // `"section//"` matches any position inside a section—a double + // slash matches any sequence of ancestor nodes. To allow multiple + // different contexts, they can be separated by a pipe (`|`) + // character, as in `"blockquote/|list_item/"`. + // + // node:: ?string + // The name of the node type to create when this rule matches. Only + // valid for rules with a `tag` property, not for style rules. Each + // rule should have one of a `node`, `mark`, or `ignore` property + // (except when it appears in a [node](#model.NodeSpec.parseDOM) or + // [mark spec](#model.MarkSpec.parseDOM), in which case the `node` + // or `mark` property will be derived from its position). + // + // mark:: ?string + // The name of the mark type to wrap the matched content in. + // + // ignore:: ?bool + // When true, ignore content that matches this rule. + // + // closeParent:: ?bool + // When true, finding an element that matches this rule will close + // the current node. + // + // skip:: ?bool + // When true, ignore the node that matches this rule, but do parse + // its content. + // + // attrs:: ?Object + // Attributes for the node or mark created by this rule. When + // `getAttrs` is provided, it takes precedence. + // + // getAttrs:: ?(union) → ?union + // A function used to compute the attributes for the node or mark + // created by this rule. Can also be used to describe further + // conditions the DOM element or style must match. When it returns + // `false`, the rule won't match. When it returns null or undefined, + // that is interpreted as an empty/default set of attributes. + // + // Called with a DOM Element for `tag` rules, and with a string (the + // style's value) for `style` rules. + // + // contentElement:: ?union + // For `tag` rules that produce non-leaf nodes or marks, by default + // the content of the DOM element is parsed as content of the mark + // or node. If the child nodes are in a descendent node, this may be + // a CSS selector string that the parser must use to find the actual + // content element, or a function that returns the actual content + // element to the parser. + // + // getContent:: ?(dom.Node, schema: Schema) → Fragment + // Can be used to override the content of a matched node. When + // present, instead of parsing the node's child nodes, the result of + // this function is used. + // + // preserveWhitespace:: ?union + // Controls whether whitespace should be preserved when parsing the + // content inside the matched element. `false` means whitespace may + // be collapsed, `true` means that whitespace should be preserved + // but newlines normalized to spaces, and `"full"` means that + // newlines should also be preserved. + + // ::- A DOM parser represents a strategy for parsing DOM content into + // a ProseMirror document conforming to a given schema. Its behavior + // is defined by an array of [rules](#model.ParseRule). + var DOMParser$1 = function DOMParser(schema, rules) { + var this$1 = this; + + // :: Schema + // The schema into which the parser parses. + this.schema = schema; + // :: [ParseRule] + // The set of [parse rules](#model.ParseRule) that the parser + // uses, in order of precedence. + this.rules = rules; + this.tags = []; + this.styles = []; + + rules.forEach(function (rule) { + if (rule.tag) { this$1.tags.push(rule); } + else if (rule.style) { this$1.styles.push(rule); } + }); + + // Only normalize list elements when lists in the schema can't directly contain themselves + this.normalizeLists = !this.tags.some(function (r) { + if (!/^(ul|ol)\b/.test(r.tag) || !r.node) { return false } + var node = schema.nodes[r.node]; + return node.contentMatch.matchType(node) + }); + }; + + // :: (dom.Node, ?ParseOptions) → Node + // Parse a document from the content of a DOM node. + DOMParser$1.prototype.parse = function parse (dom, options) { + if ( options === void 0 ) options = {}; + + var context = new ParseContext(this, options, false); + context.addAll(dom, null, options.from, options.to); + return context.finish() + }; + + // :: (dom.Node, ?ParseOptions) → Slice + // Parses the content of the given DOM node, like + // [`parse`](#model.DOMParser.parse), and takes the same set of + // options. But unlike that method, which produces a whole node, + // this one returns a slice that is open at the sides, meaning that + // the schema constraints aren't applied to the start of nodes to + // the left of the input and the end of nodes at the end. + DOMParser$1.prototype.parseSlice = function parseSlice (dom, options) { + if ( options === void 0 ) options = {}; + + var context = new ParseContext(this, options, true); + context.addAll(dom, null, options.from, options.to); + return Slice.maxOpen(context.finish()) + }; + + DOMParser$1.prototype.matchTag = function matchTag (dom, context) { + for (var i = 0; i < this.tags.length; i++) { + var rule = this.tags[i]; + if (matches(dom, rule.tag) && + (rule.namespace === undefined || dom.namespaceURI == rule.namespace) && + (!rule.context || context.matchesContext(rule.context))) { + if (rule.getAttrs) { + var result = rule.getAttrs(dom); + if (result === false) { continue } + rule.attrs = result; + } + return rule + } + } + }; + + DOMParser$1.prototype.matchStyle = function matchStyle (prop, value, context) { + for (var i = 0; i < this.styles.length; i++) { + var rule = this.styles[i]; + if (rule.style.indexOf(prop) != 0 || + rule.context && !context.matchesContext(rule.context) || + // Test that the style string either precisely matches the prop, + // or has an '=' sign after the prop, followed by the given + // value. + rule.style.length > prop.length && + (rule.style.charCodeAt(prop.length) != 61 || rule.style.slice(prop.length + 1) != value)) + { continue } + if (rule.getAttrs) { + var result = rule.getAttrs(value); + if (result === false) { continue } + rule.attrs = result; + } + return rule + } + }; + + // : (Schema) → [ParseRule] + DOMParser$1.schemaRules = function schemaRules (schema) { + var result = []; + function insert(rule) { + var priority = rule.priority == null ? 50 : rule.priority, i = 0; + for (; i < result.length; i++) { + var next = result[i], nextPriority = next.priority == null ? 50 : next.priority; + if (nextPriority < priority) { break } + } + result.splice(i, 0, rule); + } + + var loop = function ( name ) { + var rules = schema.marks[name].spec.parseDOM; + if (rules) { rules.forEach(function (rule) { + insert(rule = copy$1(rule)); + rule.mark = name; + }); } + }; + + for (var name in schema.marks) loop( name ); + var loop$1 = function ( name ) { + var rules$1 = schema.nodes[name$1].spec.parseDOM; + if (rules$1) { rules$1.forEach(function (rule) { + insert(rule = copy$1(rule)); + rule.node = name$1; + }); } + }; + + for (var name$1 in schema.nodes) loop$1(); + return result + }; + + // :: (Schema) → DOMParser + // Construct a DOM parser using the parsing rules listed in a + // schema's [node specs](#model.NodeSpec.parseDOM), reordered by + // [priority](#model.ParseRule.priority). + DOMParser$1.fromSchema = function fromSchema (schema) { + return schema.cached.domParser || + (schema.cached.domParser = new DOMParser$1(schema, DOMParser$1.schemaRules(schema))) + }; + + // : Object The block-level tags in HTML5 + var blockTags = { + address: true, article: true, aside: true, blockquote: true, canvas: true, + dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true, + footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true, + h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true, + output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true + }; + + // : Object The tags that we normally ignore. + var ignoreTags = { + head: true, noscript: true, object: true, script: true, style: true, title: true + }; + + // : Object List tags. + var listTags = {ol: true, ul: true}; + + // Using a bitfield for node context options + var OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4; + + function wsOptionsFor(preserveWhitespace) { + return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0) + } + + var NodeContext = function NodeContext(type, attrs, marks, pendingMarks, solid, match, options) { + this.type = type; + this.attrs = attrs; + this.solid = solid; + this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch); + this.options = options; + this.content = []; + // Marks applied to this node itself + this.marks = marks; + // Marks applied to its children + this.activeMarks = Mark.none; + // Marks that can't apply here, but will be used in children if possible + this.pendingMarks = pendingMarks; + // Nested Marks with same type + this.stashMarks = []; + }; + + NodeContext.prototype.findWrapping = function findWrapping (node) { + if (!this.match) { + if (!this.type) { return [] } + var fill = this.type.contentMatch.fillBefore(Fragment.from(node)); + if (fill) { + this.match = this.type.contentMatch.matchFragment(fill); + } else { + var start = this.type.contentMatch, wrap; + if (wrap = start.findWrapping(node.type)) { + this.match = start; + return wrap + } else { + return null + } + } + } + return this.match.findWrapping(node.type) + }; + + NodeContext.prototype.finish = function finish (openEnd) { + if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace + var last = this.content[this.content.length - 1], m; + if (last && last.isText && (m = /[ \t\r\n\u000c]+$/.exec(last.text))) { + if (last.text.length == m[0].length) { this.content.pop(); } + else { this.content[this.content.length - 1] = last.withText(last.text.slice(0, last.text.length - m[0].length)); } + } + } + var content = Fragment.from(this.content); + if (!openEnd && this.match) + { content = content.append(this.match.fillBefore(Fragment.empty, true)); } + return this.type ? this.type.create(this.attrs, content, this.marks) : content + }; + + NodeContext.prototype.popFromStashMark = function popFromStashMark (markType) { + for (var i = this.stashMarks.length - 1; i >= 0; i--) + { if (this.stashMarks[i].type == markType) { return this.stashMarks.splice(i, 1)[0] } } + }; + + NodeContext.prototype.applyPending = function applyPending (nextType) { + for (var i = 0, pending = this.pendingMarks; i < pending.length; i++) { + var mark = pending[i]; + if ((this.type ? this.type.allowsMarkType(mark.type) : markMayApply(mark.type, nextType)) && + !mark.isInSet(this.activeMarks)) { + var found = findSameTypeInSet(mark, this.activeMarks); + if (found) { this.stashMarks.push(found); } + this.activeMarks = mark.addToSet(this.activeMarks); + this.pendingMarks = mark.removeFromSet(this.pendingMarks); + } + } + }; + + var ParseContext = function ParseContext(parser, options, open) { + // : DOMParser The parser we are using. + this.parser = parser; + // : Object The options passed to this parse. + this.options = options; + this.isOpen = open; + var topNode = options.topNode, topContext; + var topOptions = wsOptionsFor(options.preserveWhitespace) | (open ? OPT_OPEN_LEFT : 0); + if (topNode) + { topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, Mark.none, true, + options.topMatch || topNode.type.contentMatch, topOptions); } + else if (open) + { topContext = new NodeContext(null, null, Mark.none, Mark.none, true, null, topOptions); } + else + { topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, Mark.none, true, null, topOptions); } + this.nodes = [topContext]; + // : [Mark] The current set of marks + this.open = 0; + this.find = options.findPositions; + this.needsBlock = false; + }; + + var prototypeAccessors$6 = { top: { configurable: true },currentPos: { configurable: true } }; + + prototypeAccessors$6.top.get = function () { + return this.nodes[this.open] + }; + + // : (dom.Node) + // Add a DOM node to the content. Text is inserted as text node, + // otherwise, the node is passed to `addElement` or, if it has a + // `style` attribute, `addElementWithStyles`. + ParseContext.prototype.addDOM = function addDOM (dom) { + if (dom.nodeType == 3) { + this.addTextNode(dom); + } else if (dom.nodeType == 1) { + var style = dom.getAttribute("style"); + var marks = style ? this.readStyles(parseStyles(style)) : null, top = this.top; + if (marks != null) { for (var i = 0; i < marks.length; i++) { this.addPendingMark(marks[i]); } } + this.addElement(dom); + if (marks != null) { for (var i$1 = 0; i$1 < marks.length; i$1++) { this.removePendingMark(marks[i$1], top); } } + } + }; + + ParseContext.prototype.addTextNode = function addTextNode (dom) { + var value = dom.nodeValue; + var top = this.top; + if ((top.type ? top.type.inlineContent : top.content.length && top.content[0].isInline) || /[^ \t\r\n\u000c]/.test(value)) { + if (!(top.options & OPT_PRESERVE_WS)) { + value = value.replace(/[ \t\r\n\u000c]+/g, " "); + // If this starts with whitespace, and there is no node before it, or + // a hard break, or a text node that ends with whitespace, strip the + // leading space. + if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) { + var nodeBefore = top.content[top.content.length - 1]; + var domNodeBefore = dom.previousSibling; + if (!nodeBefore || + (domNodeBefore && domNodeBefore.nodeName == 'BR') || + (nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text))) + { value = value.slice(1); } + } + } else if (!(top.options & OPT_PRESERVE_WS_FULL)) { + value = value.replace(/\r?\n|\r/g, " "); + } + if (value) { this.insertNode(this.parser.schema.text(value)); } + this.findInText(dom); + } else { + this.findInside(dom); + } + }; + + // : (dom.Element) + // Try to find a handler for the given tag and use that to parse. If + // none is found, the element's content nodes are added directly. + ParseContext.prototype.addElement = function addElement (dom) { + var name = dom.nodeName.toLowerCase(); + if (listTags.hasOwnProperty(name) && this.parser.normalizeLists) { normalizeList(dom); } + var rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) || this.parser.matchTag(dom, this); + if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) { + this.findInside(dom); + } else if (!rule || rule.skip || rule.closeParent) { + if (rule && rule.closeParent) { this.open = Math.max(0, this.open - 1); } + else if (rule && rule.skip.nodeType) { dom = rule.skip; } + var sync, top = this.top, oldNeedsBlock = this.needsBlock; + if (blockTags.hasOwnProperty(name)) { + sync = true; + if (!top.type) { this.needsBlock = true; } + } else if (!dom.firstChild) { + this.leafFallback(dom); + return + } + this.addAll(dom); + if (sync) { this.sync(top); } + this.needsBlock = oldNeedsBlock; + } else { + this.addElementByRule(dom, rule); + } + }; + + // Called for leaf DOM nodes that would otherwise be ignored + ParseContext.prototype.leafFallback = function leafFallback (dom) { + if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent) + { this.addTextNode(dom.ownerDocument.createTextNode("\n")); } + }; + + // Run any style parser associated with the node's styles. Either + // return an array of marks, or null to indicate some of the styles + // had a rule with `ignore` set. + ParseContext.prototype.readStyles = function readStyles (styles) { + var marks = Mark.none; + for (var i = 0; i < styles.length; i += 2) { + var rule = this.parser.matchStyle(styles[i], styles[i + 1], this); + if (!rule) { continue } + if (rule.ignore) { return null } + marks = this.parser.schema.marks[rule.mark].create(rule.attrs).addToSet(marks); + } + return marks + }; + + // : (dom.Element, ParseRule) → bool + // Look up a handler for the given node. If none are found, return + // false. Otherwise, apply it, use its return value to drive the way + // the node's content is wrapped, and return true. + ParseContext.prototype.addElementByRule = function addElementByRule (dom, rule) { + var this$1 = this; + + var sync, nodeType, markType, mark; + if (rule.node) { + nodeType = this.parser.schema.nodes[rule.node]; + if (!nodeType.isLeaf) { + sync = this.enter(nodeType, rule.attrs, rule.preserveWhitespace); + } else if (!this.insertNode(nodeType.create(rule.attrs))) { + this.leafFallback(dom); + } + } else { + markType = this.parser.schema.marks[rule.mark]; + mark = markType.create(rule.attrs); + this.addPendingMark(mark); + } + var startIn = this.top; + + if (nodeType && nodeType.isLeaf) { + this.findInside(dom); + } else if (rule.getContent) { + this.findInside(dom); + rule.getContent(dom, this.parser.schema).forEach(function (node) { return this$1.insertNode(node); }); + } else { + var contentDOM = rule.contentElement; + if (typeof contentDOM == "string") { contentDOM = dom.querySelector(contentDOM); } + else if (typeof contentDOM == "function") { contentDOM = contentDOM(dom); } + if (!contentDOM) { contentDOM = dom; } + this.findAround(dom, contentDOM, true); + this.addAll(contentDOM, sync); + } + if (sync) { this.sync(startIn); this.open--; } + if (mark) { this.removePendingMark(mark, startIn); } + }; + + // : (dom.Node, ?NodeBuilder, ?number, ?number) + // Add all child nodes between `startIndex` and `endIndex` (or the + // whole node, if not given). If `sync` is passed, use it to + // synchronize after every block element. + ParseContext.prototype.addAll = function addAll (parent, sync, startIndex, endIndex) { + var index = startIndex || 0; + for (var dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, + end = endIndex == null ? null : parent.childNodes[endIndex]; + dom != end; dom = dom.nextSibling, ++index) { + this.findAtPoint(parent, index); + this.addDOM(dom); + if (sync && blockTags.hasOwnProperty(dom.nodeName.toLowerCase())) + { this.sync(sync); } + } + this.findAtPoint(parent, index); + }; + + // Try to find a way to fit the given node type into the current + // context. May add intermediate wrappers and/or leave non-solid + // nodes that we're in. + ParseContext.prototype.findPlace = function findPlace (node) { + var route, sync; + for (var depth = this.open; depth >= 0; depth--) { + var cx = this.nodes[depth]; + var found = cx.findWrapping(node); + if (found && (!route || route.length > found.length)) { + route = found; + sync = cx; + if (!found.length) { break } + } + if (cx.solid) { break } + } + if (!route) { return false } + this.sync(sync); + for (var i = 0; i < route.length; i++) + { this.enterInner(route[i], null, false); } + return true + }; + + // : (Node) → ?Node + // Try to insert the given node, adjusting the context when needed. + ParseContext.prototype.insertNode = function insertNode (node) { + if (node.isInline && this.needsBlock && !this.top.type) { + var block = this.textblockFromContext(); + if (block) { this.enterInner(block); } + } + if (this.findPlace(node)) { + this.closeExtra(); + var top = this.top; + top.applyPending(node.type); + if (top.match) { top.match = top.match.matchType(node.type); } + var marks = top.activeMarks; + for (var i = 0; i < node.marks.length; i++) + { if (!top.type || top.type.allowsMarkType(node.marks[i].type)) + { marks = node.marks[i].addToSet(marks); } } + top.content.push(node.mark(marks)); + return true + } + return false + }; + + // : (NodeType, ?Object) → bool + // Try to start a node of the given type, adjusting the context when + // necessary. + ParseContext.prototype.enter = function enter (type, attrs, preserveWS) { + var ok = this.findPlace(type.create(attrs)); + if (ok) { this.enterInner(type, attrs, true, preserveWS); } + return ok + }; + + // Open a node of the given type + ParseContext.prototype.enterInner = function enterInner (type, attrs, solid, preserveWS) { + this.closeExtra(); + var top = this.top; + top.applyPending(type); + top.match = top.match && top.match.matchType(type, attrs); + var options = preserveWS == null ? top.options & ~OPT_OPEN_LEFT : wsOptionsFor(preserveWS); + if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0) { options |= OPT_OPEN_LEFT; } + this.nodes.push(new NodeContext(type, attrs, top.activeMarks, top.pendingMarks, solid, null, options)); + this.open++; + }; + + // Make sure all nodes above this.open are finished and added to + // their parents + ParseContext.prototype.closeExtra = function closeExtra (openEnd) { + var i = this.nodes.length - 1; + if (i > this.open) { + for (; i > this.open; i--) { this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd)); } + this.nodes.length = this.open + 1; + } + }; + + ParseContext.prototype.finish = function finish () { + this.open = 0; + this.closeExtra(this.isOpen); + return this.nodes[0].finish(this.isOpen || this.options.topOpen) + }; + + ParseContext.prototype.sync = function sync (to) { + for (var i = this.open; i >= 0; i--) { if (this.nodes[i] == to) { + this.open = i; + return + } } + }; + + prototypeAccessors$6.currentPos.get = function () { + this.closeExtra(); + var pos = 0; + for (var i = this.open; i >= 0; i--) { + var content = this.nodes[i].content; + for (var j = content.length - 1; j >= 0; j--) + { pos += content[j].nodeSize; } + if (i) { pos++; } + } + return pos + }; + + ParseContext.prototype.findAtPoint = function findAtPoint (parent, offset) { + if (this.find) { for (var i = 0; i < this.find.length; i++) { + if (this.find[i].node == parent && this.find[i].offset == offset) + { this.find[i].pos = this.currentPos; } + } } + }; + + ParseContext.prototype.findInside = function findInside (parent) { + if (this.find) { for (var i = 0; i < this.find.length; i++) { + if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) + { this.find[i].pos = this.currentPos; } + } } + }; + + ParseContext.prototype.findAround = function findAround (parent, content, before) { + if (parent != content && this.find) { for (var i = 0; i < this.find.length; i++) { + if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) { + var pos = content.compareDocumentPosition(this.find[i].node); + if (pos & (before ? 2 : 4)) + { this.find[i].pos = this.currentPos; } + } + } } + }; + + ParseContext.prototype.findInText = function findInText (textNode) { + if (this.find) { for (var i = 0; i < this.find.length; i++) { + if (this.find[i].node == textNode) + { this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset); } + } } + }; + + // : (string) → bool + // Determines whether the given [context + // string](#ParseRule.context) matches this context. + ParseContext.prototype.matchesContext = function matchesContext (context) { + var this$1 = this; + + if (context.indexOf("|") > -1) + { return context.split(/\s*\|\s*/).some(this.matchesContext, this) } + + var parts = context.split("/"); + var option = this.options.context; + var useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type); + var minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1); + var match = function (i, depth) { + for (; i >= 0; i--) { + var part = parts[i]; + if (part == "") { + if (i == parts.length - 1 || i == 0) { continue } + for (; depth >= minDepth; depth--) + { if (match(i - 1, depth)) { return true } } + return false + } else { + var next = depth > 0 || (depth == 0 && useRoot) ? this$1.nodes[depth].type + : option && depth >= minDepth ? option.node(depth - minDepth).type + : null; + if (!next || (next.name != part && next.groups.indexOf(part) == -1)) + { return false } + depth--; + } + } + return true + }; + return match(parts.length - 1, this.open) + }; + + ParseContext.prototype.textblockFromContext = function textblockFromContext () { + var $context = this.options.context; + if ($context) { for (var d = $context.depth; d >= 0; d--) { + var deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType; + if (deflt && deflt.isTextblock && deflt.defaultAttrs) { return deflt } + } } + for (var name in this.parser.schema.nodes) { + var type = this.parser.schema.nodes[name]; + if (type.isTextblock && type.defaultAttrs) { return type } + } + }; + + ParseContext.prototype.addPendingMark = function addPendingMark (mark) { + var found = findSameTypeInSet(mark, this.top.pendingMarks); + if (found) { this.top.stashMarks.push(found); } + this.top.pendingMarks = mark.addToSet(this.top.pendingMarks); + }; + + ParseContext.prototype.removePendingMark = function removePendingMark (mark, upto) { + for (var depth = this.open; depth >= 0; depth--) { + var level = this.nodes[depth]; + var found = level.pendingMarks.lastIndexOf(mark); + if (found > -1) { + level.pendingMarks = mark.removeFromSet(level.pendingMarks); + } else { + level.activeMarks = mark.removeFromSet(level.activeMarks); + var stashMark = level.popFromStashMark(mark.type); + if (stashMark) { level.activeMarks = stashMark.addToSet(level.activeMarks); } + } + if (level == upto) { break } + } + }; + + Object.defineProperties( ParseContext.prototype, prototypeAccessors$6 ); + + // Kludge to work around directly nested list nodes produced by some + // tools and allowed by browsers to mean that the nested list is + // actually part of the list item above it. + function normalizeList(dom) { + for (var child = dom.firstChild, prevItem = null; child; child = child.nextSibling) { + var name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null; + if (name && listTags.hasOwnProperty(name) && prevItem) { + prevItem.appendChild(child); + child = prevItem; + } else if (name == "li") { + prevItem = child; + } else if (name) { + prevItem = null; + } + } + } + + // Apply a CSS selector. + function matches(dom, selector) { + return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector) + } + + // : (string) → [string] + // Tokenize a style attribute into property/value pairs. + function parseStyles(style) { + var re = /\s*([\w-]+)\s*:\s*([^;]+)/g, m, result = []; + while (m = re.exec(style)) { result.push(m[1], m[2].trim()); } + return result + } + + function copy$1(obj) { + var copy = {}; + for (var prop in obj) { copy[prop] = obj[prop]; } + return copy + } + + // Used when finding a mark at the top level of a fragment parse. + // Checks whether it would be reasonable to apply a given mark type to + // a given node, by looking at the way the mark occurs in the schema. + function markMayApply(markType, nodeType) { + var nodes = nodeType.schema.nodes; + var loop = function ( name ) { + var parent = nodes[name]; + if (!parent.allowsMarkType(markType)) { return } + var seen = [], scan = function (match) { + seen.push(match); + for (var i = 0; i < match.edgeCount; i++) { + var ref = match.edge(i); + var type = ref.type; + var next = ref.next; + if (type == nodeType) { return true } + if (seen.indexOf(next) < 0 && scan(next)) { return true } + } + }; + if (scan(parent.contentMatch)) { return { v: true } } + }; + + for (var name in nodes) { + var returned = loop( name ); + + if ( returned ) return returned.v; + } + } + + function findSameTypeInSet(mark, set) { + for (var i = 0; i < set.length; i++) { + if (mark.type == set[i].type) { return set[i] } + } + } + + // DOMOutputSpec:: interface + // A description of a DOM structure. Can be either a string, which is + // interpreted as a text node, a DOM node, which is interpreted as + // itself, a `{dom: Node, contentDOM: ?Node}` object, or an array. + // + // An array describes a DOM element. The first value in the array + // should be a string—the name of the DOM element, optionally prefixed + // by a namespace URL and a space. If the second element is plain + // object, it is interpreted as a set of attributes for the element. + // Any elements after that (including the 2nd if it's not an attribute + // object) are interpreted as children of the DOM elements, and must + // either be valid `DOMOutputSpec` values, or the number zero. + // + // The number zero (pronounced “hole”) is used to indicate the place + // where a node's child nodes should be inserted. If it occurs in an + // output spec, it should be the only child element in its parent + // node. + + // ::- A DOM serializer knows how to convert ProseMirror nodes and + // marks of various types to DOM nodes. + var DOMSerializer = function DOMSerializer(nodes, marks) { + // :: Object<(node: Node) → DOMOutputSpec> + // The node serialization functions. + this.nodes = nodes || {}; + // :: Object + // The mark serialization functions. + this.marks = marks || {}; + }; + + // :: (Fragment, ?Object) → dom.DocumentFragment + // Serialize the content of this fragment to a DOM fragment. When + // not in the browser, the `document` option, containing a DOM + // document, should be passed so that the serializer can create + // nodes. + DOMSerializer.prototype.serializeFragment = function serializeFragment (fragment, options, target) { + var this$1 = this; + if ( options === void 0 ) options = {}; + + if (!target) { target = doc$1(options).createDocumentFragment(); } + + var top = target, active = null; + fragment.forEach(function (node) { + if (active || node.marks.length) { + if (!active) { active = []; } + var keep = 0, rendered = 0; + while (keep < active.length && rendered < node.marks.length) { + var next = node.marks[rendered]; + if (!this$1.marks[next.type.name]) { rendered++; continue } + if (!next.eq(active[keep]) || next.type.spec.spanning === false) { break } + keep += 2; rendered++; + } + while (keep < active.length) { + top = active.pop(); + active.pop(); + } + while (rendered < node.marks.length) { + var add = node.marks[rendered++]; + var markDOM = this$1.serializeMark(add, node.isInline, options); + if (markDOM) { + active.push(add, top); + top.appendChild(markDOM.dom); + top = markDOM.contentDOM || markDOM.dom; + } + } + } + top.appendChild(this$1.serializeNode(node, options)); + }); + + return target + }; + + // :: (Node, ?Object) → dom.Node + // Serialize this node to a DOM node. This can be useful when you + // need to serialize a part of a document, as opposed to the whole + // document. To serialize a whole document, use + // [`serializeFragment`](#model.DOMSerializer.serializeFragment) on + // its [content](#model.Node.content). + DOMSerializer.prototype.serializeNode = function serializeNode (node, options) { + if ( options === void 0 ) options = {}; + + var ref = + DOMSerializer.renderSpec(doc$1(options), this.nodes[node.type.name](node)); + var dom = ref.dom; + var contentDOM = ref.contentDOM; + if (contentDOM) { + if (node.isLeaf) + { throw new RangeError("Content hole not allowed in a leaf node spec") } + if (options.onContent) + { options.onContent(node, contentDOM, options); } + else + { this.serializeFragment(node.content, options, contentDOM); } + } + return dom + }; + + DOMSerializer.prototype.serializeNodeAndMarks = function serializeNodeAndMarks (node, options) { + if ( options === void 0 ) options = {}; + + var dom = this.serializeNode(node, options); + for (var i = node.marks.length - 1; i >= 0; i--) { + var wrap = this.serializeMark(node.marks[i], node.isInline, options); + if (wrap) { + (wrap.contentDOM || wrap.dom).appendChild(dom); + dom = wrap.dom; + } + } + return dom + }; + + DOMSerializer.prototype.serializeMark = function serializeMark (mark, inline, options) { + if ( options === void 0 ) options = {}; + + var toDOM = this.marks[mark.type.name]; + return toDOM && DOMSerializer.renderSpec(doc$1(options), toDOM(mark, inline)) + }; + + // :: (dom.Document, DOMOutputSpec) → {dom: dom.Node, contentDOM: ?dom.Node} + // Render an [output spec](#model.DOMOutputSpec) to a DOM node. If + // the spec has a hole (zero) in it, `contentDOM` will point at the + // node with the hole. + DOMSerializer.renderSpec = function renderSpec (doc, structure, xmlNS) { + if ( xmlNS === void 0 ) xmlNS = null; + + if (typeof structure == "string") + { return {dom: doc.createTextNode(structure)} } + if (structure.nodeType != null) + { return {dom: structure} } + if (structure.dom && structure.dom.nodeType != null) + { return structure } + var tagName = structure[0], space = tagName.indexOf(" "); + if (space > 0) { + xmlNS = tagName.slice(0, space); + tagName = tagName.slice(space + 1); + } + var contentDOM = null, dom = xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName); + var attrs = structure[1], start = 1; + if (attrs && typeof attrs == "object" && attrs.nodeType == null && !Array.isArray(attrs)) { + start = 2; + for (var name in attrs) { if (attrs[name] != null) { + var space$1 = name.indexOf(" "); + if (space$1 > 0) { dom.setAttributeNS(name.slice(0, space$1), name.slice(space$1 + 1), attrs[name]); } + else { dom.setAttribute(name, attrs[name]); } + } } + } + for (var i = start; i < structure.length; i++) { + var child = structure[i]; + if (child === 0) { + if (i < structure.length - 1 || i > start) + { throw new RangeError("Content hole must be the only child of its parent node") } + return {dom: dom, contentDOM: dom} + } else { + var ref = DOMSerializer.renderSpec(doc, child, xmlNS); + var inner = ref.dom; + var innerContent = ref.contentDOM; + dom.appendChild(inner); + if (innerContent) { + if (contentDOM) { throw new RangeError("Multiple content holes") } + contentDOM = innerContent; + } + } + } + return {dom: dom, contentDOM: contentDOM} + }; + + // :: (Schema) → DOMSerializer + // Build a serializer using the [`toDOM`](#model.NodeSpec.toDOM) + // properties in a schema's node and mark specs. + DOMSerializer.fromSchema = function fromSchema (schema) { + return schema.cached.domSerializer || + (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema))) + }; + + // : (Schema) → Object<(node: Node) → DOMOutputSpec> + // Gather the serializers in a schema's node specs into an object. + // This can be useful as a base to build a custom serializer from. + DOMSerializer.nodesFromSchema = function nodesFromSchema (schema) { + var result = gatherToDOM(schema.nodes); + if (!result.text) { result.text = function (node) { return node.text; }; } + return result + }; + + // : (Schema) → Object<(mark: Mark) → DOMOutputSpec> + // Gather the serializers in a schema's mark specs into an object. + DOMSerializer.marksFromSchema = function marksFromSchema (schema) { + return gatherToDOM(schema.marks) + }; + + function gatherToDOM(obj) { + var result = {}; + for (var name in obj) { + var toDOM = obj[name].spec.toDOM; + if (toDOM) { result[name] = toDOM; } + } + return result + } + + function doc$1(options) { + // declare global: window + return options.document || window.document + } + + // Mappable:: interface + // There are several things that positions can be mapped through. + // Such objects conform to this interface. + // + // map:: (pos: number, assoc: ?number) → number + // Map a position through this object. When given, `assoc` (should + // be -1 or 1, defaults to 1) determines with which side the + // position is associated, which determines in which direction to + // move when a chunk of content is inserted at the mapped position. + // + // mapResult:: (pos: number, assoc: ?number) → MapResult + // Map a position, and return an object containing additional + // information about the mapping. The result's `deleted` field tells + // you whether the position was deleted (completely enclosed in a + // replaced range) during the mapping. When content on only one side + // is deleted, the position itself is only considered deleted when + // `assoc` points in the direction of the deleted content. + + // Recovery values encode a range index and an offset. They are + // represented as numbers, because tons of them will be created when + // mapping, for example, a large number of decorations. The number's + // lower 16 bits provide the index, the remaining bits the offset. + // + // Note: We intentionally don't use bit shift operators to en- and + // decode these, since those clip to 32 bits, which we might in rare + // cases want to overflow. A 64-bit float can represent 48-bit + // integers precisely. + + var lower16 = 0xffff; + var factor16 = Math.pow(2, 16); + + function makeRecover(index, offset) { return index + offset * factor16 } + function recoverIndex(value) { return value & lower16 } + function recoverOffset(value) { return (value - (value & lower16)) / factor16 } + + // ::- An object representing a mapped position with extra + // information. + var MapResult = function MapResult(pos, deleted, recover) { + if ( deleted === void 0 ) deleted = false; + if ( recover === void 0 ) recover = null; + + // :: number The mapped version of the position. + this.pos = pos; + // :: bool Tells you whether the position was deleted, that is, + // whether the step removed its surroundings from the document. + this.deleted = deleted; + this.recover = recover; + }; + + // :: class extends Mappable + // A map describing the deletions and insertions made by a step, which + // can be used to find the correspondence between positions in the + // pre-step version of a document and the same position in the + // post-step version. + var StepMap = function StepMap(ranges, inverted) { + if ( inverted === void 0 ) inverted = false; + + this.ranges = ranges; + this.inverted = inverted; + }; + + StepMap.prototype.recover = function recover (value) { + var diff = 0, index = recoverIndex(value); + if (!this.inverted) { for (var i = 0; i < index; i++) + { diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1]; } } + return this.ranges[index * 3] + diff + recoverOffset(value) + }; + + // : (number, ?number) → MapResult + StepMap.prototype.mapResult = function mapResult (pos, assoc) { + if ( assoc === void 0 ) assoc = 1; + return this._map(pos, assoc, false) }; + + // : (number, ?number) → number + StepMap.prototype.map = function map (pos, assoc) { + if ( assoc === void 0 ) assoc = 1; + return this._map(pos, assoc, true) }; + + StepMap.prototype._map = function _map (pos, assoc, simple) { + var diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; + for (var i = 0; i < this.ranges.length; i += 3) { + var start = this.ranges[i] - (this.inverted ? diff : 0); + if (start > pos) { break } + var oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize; + if (pos <= end) { + var side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc; + var result = start + diff + (side < 0 ? 0 : newSize); + if (simple) { return result } + var recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start); + return new MapResult(result, assoc < 0 ? pos != start : pos != end, recover) + } + diff += newSize - oldSize; + } + return simple ? pos + diff : new MapResult(pos + diff) + }; + + StepMap.prototype.touches = function touches (pos, recover) { + var diff = 0, index = recoverIndex(recover); + var oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; + for (var i = 0; i < this.ranges.length; i += 3) { + var start = this.ranges[i] - (this.inverted ? diff : 0); + if (start > pos) { break } + var oldSize = this.ranges[i + oldIndex], end = start + oldSize; + if (pos <= end && i == index * 3) { return true } + diff += this.ranges[i + newIndex] - oldSize; + } + return false + }; + + // :: ((oldStart: number, oldEnd: number, newStart: number, newEnd: number)) + // Calls the given function on each of the changed ranges included in + // this map. + StepMap.prototype.forEach = function forEach (f) { + var oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; + for (var i = 0, diff = 0; i < this.ranges.length; i += 3) { + var start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff); + var oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex]; + f(oldStart, oldStart + oldSize, newStart, newStart + newSize); + diff += newSize - oldSize; + } + }; + + // :: () → StepMap + // Create an inverted version of this map. The result can be used to + // map positions in the post-step document to the pre-step document. + StepMap.prototype.invert = function invert () { + return new StepMap(this.ranges, !this.inverted) + }; + + StepMap.prototype.toString = function toString () { + return (this.inverted ? "-" : "") + JSON.stringify(this.ranges) + }; + + // :: (n: number) → StepMap + // Create a map that moves all positions by offset `n` (which may be + // negative). This can be useful when applying steps meant for a + // sub-document to a larger document, or vice-versa. + StepMap.offset = function offset (n) { + return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]) + }; + + StepMap.empty = new StepMap([]); + + // :: class extends Mappable + // A mapping represents a pipeline of zero or more [step + // maps](#transform.StepMap). It has special provisions for losslessly + // handling mapping positions through a series of steps in which some + // steps are inverted versions of earlier steps. (This comes up when + // ‘[rebasing](/docs/guide/#transform.rebasing)’ steps for + // collaboration or history management.) + var Mapping = function Mapping(maps, mirror, from, to) { + // :: [StepMap] + // The step maps in this mapping. + this.maps = maps || []; + // :: number + // The starting position in the `maps` array, used when `map` or + // `mapResult` is called. + this.from = from || 0; + // :: number + // The end position in the `maps` array. + this.to = to == null ? this.maps.length : to; + this.mirror = mirror; + }; + + // :: (?number, ?number) → Mapping + // Create a mapping that maps only through a part of this one. + Mapping.prototype.slice = function slice (from, to) { + if ( from === void 0 ) from = 0; + if ( to === void 0 ) to = this.maps.length; + + return new Mapping(this.maps, this.mirror, from, to) + }; + + Mapping.prototype.copy = function copy () { + return new Mapping(this.maps.slice(), this.mirror && this.mirror.slice(), this.from, this.to) + }; + + // :: (StepMap, ?number) + // Add a step map to the end of this mapping. If `mirrors` is + // given, it should be the index of the step map that is the mirror + // image of this one. + Mapping.prototype.appendMap = function appendMap (map, mirrors) { + this.to = this.maps.push(map); + if (mirrors != null) { this.setMirror(this.maps.length - 1, mirrors); } + }; + + // :: (Mapping) + // Add all the step maps in a given mapping to this one (preserving + // mirroring information). + Mapping.prototype.appendMapping = function appendMapping (mapping) { + for (var i = 0, startSize = this.maps.length; i < mapping.maps.length; i++) { + var mirr = mapping.getMirror(i); + this.appendMap(mapping.maps[i], mirr != null && mirr < i ? startSize + mirr : null); + } + }; + + // :: (number) → ?number + // Finds the offset of the step map that mirrors the map at the + // given offset, in this mapping (as per the second argument to + // `appendMap`). + Mapping.prototype.getMirror = function getMirror (n) { + if (this.mirror) { for (var i = 0; i < this.mirror.length; i++) + { if (this.mirror[i] == n) { return this.mirror[i + (i % 2 ? -1 : 1)] } } } + }; + + Mapping.prototype.setMirror = function setMirror (n, m) { + if (!this.mirror) { this.mirror = []; } + this.mirror.push(n, m); + }; + + // :: (Mapping) + // Append the inverse of the given mapping to this one. + Mapping.prototype.appendMappingInverted = function appendMappingInverted (mapping) { + for (var i = mapping.maps.length - 1, totalSize = this.maps.length + mapping.maps.length; i >= 0; i--) { + var mirr = mapping.getMirror(i); + this.appendMap(mapping.maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : null); + } + }; + + // :: () → Mapping + // Create an inverted version of this mapping. + Mapping.prototype.invert = function invert () { + var inverse = new Mapping; + inverse.appendMappingInverted(this); + return inverse + }; + + // : (number, ?number) → number + // Map a position through this mapping. + Mapping.prototype.map = function map (pos, assoc) { + if ( assoc === void 0 ) assoc = 1; + + if (this.mirror) { return this._map(pos, assoc, true) } + for (var i = this.from; i < this.to; i++) + { pos = this.maps[i].map(pos, assoc); } + return pos + }; + + // : (number, ?number) → MapResult + // Map a position through this mapping, returning a mapping + // result. + Mapping.prototype.mapResult = function mapResult (pos, assoc) { + if ( assoc === void 0 ) assoc = 1; + return this._map(pos, assoc, false) }; + + Mapping.prototype._map = function _map (pos, assoc, simple) { + var deleted = false; + + for (var i = this.from; i < this.to; i++) { + var map = this.maps[i], result = map.mapResult(pos, assoc); + if (result.recover != null) { + var corr = this.getMirror(i); + if (corr != null && corr > i && corr < this.to) { + i = corr; + pos = this.maps[corr].recover(result.recover); + continue + } + } + + if (result.deleted) { deleted = true; } + pos = result.pos; + } + + return simple ? pos : new MapResult(pos, deleted) + }; + + function TransformError(message) { + var err = Error.call(this, message); + err.__proto__ = TransformError.prototype; + return err + } + + TransformError.prototype = Object.create(Error.prototype); + TransformError.prototype.constructor = TransformError; + TransformError.prototype.name = "TransformError"; + + // ::- Abstraction to build up and track an array of + // [steps](#transform.Step) representing a document transformation. + // + // Most transforming methods return the `Transform` object itself, so + // that they can be chained. + var Transform = function Transform(doc) { + // :: Node + // The current document (the result of applying the steps in the + // transform). + this.doc = doc; + // :: [Step] + // The steps in this transform. + this.steps = []; + // :: [Node] + // The documents before each of the steps. + this.docs = []; + // :: Mapping + // A mapping with the maps for each of the steps in this transform. + this.mapping = new Mapping; + }; + + var prototypeAccessors$7 = { before: { configurable: true },docChanged: { configurable: true } }; + + // :: Node The starting document. + prototypeAccessors$7.before.get = function () { return this.docs.length ? this.docs[0] : this.doc }; + + // :: (step: Step) → this + // Apply a new step in this transform, saving the result. Throws an + // error when the step fails. + Transform.prototype.step = function step (object) { + var result = this.maybeStep(object); + if (result.failed) { throw new TransformError(result.failed) } + return this + }; + + // :: (Step) → StepResult + // Try to apply a step in this transformation, ignoring it if it + // fails. Returns the step result. + Transform.prototype.maybeStep = function maybeStep (step) { + var result = step.apply(this.doc); + if (!result.failed) { this.addStep(step, result.doc); } + return result + }; + + // :: bool + // True when the document has been changed (when there are any + // steps). + prototypeAccessors$7.docChanged.get = function () { + return this.steps.length > 0 + }; + + Transform.prototype.addStep = function addStep (step, doc) { + this.docs.push(this.doc); + this.steps.push(step); + this.mapping.appendMap(step.getMap()); + this.doc = doc; + }; + + Object.defineProperties( Transform.prototype, prototypeAccessors$7 ); + + function mustOverride() { throw new Error("Override me") } + + var stepsByID = Object.create(null); + + // ::- A step object represents an atomic change. It generally applies + // only to the document it was created for, since the positions + // stored in it will only make sense for that document. + // + // New steps are defined by creating classes that extend `Step`, + // overriding the `apply`, `invert`, `map`, `getMap` and `fromJSON` + // methods, and registering your class with a unique + // JSON-serialization identifier using + // [`Step.jsonID`](#transform.Step^jsonID). + var Step = function Step () {}; + + Step.prototype.apply = function apply (_doc) { return mustOverride() }; + + // :: () → StepMap + // Get the step map that represents the changes made by this step, + // and which can be used to transform between positions in the old + // and the new document. + Step.prototype.getMap = function getMap () { return StepMap.empty }; + + // :: (doc: Node) → Step + // Create an inverted version of this step. Needs the document as it + // was before the step as argument. + Step.prototype.invert = function invert (_doc) { return mustOverride() }; + + // :: (mapping: Mappable) → ?Step + // Map this step through a mappable thing, returning either a + // version of that step with its positions adjusted, or `null` if + // the step was entirely deleted by the mapping. + Step.prototype.map = function map (_mapping) { return mustOverride() }; + + // :: (other: Step) → ?Step + // Try to merge this step with another one, to be applied directly + // after it. Returns the merged step when possible, null if the + // steps can't be merged. + Step.prototype.merge = function merge (_other) { return null }; + + // :: () → Object + // Create a JSON-serializeable representation of this step. When + // defining this for a custom subclass, make sure the result object + // includes the step type's [JSON id](#transform.Step^jsonID) under + // the `stepType` property. + Step.prototype.toJSON = function toJSON () { return mustOverride() }; + + // :: (Schema, Object) → Step + // Deserialize a step from its JSON representation. Will call + // through to the step class' own implementation of this method. + Step.fromJSON = function fromJSON (schema, json) { + if (!json || !json.stepType) { throw new RangeError("Invalid input for Step.fromJSON") } + var type = stepsByID[json.stepType]; + if (!type) { throw new RangeError(("No step type " + (json.stepType) + " defined")) } + return type.fromJSON(schema, json) + }; + + // :: (string, constructor) + // To be able to serialize steps to JSON, each step needs a string + // ID to attach to its JSON representation. Use this method to + // register an ID for your step classes. Try to pick something + // that's unlikely to clash with steps from other modules. + Step.jsonID = function jsonID (id, stepClass) { + if (id in stepsByID) { throw new RangeError("Duplicate use of step JSON ID " + id) } + stepsByID[id] = stepClass; + stepClass.prototype.jsonID = id; + return stepClass + }; + + // ::- The result of [applying](#transform.Step.apply) a step. Contains either a + // new document or a failure value. + var StepResult = function StepResult(doc, failed) { + // :: ?Node The transformed document. + this.doc = doc; + // :: ?string Text providing information about a failed step. + this.failed = failed; + }; + + // :: (Node) → StepResult + // Create a successful step result. + StepResult.ok = function ok (doc) { return new StepResult(doc, null) }; + + // :: (string) → StepResult + // Create a failed step result. + StepResult.fail = function fail (message) { return new StepResult(null, message) }; + + // :: (Node, number, number, Slice) → StepResult + // Call [`Node.replace`](#model.Node.replace) with the given + // arguments. Create a successful result if it succeeds, and a + // failed one if it throws a `ReplaceError`. + StepResult.fromReplace = function fromReplace (doc, from, to, slice) { + try { + return StepResult.ok(doc.replace(from, to, slice)) + } catch (e) { + if (e instanceof ReplaceError) { return StepResult.fail(e.message) } + throw e + } + }; + + // ::- Replace a part of the document with a slice of new content. + var ReplaceStep = /*@__PURE__*/(function (Step) { + function ReplaceStep(from, to, slice, structure) { + Step.call(this); + this.from = from; + this.to = to; + this.slice = slice; + this.structure = !!structure; + } + + if ( Step ) ReplaceStep.__proto__ = Step; + ReplaceStep.prototype = Object.create( Step && Step.prototype ); + ReplaceStep.prototype.constructor = ReplaceStep; + + ReplaceStep.prototype.apply = function apply (doc) { + if (this.structure && contentBetween(doc, this.from, this.to)) + { return StepResult.fail("Structure replace would overwrite content") } + return StepResult.fromReplace(doc, this.from, this.to, this.slice) + }; + + ReplaceStep.prototype.getMap = function getMap () { + return new StepMap([this.from, this.to - this.from, this.slice.size]) + }; + + ReplaceStep.prototype.invert = function invert (doc) { + return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to)) + }; + + ReplaceStep.prototype.map = function map (mapping) { + var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); + if (from.deleted && to.deleted) { return null } + return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice) + }; + + ReplaceStep.prototype.merge = function merge (other) { + if (!(other instanceof ReplaceStep) || other.structure != this.structure) { return null } + + if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) { + var slice = this.slice.size + other.slice.size == 0 ? Slice.empty + : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd); + return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure) + } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) { + var slice$1 = this.slice.size + other.slice.size == 0 ? Slice.empty + : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd); + return new ReplaceStep(other.from, this.to, slice$1, this.structure) + } else { + return null + } + }; + + ReplaceStep.prototype.toJSON = function toJSON () { + var json = {stepType: "replace", from: this.from, to: this.to}; + if (this.slice.size) { json.slice = this.slice.toJSON(); } + if (this.structure) { json.structure = true; } + return json + }; + + ReplaceStep.fromJSON = function fromJSON (schema, json) { + if (typeof json.from != "number" || typeof json.to != "number") + { throw new RangeError("Invalid input for ReplaceStep.fromJSON") } + return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure) + }; + + return ReplaceStep; + }(Step)); + + Step.jsonID("replace", ReplaceStep); + + // ::- Replace a part of the document with a slice of content, but + // preserve a range of the replaced content by moving it into the + // slice. + var ReplaceAroundStep = /*@__PURE__*/(function (Step) { + function ReplaceAroundStep(from, to, gapFrom, gapTo, slice, insert, structure) { + Step.call(this); + this.from = from; + this.to = to; + this.gapFrom = gapFrom; + this.gapTo = gapTo; + this.slice = slice; + this.insert = insert; + this.structure = !!structure; + } + + if ( Step ) ReplaceAroundStep.__proto__ = Step; + ReplaceAroundStep.prototype = Object.create( Step && Step.prototype ); + ReplaceAroundStep.prototype.constructor = ReplaceAroundStep; + + ReplaceAroundStep.prototype.apply = function apply (doc) { + if (this.structure && (contentBetween(doc, this.from, this.gapFrom) || + contentBetween(doc, this.gapTo, this.to))) + { return StepResult.fail("Structure gap-replace would overwrite content") } + + var gap = doc.slice(this.gapFrom, this.gapTo); + if (gap.openStart || gap.openEnd) + { return StepResult.fail("Gap is not a flat range") } + var inserted = this.slice.insertAt(this.insert, gap.content); + if (!inserted) { return StepResult.fail("Content does not fit in gap") } + return StepResult.fromReplace(doc, this.from, this.to, inserted) + }; + + ReplaceAroundStep.prototype.getMap = function getMap () { + return new StepMap([this.from, this.gapFrom - this.from, this.insert, + this.gapTo, this.to - this.gapTo, this.slice.size - this.insert]) + }; + + ReplaceAroundStep.prototype.invert = function invert (doc) { + var gap = this.gapTo - this.gapFrom; + return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, + this.from + this.insert, this.from + this.insert + gap, + doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), + this.gapFrom - this.from, this.structure) + }; + + ReplaceAroundStep.prototype.map = function map (mapping) { + var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); + var gapFrom = mapping.map(this.gapFrom, -1), gapTo = mapping.map(this.gapTo, 1); + if ((from.deleted && to.deleted) || gapFrom < from.pos || gapTo > to.pos) { return null } + return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure) + }; + + ReplaceAroundStep.prototype.toJSON = function toJSON () { + var json = {stepType: "replaceAround", from: this.from, to: this.to, + gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert}; + if (this.slice.size) { json.slice = this.slice.toJSON(); } + if (this.structure) { json.structure = true; } + return json + }; + + ReplaceAroundStep.fromJSON = function fromJSON (schema, json) { + if (typeof json.from != "number" || typeof json.to != "number" || + typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number") + { throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON") } + return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, + Slice.fromJSON(schema, json.slice), json.insert, !!json.structure) + }; + + return ReplaceAroundStep; + }(Step)); + + Step.jsonID("replaceAround", ReplaceAroundStep); + + function contentBetween(doc, from, to) { + var $from = doc.resolve(from), dist = to - from, depth = $from.depth; + while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) { + depth--; + dist--; + } + if (dist > 0) { + var next = $from.node(depth).maybeChild($from.indexAfter(depth)); + while (dist > 0) { + if (!next || next.isLeaf) { return true } + next = next.firstChild; + dist--; + } + } + return false + } + + // :: (NodeRange, number) → this + // Split the content in the given range off from its parent, if there + // is sibling content before or after it, and move it up the tree to + // the depth specified by `target`. You'll probably want to use + // [`liftTarget`](#transform.liftTarget) to compute `target`, to make + // sure the lift is valid. + Transform.prototype.lift = function(range, target) { + var $from = range.$from; + var $to = range.$to; + var depth = range.depth; + + var gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1); + var start = gapStart, end = gapEnd; + + var before = Fragment.empty, openStart = 0; + for (var d = depth, splitting = false; d > target; d--) + { if (splitting || $from.index(d) > 0) { + splitting = true; + before = Fragment.from($from.node(d).copy(before)); + openStart++; + } else { + start--; + } } + var after = Fragment.empty, openEnd = 0; + for (var d$1 = depth, splitting$1 = false; d$1 > target; d$1--) + { if (splitting$1 || $to.after(d$1 + 1) < $to.end(d$1)) { + splitting$1 = true; + after = Fragment.from($to.node(d$1).copy(after)); + openEnd++; + } else { + end++; + } } + + return this.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, + new Slice(before.append(after), openStart, openEnd), + before.size - openStart, true)) + }; + + // :: (NodeRange, NodeType, ?Object, ?NodeRange) → ?[{type: NodeType, attrs: ?Object}] + // Try to find a valid way to wrap the content in the given range in a + // node of the given type. May introduce extra nodes around and inside + // the wrapper node, if necessary. Returns null if no valid wrapping + // could be found. When `innerRange` is given, that range's content is + // used as the content to fit into the wrapping, instead of the + // content of `range`. + function findWrapping(range, nodeType, attrs, innerRange) { + if ( innerRange === void 0 ) innerRange = range; + + var around = findWrappingOutside(range, nodeType); + var inner = around && findWrappingInside(innerRange, nodeType); + if (!inner) { return null } + return around.map(withAttrs).concat({type: nodeType, attrs: attrs}).concat(inner.map(withAttrs)) + } + + function withAttrs(type) { return {type: type, attrs: null} } + + function findWrappingOutside(range, type) { + var parent = range.parent; + var startIndex = range.startIndex; + var endIndex = range.endIndex; + var around = parent.contentMatchAt(startIndex).findWrapping(type); + if (!around) { return null } + var outer = around.length ? around[0] : type; + return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null + } + + function findWrappingInside(range, type) { + var parent = range.parent; + var startIndex = range.startIndex; + var endIndex = range.endIndex; + var inner = parent.child(startIndex); + var inside = type.contentMatch.findWrapping(inner.type); + if (!inside) { return null } + var lastType = inside.length ? inside[inside.length - 1] : type; + var innerMatch = lastType.contentMatch; + for (var i = startIndex; innerMatch && i < endIndex; i++) + { innerMatch = innerMatch.matchType(parent.child(i).type); } + if (!innerMatch || !innerMatch.validEnd) { return null } + return inside + } + + // :: (NodeRange, [{type: NodeType, attrs: ?Object}]) → this + // Wrap the given [range](#model.NodeRange) in the given set of wrappers. + // The wrappers are assumed to be valid in this position, and should + // probably be computed with [`findWrapping`](#transform.findWrapping). + Transform.prototype.wrap = function(range, wrappers) { + var content = Fragment.empty; + for (var i = wrappers.length - 1; i >= 0; i--) + { content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content)); } + + var start = range.start, end = range.end; + return this.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true)) + }; + + // :: (number, ?number, NodeType, ?Object) → this + // Set the type of all textblocks (partly) between `from` and `to` to + // the given node type with the given attributes. + Transform.prototype.setBlockType = function(from, to, type, attrs) { + var this$1 = this; + if ( to === void 0 ) to = from; + + if (!type.isTextblock) { throw new RangeError("Type given to setBlockType should be a textblock") } + var mapFrom = this.steps.length; + this.doc.nodesBetween(from, to, function (node, pos) { + if (node.isTextblock && !node.hasMarkup(type, attrs) && canChangeType(this$1.doc, this$1.mapping.slice(mapFrom).map(pos), type)) { + // Ensure all markup that isn't allowed in the new node type is cleared + this$1.clearIncompatible(this$1.mapping.slice(mapFrom).map(pos, 1), type); + var mapping = this$1.mapping.slice(mapFrom); + var startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1); + this$1.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, + new Slice(Fragment.from(type.create(attrs, null, node.marks)), 0, 0), 1, true)); + return false + } + }); + return this + }; + + function canChangeType(doc, pos, type) { + var $pos = doc.resolve(pos), index = $pos.index(); + return $pos.parent.canReplaceWith(index, index + 1, type) + } + + // :: (number, ?NodeType, ?Object, ?[Mark]) → this + // Change the type, attributes, and/or marks of the node at `pos`. + // When `type` isn't given, the existing node type is preserved, + Transform.prototype.setNodeMarkup = function(pos, type, attrs, marks) { + var node = this.doc.nodeAt(pos); + if (!node) { throw new RangeError("No node at given position") } + if (!type) { type = node.type; } + var newNode = type.create(attrs, null, marks || node.marks); + if (node.isLeaf) + { return this.replaceWith(pos, pos + node.nodeSize, newNode) } + + if (!type.validContent(node.content)) + { throw new RangeError("Invalid content for node type " + type.name) } + + return this.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, + new Slice(Fragment.from(newNode), 0, 0), 1, true)) + }; + + // :: (number, ?number, ?[?{type: NodeType, attrs: ?Object}]) → this + // Split the node at the given position, and optionally, if `depth` is + // greater than one, any number of nodes above that. By default, the + // parts split off will inherit the node type of the original node. + // This can be changed by passing an array of types and attributes to + // use after the split. + Transform.prototype.split = function(pos, depth, typesAfter) { + if ( depth === void 0 ) depth = 1; + + var $pos = this.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty; + for (var d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) { + before = Fragment.from($pos.node(d).copy(before)); + var typeAfter = typesAfter && typesAfter[i]; + after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after)); + } + return this.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true)) + }; + + // :: (number, ?number) → this + // Join the blocks around the given position. If depth is 2, their + // last and first siblings are also joined, and so on. + Transform.prototype.join = function(pos, depth) { + if ( depth === void 0 ) depth = 1; + + var step = new ReplaceStep(pos - depth, pos + depth, Slice.empty, true); + return this.step(step) + }; + + // :: (Node, number, NodeType) → ?number + // Try to find a point where a node of the given type can be inserted + // near `pos`, by searching up the node hierarchy when `pos` itself + // isn't a valid place but is at the start or end of a node. Return + // null if no position was found. + function insertPoint(doc, pos, nodeType) { + var $pos = doc.resolve(pos); + if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType)) { return pos } + + if ($pos.parentOffset == 0) + { for (var d = $pos.depth - 1; d >= 0; d--) { + var index = $pos.index(d); + if ($pos.node(d).canReplaceWith(index, index, nodeType)) { return $pos.before(d + 1) } + if (index > 0) { return null } + } } + if ($pos.parentOffset == $pos.parent.content.size) + { for (var d$1 = $pos.depth - 1; d$1 >= 0; d$1--) { + var index$1 = $pos.indexAfter(d$1); + if ($pos.node(d$1).canReplaceWith(index$1, index$1, nodeType)) { return $pos.after(d$1 + 1) } + if (index$1 < $pos.node(d$1).childCount) { return null } + } } + } + + // :: (Node, number, Slice) → ?number + // Finds a position at or around the given position where the given + // slice can be inserted. Will look at parent nodes' nearest boundary + // and try there, even if the original position wasn't directly at the + // start or end of that node. Returns null when no position was found. + function dropPoint(doc, pos, slice) { + var $pos = doc.resolve(pos); + if (!slice.content.size) { return pos } + var content = slice.content; + for (var i = 0; i < slice.openStart; i++) { content = content.firstChild.content; } + for (var pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) { + for (var d = $pos.depth; d >= 0; d--) { + var bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1; + var insertPos = $pos.index(d) + (bias > 0 ? 1 : 0); + if (pass == 1 + ? $pos.node(d).canReplace(insertPos, insertPos, content) + : $pos.node(d).contentMatchAt(insertPos).findWrapping(content.firstChild.type)) + { return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1) } + } + } + return null + } + + function mapFragment(fragment, f, parent) { + var mapped = []; + for (var i = 0; i < fragment.childCount; i++) { + var child = fragment.child(i); + if (child.content.size) { child = child.copy(mapFragment(child.content, f, child)); } + if (child.isInline) { child = f(child, parent, i); } + mapped.push(child); + } + return Fragment.fromArray(mapped) + } + + // ::- Add a mark to all inline content between two positions. + var AddMarkStep = /*@__PURE__*/(function (Step) { + function AddMarkStep(from, to, mark) { + Step.call(this); + this.from = from; + this.to = to; + this.mark = mark; + } + + if ( Step ) AddMarkStep.__proto__ = Step; + AddMarkStep.prototype = Object.create( Step && Step.prototype ); + AddMarkStep.prototype.constructor = AddMarkStep; + + AddMarkStep.prototype.apply = function apply (doc) { + var this$1 = this; + + var oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from); + var parent = $from.node($from.sharedDepth(this.to)); + var slice = new Slice(mapFragment(oldSlice.content, function (node, parent) { + if (!parent.type.allowsMarkType(this$1.mark.type)) { return node } + return node.mark(this$1.mark.addToSet(node.marks)) + }, parent), oldSlice.openStart, oldSlice.openEnd); + return StepResult.fromReplace(doc, this.from, this.to, slice) + }; + + AddMarkStep.prototype.invert = function invert () { + return new RemoveMarkStep(this.from, this.to, this.mark) + }; + + AddMarkStep.prototype.map = function map (mapping) { + var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); + if (from.deleted && to.deleted || from.pos >= to.pos) { return null } + return new AddMarkStep(from.pos, to.pos, this.mark) + }; + + AddMarkStep.prototype.merge = function merge (other) { + if (other instanceof AddMarkStep && + other.mark.eq(this.mark) && + this.from <= other.to && this.to >= other.from) + { return new AddMarkStep(Math.min(this.from, other.from), + Math.max(this.to, other.to), this.mark) } + }; + + AddMarkStep.prototype.toJSON = function toJSON () { + return {stepType: "addMark", mark: this.mark.toJSON(), + from: this.from, to: this.to} + }; + + AddMarkStep.fromJSON = function fromJSON (schema, json) { + if (typeof json.from != "number" || typeof json.to != "number") + { throw new RangeError("Invalid input for AddMarkStep.fromJSON") } + return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark)) + }; + + return AddMarkStep; + }(Step)); + + Step.jsonID("addMark", AddMarkStep); + + // ::- Remove a mark from all inline content between two positions. + var RemoveMarkStep = /*@__PURE__*/(function (Step) { + function RemoveMarkStep(from, to, mark) { + Step.call(this); + this.from = from; + this.to = to; + this.mark = mark; + } + + if ( Step ) RemoveMarkStep.__proto__ = Step; + RemoveMarkStep.prototype = Object.create( Step && Step.prototype ); + RemoveMarkStep.prototype.constructor = RemoveMarkStep; + + RemoveMarkStep.prototype.apply = function apply (doc) { + var this$1 = this; + + var oldSlice = doc.slice(this.from, this.to); + var slice = new Slice(mapFragment(oldSlice.content, function (node) { + return node.mark(this$1.mark.removeFromSet(node.marks)) + }), oldSlice.openStart, oldSlice.openEnd); + return StepResult.fromReplace(doc, this.from, this.to, slice) + }; + + RemoveMarkStep.prototype.invert = function invert () { + return new AddMarkStep(this.from, this.to, this.mark) + }; + + RemoveMarkStep.prototype.map = function map (mapping) { + var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); + if (from.deleted && to.deleted || from.pos >= to.pos) { return null } + return new RemoveMarkStep(from.pos, to.pos, this.mark) + }; + + RemoveMarkStep.prototype.merge = function merge (other) { + if (other instanceof RemoveMarkStep && + other.mark.eq(this.mark) && + this.from <= other.to && this.to >= other.from) + { return new RemoveMarkStep(Math.min(this.from, other.from), + Math.max(this.to, other.to), this.mark) } + }; + + RemoveMarkStep.prototype.toJSON = function toJSON () { + return {stepType: "removeMark", mark: this.mark.toJSON(), + from: this.from, to: this.to} + }; + + RemoveMarkStep.fromJSON = function fromJSON (schema, json) { + if (typeof json.from != "number" || typeof json.to != "number") + { throw new RangeError("Invalid input for RemoveMarkStep.fromJSON") } + return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark)) + }; + + return RemoveMarkStep; + }(Step)); + + Step.jsonID("removeMark", RemoveMarkStep); + + // :: (number, number, Mark) → this + // Add the given mark to the inline content between `from` and `to`. + Transform.prototype.addMark = function(from, to, mark) { + var this$1 = this; + + var removed = [], added = [], removing = null, adding = null; + this.doc.nodesBetween(from, to, function (node, pos, parent) { + if (!node.isInline) { return } + var marks = node.marks; + if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) { + var start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to); + var newSet = mark.addToSet(marks); + + for (var i = 0; i < marks.length; i++) { + if (!marks[i].isInSet(newSet)) { + if (removing && removing.to == start && removing.mark.eq(marks[i])) + { removing.to = end; } + else + { removed.push(removing = new RemoveMarkStep(start, end, marks[i])); } + } + } + + if (adding && adding.to == start) + { adding.to = end; } + else + { added.push(adding = new AddMarkStep(start, end, mark)); } + } + }); + + removed.forEach(function (s) { return this$1.step(s); }); + added.forEach(function (s) { return this$1.step(s); }); + return this + }; + + // :: (number, number, ?union) → this + // Remove marks from inline nodes between `from` and `to`. When `mark` + // is a single mark, remove precisely that mark. When it is a mark type, + // remove all marks of that type. When it is null, remove all marks of + // any type. + Transform.prototype.removeMark = function(from, to, mark) { + var this$1 = this; + if ( mark === void 0 ) mark = null; + + var matched = [], step = 0; + this.doc.nodesBetween(from, to, function (node, pos) { + if (!node.isInline) { return } + step++; + var toRemove = null; + if (mark instanceof MarkType) { + var found = mark.isInSet(node.marks); + if (found) { toRemove = [found]; } + } else if (mark) { + if (mark.isInSet(node.marks)) { toRemove = [mark]; } + } else { + toRemove = node.marks; + } + if (toRemove && toRemove.length) { + var end = Math.min(pos + node.nodeSize, to); + for (var i = 0; i < toRemove.length; i++) { + var style = toRemove[i], found$1 = (void 0); + for (var j = 0; j < matched.length; j++) { + var m = matched[j]; + if (m.step == step - 1 && style.eq(matched[j].style)) { found$1 = m; } + } + if (found$1) { + found$1.to = end; + found$1.step = step; + } else { + matched.push({style: style, from: Math.max(pos, from), to: end, step: step}); + } + } + } + }); + matched.forEach(function (m) { return this$1.step(new RemoveMarkStep(m.from, m.to, m.style)); }); + return this + }; + + // :: (number, NodeType, ?ContentMatch) → this + // Removes all marks and nodes from the content of the node at `pos` + // that don't match the given new parent node type. Accepts an + // optional starting [content match](#model.ContentMatch) as third + // argument. + Transform.prototype.clearIncompatible = function(pos, parentType, match) { + if ( match === void 0 ) match = parentType.contentMatch; + + var node = this.doc.nodeAt(pos); + var delSteps = [], cur = pos + 1; + for (var i = 0; i < node.childCount; i++) { + var child = node.child(i), end = cur + child.nodeSize; + var allowed = match.matchType(child.type, child.attrs); + if (!allowed) { + delSteps.push(new ReplaceStep(cur, end, Slice.empty)); + } else { + match = allowed; + for (var j = 0; j < child.marks.length; j++) { if (!parentType.allowsMarkType(child.marks[j].type)) + { this.step(new RemoveMarkStep(cur, end, child.marks[j])); } } + } + cur = end; + } + if (!match.validEnd) { + var fill = match.fillBefore(Fragment.empty, true); + this.replace(cur, cur, new Slice(fill, 0, 0)); + } + for (var i$1 = delSteps.length - 1; i$1 >= 0; i$1--) { this.step(delSteps[i$1]); } + return this + }; + + // :: (Node, number, ?number, ?Slice) → ?Step + // ‘Fit’ a slice into a given position in the document, producing a + // [step](#transform.Step) that inserts it. Will return null if + // there's no meaningful way to insert the slice here, or inserting it + // would be a no-op (an empty slice over an empty range). + function replaceStep(doc, from, to, slice) { + if ( to === void 0 ) to = from; + if ( slice === void 0 ) slice = Slice.empty; + + if (from == to && !slice.size) { return null } + + var $from = doc.resolve(from), $to = doc.resolve(to); + // Optimization -- avoid work if it's obvious that it's not needed. + if (fitsTrivially($from, $to, slice)) { return new ReplaceStep(from, to, slice) } + return new Fitter($from, $to, slice).fit() + } + + // :: (number, ?number, ?Slice) → this + // Replace the part of the document between `from` and `to` with the + // given `slice`. + Transform.prototype.replace = function(from, to, slice) { + if ( to === void 0 ) to = from; + if ( slice === void 0 ) slice = Slice.empty; + + var step = replaceStep(this.doc, from, to, slice); + if (step) { this.step(step); } + return this + }; + + // :: (number, number, union) → this + // Replace the given range with the given content, which may be a + // fragment, node, or array of nodes. + Transform.prototype.replaceWith = function(from, to, content) { + return this.replace(from, to, new Slice(Fragment.from(content), 0, 0)) + }; + + // :: (number, number) → this + // Delete the content between the given positions. + Transform.prototype.delete = function(from, to) { + return this.replace(from, to, Slice.empty) + }; + + // :: (number, union) → this + // Insert the given content at the given position. + Transform.prototype.insert = function(pos, content) { + return this.replaceWith(pos, pos, content) + }; + + function fitsTrivially($from, $to, slice) { + return !slice.openStart && !slice.openEnd && $from.start() == $to.start() && + $from.parent.canReplace($from.index(), $to.index(), slice.content) + } + + // Algorithm for 'placing' the elements of a slice into a gap: + // + // We consider the content of each node that is open to the left to be + // independently placeable. I.e. in , when the + // paragraph on the left is open, "foo" can be placed (somewhere on + // the left side of the replacement gap) independently from p("bar"). + // + // This class tracks the state of the placement progress in the + // following properties: + // + // - `frontier` holds a stack of `{type, match}` objects that + // represent the open side of the replacement. It starts at + // `$from`, then moves forward as content is placed, and is finally + // reconciled with `$to`. + // + // - `unplaced` is a slice that represents the content that hasn't + // been placed yet. + // + // - `placed` is a fragment of placed content. Its open-start value + // is implicit in `$from`, and its open-end value in `frontier`. + var Fitter = function Fitter($from, $to, slice) { + this.$to = $to; + this.$from = $from; + this.unplaced = slice; + + this.frontier = []; + for (var i = 0; i <= $from.depth; i++) { + var node = $from.node(i); + this.frontier.push({ + type: node.type, + match: node.contentMatchAt($from.indexAfter(i)) + }); + } + + this.placed = Fragment.empty; + for (var i$1 = $from.depth; i$1 > 0; i$1--) + { this.placed = Fragment.from($from.node(i$1).copy(this.placed)); } + }; + + var prototypeAccessors$1$4 = { depth: { configurable: true } }; + + prototypeAccessors$1$4.depth.get = function () { return this.frontier.length - 1 }; + + Fitter.prototype.fit = function fit () { + // As long as there's unplaced content, try to place some of it. + // If that fails, either increase the open score of the unplaced + // slice, or drop nodes from it, and then try again. + while (this.unplaced.size) { + var fit = this.findFittable(); + if (fit) { this.placeNodes(fit); } + else { this.openMore() || this.dropNode(); } + } + // When there's inline content directly after the frontier _and_ + // directly after `this.$to`, we must generate a `ReplaceAround` + // step that pulls that content into the node after the frontier. + // That means the fitting must be done to the end of the textblock + // node after `this.$to`, not `this.$to` itself. + var moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth; + var $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline)); + if (!$to) { return null } + + // If closing to `$to` succeeded, create a step + var content = this.placed, openStart = $from.depth, openEnd = $to.depth; + while (openStart && openEnd && content.childCount == 1) { // Normalize by dropping open parent nodes + content = content.firstChild.content; + openStart--; openEnd--; + } + var slice = new Slice(content, openStart, openEnd); + if (moveInline > -1) + { return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize) } + if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps + { return new ReplaceStep($from.pos, $to.pos, slice) } + }; + + // Find a position on the start spine of `this.unplaced` that has + // content that can be moved somewhere on the frontier. Returns two + // depths, one for the slice and one for the frontier. + Fitter.prototype.findFittable = function findFittable () { + // Only try wrapping nodes (pass 2) after finding a place without + // wrapping failed. + for (var pass = 1; pass <= 2; pass++) { + for (var sliceDepth = this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) { + var fragment = (void 0), parent = (void 0); + if (sliceDepth) { + parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild; + fragment = parent.content; + } else { + fragment = this.unplaced.content; + } + var first = fragment.firstChild; + for (var frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) { + var ref = this.frontier[frontierDepth]; + var type = ref.type; + var match = ref.match; + var wrap = (void 0), inject = (void 0); + // In pass 1, if the next node matches, or there is no next + // node but the parents look compatible, we've found a + // place. + if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false)) + : type.compatibleContent(parent.type))) + { return {sliceDepth: sliceDepth, frontierDepth: frontierDepth, parent: parent, inject: inject} } + // In pass 2, look for a set of wrapping nodes that make + // `first` fit here. + else if (pass == 2 && first && (wrap = match.findWrapping(first.type))) + { return {sliceDepth: sliceDepth, frontierDepth: frontierDepth, parent: parent, wrap: wrap} } + // Don't continue looking further up if the parent node + // would fit here. + if (parent && match.matchType(parent.type)) { break } + } + } + } + }; + + Fitter.prototype.openMore = function openMore () { + var ref = this.unplaced; + var content = ref.content; + var openStart = ref.openStart; + var openEnd = ref.openEnd; + var inner = contentAt(content, openStart); + if (!inner.childCount || inner.firstChild.isLeaf) { return false } + this.unplaced = new Slice(content, openStart + 1, + Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0)); + return true + }; + + Fitter.prototype.dropNode = function dropNode () { + var ref = this.unplaced; + var content = ref.content; + var openStart = ref.openStart; + var openEnd = ref.openEnd; + var inner = contentAt(content, openStart); + if (inner.childCount <= 1 && openStart > 0) { + var openAtEnd = content.size - openStart <= openStart + inner.size; + this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, + openAtEnd ? openStart - 1 : openEnd); + } else { + this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd); + } + }; + + // : ({sliceDepth: number, frontierDepth: number, parent: ?Node, wrap: ?[NodeType], inject: ?Fragment}) + // Move content from the unplaced slice at `sliceDepth` to the + // frontier node at `frontierDepth`. Close that frontier node when + // applicable. + Fitter.prototype.placeNodes = function placeNodes (ref) { + var sliceDepth = ref.sliceDepth; + var frontierDepth = ref.frontierDepth; + var parent = ref.parent; + var inject = ref.inject; + var wrap = ref.wrap; + + while (this.depth > frontierDepth) { this.closeFrontierNode(); } + if (wrap) { for (var i = 0; i < wrap.length; i++) { this.openFrontierNode(wrap[i]); } } + + var slice = this.unplaced, fragment = parent ? parent.content : slice.content; + var openStart = slice.openStart - sliceDepth; + var taken = 0, add = []; + var ref$1 = this.frontier[frontierDepth]; + var match = ref$1.match; + var type = ref$1.type; + if (inject) { + for (var i$1 = 0; i$1 < inject.childCount; i$1++) { add.push(inject.child(i$1)); } + match = match.matchFragment(inject); + } + // Computes the amount of (end) open nodes at the end of the + // fragment. When 0, the parent is open, but no more. When + // negative, nothing is open. + var openEndCount = (fragment.size + sliceDepth) - (slice.content.size - slice.openEnd); + // Scan over the fragment, fitting as many child nodes as + // possible. + while (taken < fragment.childCount) { + var next = fragment.child(taken), matches = match.matchType(next.type); + if (!matches) { break } + taken++; + if (taken > 1 || openStart == 0 || next.content.size) { // Drop empty open nodes + match = matches; + add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, + taken == fragment.childCount ? openEndCount : -1)); + } + } + var toEnd = taken == fragment.childCount; + if (!toEnd) { openEndCount = -1; } + + this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add)); + this.frontier[frontierDepth].match = match; + + // If the parent types match, and the entire node was moved, and + // it's not open, close this frontier node right away. + if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type) { this.closeFrontierNode(); } + + // Add new frontier nodes for any open nodes at the end. + for (var i$2 = 0, cur = fragment; i$2 < openEndCount; i$2++) { + var node = cur.lastChild; + this.frontier.push({type: node.type, match: node.contentMatchAt(node.childCount)}); + cur = node.content; + } + + // Update `this.unplaced`. Drop the entire node from which we + // placed it we got to its end, otherwise just drop the placed + // nodes. + this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd) + : sliceDepth == 0 ? Slice.empty + : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), + sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1); + }; + + Fitter.prototype.mustMoveInline = function mustMoveInline () { + if (!this.$to.parent.isTextblock || this.$to.end() == this.$to.pos) { return -1 } + var top = this.frontier[this.depth], level; + if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) || + (this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth)) { return -1 } + + var ref = this.$to; + var depth = ref.depth; + var after = this.$to.after(depth); + while (depth > 1 && after == this.$to.end(--depth)) { ++after; } + return after + }; + + Fitter.prototype.findCloseLevel = function findCloseLevel ($to) { + scan: for (var i = Math.min(this.depth, $to.depth); i >= 0; i--) { + var ref = this.frontier[i]; + var match = ref.match; + var type = ref.type; + var dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1)); + var fit = contentAfterFits($to, i, type, match, dropInner); + if (!fit) { continue } + for (var d = i - 1; d >= 0; d--) { + var ref$1 = this.frontier[d]; + var match$1 = ref$1.match; + var type$1 = ref$1.type; + var matches = contentAfterFits($to, d, type$1, match$1, true); + if (!matches || matches.childCount) { continue scan } + } + return {depth: i, fit: fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to} + } + }; + + Fitter.prototype.close = function close ($to) { + var close = this.findCloseLevel($to); + if (!close) { return null } + + while (this.depth > close.depth) { this.closeFrontierNode(); } + if (close.fit.childCount) { this.placed = addToFragment(this.placed, close.depth, close.fit); } + $to = close.move; + for (var d = close.depth + 1; d <= $to.depth; d++) { + var node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d)); + this.openFrontierNode(node.type, node.attrs, add); + } + return $to + }; + + Fitter.prototype.openFrontierNode = function openFrontierNode (type, attrs, content) { + var top = this.frontier[this.depth]; + top.match = top.match.matchType(type); + this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content))); + this.frontier.push({type: type, match: type.contentMatch}); + }; + + Fitter.prototype.closeFrontierNode = function closeFrontierNode () { + var open = this.frontier.pop(); + var add = open.match.fillBefore(Fragment.empty, true); + if (add.childCount) { this.placed = addToFragment(this.placed, this.frontier.length, add); } + }; + + Object.defineProperties( Fitter.prototype, prototypeAccessors$1$4 ); + + function dropFromFragment(fragment, depth, count) { + if (depth == 0) { return fragment.cutByIndex(count) } + return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count))) + } + + function addToFragment(fragment, depth, content) { + if (depth == 0) { return fragment.append(content) } + return fragment.replaceChild(fragment.childCount - 1, + fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content))) + } + + function contentAt(fragment, depth) { + for (var i = 0; i < depth; i++) { fragment = fragment.firstChild.content; } + return fragment + } + + function closeNodeStart(node, openStart, openEnd) { + if (openStart <= 0) { return node } + var frag = node.content; + if (openStart > 1) + { frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0)); } + if (openStart > 0) { + frag = node.type.contentMatch.fillBefore(frag).append(frag); + if (openEnd <= 0) { frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true)); } + } + return node.copy(frag) + } + + function contentAfterFits($to, depth, type, match, open) { + var node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth); + if (index == node.childCount && !type.compatibleContent(node.type)) { return null } + var fit = match.fillBefore(node.content, true, index); + return fit && !invalidMarks(type, node.content, index) ? fit : null + } + + function invalidMarks(type, fragment, start) { + for (var i = start; i < fragment.childCount; i++) + { if (!type.allowsMarks(fragment.child(i).marks)) { return true } } + return false + } + + // :: (number, number, Slice) → this + // Replace a range of the document with a given slice, using `from`, + // `to`, and the slice's [`openStart`](#model.Slice.openStart) property + // as hints, rather than fixed start and end points. This method may + // grow the replaced area or close open nodes in the slice in order to + // get a fit that is more in line with WYSIWYG expectations, by + // dropping fully covered parent nodes of the replaced region when + // they are marked [non-defining](#model.NodeSpec.defining), or + // including an open parent node from the slice that _is_ marked as + // [defining](#model.NodeSpec.defining). + // + // This is the method, for example, to handle paste. The similar + // [`replace`](#transform.Transform.replace) method is a more + // primitive tool which will _not_ move the start and end of its given + // range, and is useful in situations where you need more precise + // control over what happens. + Transform.prototype.replaceRange = function(from, to, slice) { + if (!slice.size) { return this.deleteRange(from, to) } + + var $from = this.doc.resolve(from), $to = this.doc.resolve(to); + if (fitsTrivially($from, $to, slice)) + { return this.step(new ReplaceStep(from, to, slice)) } + + var targetDepths = coveredDepths($from, this.doc.resolve(to)); + // Can't replace the whole document, so remove 0 if it's present + if (targetDepths[targetDepths.length - 1] == 0) { targetDepths.pop(); } + // Negative numbers represent not expansion over the whole node at + // that depth, but replacing from $from.before(-D) to $to.pos. + var preferredTarget = -($from.depth + 1); + targetDepths.unshift(preferredTarget); + // This loop picks a preferred target depth, if one of the covering + // depths is not outside of a defining node, and adds negative + // depths for any depth that has $from at its start and does not + // cross a defining node. + for (var d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) { + var spec = $from.node(d).type.spec; + if (spec.defining || spec.isolating) { break } + if (targetDepths.indexOf(d) > -1) { preferredTarget = d; } + else if ($from.before(d) == pos) { targetDepths.splice(1, 0, -d); } + } + // Try to fit each possible depth of the slice into each possible + // target depth, starting with the preferred depths. + var preferredTargetIndex = targetDepths.indexOf(preferredTarget); + + var leftNodes = [], preferredDepth = slice.openStart; + for (var content = slice.content, i = 0;; i++) { + var node = content.firstChild; + leftNodes.push(node); + if (i == slice.openStart) { break } + content = node.content; + } + // Back up if the node directly above openStart, or the node above + // that separated only by a non-defining textblock node, is defining. + if (preferredDepth > 0 && leftNodes[preferredDepth - 1].type.spec.defining && + $from.node(preferredTargetIndex).type != leftNodes[preferredDepth - 1].type) + { preferredDepth -= 1; } + else if (preferredDepth >= 2 && leftNodes[preferredDepth - 1].isTextblock && leftNodes[preferredDepth - 2].type.spec.defining && + $from.node(preferredTargetIndex).type != leftNodes[preferredDepth - 2].type) + { preferredDepth -= 2; } + + for (var j = slice.openStart; j >= 0; j--) { + var openDepth = (j + preferredDepth + 1) % (slice.openStart + 1); + var insert = leftNodes[openDepth]; + if (!insert) { continue } + for (var i$1 = 0; i$1 < targetDepths.length; i$1++) { + // Loop over possible expansion levels, starting with the + // preferred one + var targetDepth = targetDepths[(i$1 + preferredTargetIndex) % targetDepths.length], expand = true; + if (targetDepth < 0) { expand = false; targetDepth = -targetDepth; } + var parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1); + if (parent.canReplaceWith(index, index, insert.type, insert.marks)) + { return this.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, + new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), + openDepth, slice.openEnd)) } + } + } + + var startSteps = this.steps.length; + for (var i$2 = targetDepths.length - 1; i$2 >= 0; i$2--) { + this.replace(from, to, slice); + if (this.steps.length > startSteps) { break } + var depth = targetDepths[i$2]; + if (i$2 < 0) { continue } + from = $from.before(depth); to = $to.after(depth); + } + return this + }; + + function closeFragment(fragment, depth, oldOpen, newOpen, parent) { + if (depth < oldOpen) { + var first = fragment.firstChild; + fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first))); + } + if (depth > newOpen) { + var match = parent.contentMatchAt(0); + var start = match.fillBefore(fragment).append(fragment); + fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true)); + } + return fragment + } + + // :: (number, number, Node) → this + // Replace the given range with a node, but use `from` and `to` as + // hints, rather than precise positions. When from and to are the same + // and are at the start or end of a parent node in which the given + // node doesn't fit, this method may _move_ them out towards a parent + // that does allow the given node to be placed. When the given range + // completely covers a parent node, this method may completely replace + // that parent node. + Transform.prototype.replaceRangeWith = function(from, to, node) { + if (!node.isInline && from == to && this.doc.resolve(from).parent.content.size) { + var point = insertPoint(this.doc, from, node.type); + if (point != null) { from = to = point; } + } + return this.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0)) + }; + + // :: (number, number) → this + // Delete the given range, expanding it to cover fully covered + // parent nodes until a valid replace is found. + Transform.prototype.deleteRange = function(from, to) { + var $from = this.doc.resolve(from), $to = this.doc.resolve(to); + var covered = coveredDepths($from, $to); + for (var i = 0; i < covered.length; i++) { + var depth = covered[i], last = i == covered.length - 1; + if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd) + { return this.delete($from.start(depth), $to.end(depth)) } + if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1)))) + { return this.delete($from.before(depth), $to.after(depth)) } + } + for (var d = 1; d <= $from.depth && d <= $to.depth; d++) { + if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d) + { return this.delete($from.before(d), to) } + } + return this.delete(from, to) + }; + + // : (ResolvedPos, ResolvedPos) → [number] + // Returns an array of all depths for which $from - $to spans the + // whole content of the nodes at that depth. + function coveredDepths($from, $to) { + var result = [], minDepth = Math.min($from.depth, $to.depth); + for (var d = minDepth; d >= 0; d--) { + var start = $from.start(d); + if (start < $from.pos - ($from.depth - d) || + $to.end(d) > $to.pos + ($to.depth - d) || + $from.node(d).type.spec.isolating || + $to.node(d).type.spec.isolating) { break } + if (start == $to.start(d)) { result.push(d); } + } + return result + } + + var classesById = Object.create(null); + + // ::- Superclass for editor selections. Every selection type should + // extend this. Should not be instantiated directly. + var Selection = function Selection($anchor, $head, ranges) { + // :: [SelectionRange] + // The ranges covered by the selection. + this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))]; + // :: ResolvedPos + // The resolved anchor of the selection (the side that stays in + // place when the selection is modified). + this.$anchor = $anchor; + // :: ResolvedPos + // The resolved head of the selection (the side that moves when + // the selection is modified). + this.$head = $head; + }; + + var prototypeAccessors$8 = { anchor: { configurable: true },head: { configurable: true },from: { configurable: true },to: { configurable: true },$from: { configurable: true },$to: { configurable: true },empty: { configurable: true } }; + + // :: number + // The selection's anchor, as an unresolved position. + prototypeAccessors$8.anchor.get = function () { return this.$anchor.pos }; + + // :: number + // The selection's head. + prototypeAccessors$8.head.get = function () { return this.$head.pos }; + + // :: number + // The lower bound of the selection's main range. + prototypeAccessors$8.from.get = function () { return this.$from.pos }; + + // :: number + // The upper bound of the selection's main range. + prototypeAccessors$8.to.get = function () { return this.$to.pos }; + + // :: ResolvedPos + // The resolved lowerbound of the selection's main range. + prototypeAccessors$8.$from.get = function () { + return this.ranges[0].$from + }; + + // :: ResolvedPos + // The resolved upper bound of the selection's main range. + prototypeAccessors$8.$to.get = function () { + return this.ranges[0].$to + }; + + // :: bool + // Indicates whether the selection contains any content. + prototypeAccessors$8.empty.get = function () { + var ranges = this.ranges; + for (var i = 0; i < ranges.length; i++) + { if (ranges[i].$from.pos != ranges[i].$to.pos) { return false } } + return true + }; + + // eq:: (Selection) → bool + // Test whether the selection is the same as another selection. + + // map:: (doc: Node, mapping: Mappable) → Selection + // Map this selection through a [mappable](#transform.Mappable) thing. `doc` + // should be the new document to which we are mapping. + + // :: () → Slice + // Get the content of this selection as a slice. + Selection.prototype.content = function content () { + return this.$from.node(0).slice(this.from, this.to, true) + }; + + // :: (Transaction, ?Slice) + // Replace the selection with a slice or, if no slice is given, + // delete the selection. Will append to the given transaction. + Selection.prototype.replace = function replace (tr, content) { + if ( content === void 0 ) content = Slice.empty; + + // Put the new selection at the position after the inserted + // content. When that ended in an inline node, search backwards, + // to get the position after that node. If not, search forward. + var lastNode = content.content.lastChild, lastParent = null; + for (var i = 0; i < content.openEnd; i++) { + lastParent = lastNode; + lastNode = lastNode.lastChild; + } + + var mapFrom = tr.steps.length, ranges = this.ranges; + for (var i$1 = 0; i$1 < ranges.length; i$1++) { + var ref = ranges[i$1]; + var $from = ref.$from; + var $to = ref.$to; + var mapping = tr.mapping.slice(mapFrom); + tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i$1 ? Slice.empty : content); + if (i$1 == 0) + { selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1); } + } + }; + + // :: (Transaction, Node) + // Replace the selection with the given node, appending the changes + // to the given transaction. + Selection.prototype.replaceWith = function replaceWith (tr, node) { + var mapFrom = tr.steps.length, ranges = this.ranges; + for (var i = 0; i < ranges.length; i++) { + var ref = ranges[i]; + var $from = ref.$from; + var $to = ref.$to; + var mapping = tr.mapping.slice(mapFrom); + var from = mapping.map($from.pos), to = mapping.map($to.pos); + if (i) { + tr.deleteRange(from, to); + } else { + tr.replaceRangeWith(from, to, node); + selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1); + } + } + }; + + // toJSON:: () → Object + // Convert the selection to a JSON representation. When implementing + // this for a custom selection class, make sure to give the object a + // `type` property whose value matches the ID under which you + // [registered](#state.Selection^jsonID) your class. + + // :: (ResolvedPos, number, ?bool) → ?Selection + // Find a valid cursor or leaf node selection starting at the given + // position and searching back if `dir` is negative, and forward if + // positive. When `textOnly` is true, only consider cursor + // selections. Will return null when no valid selection position is + // found. + Selection.findFrom = function findFrom ($pos, dir, textOnly) { + var inner = $pos.parent.inlineContent ? new TextSelection($pos) + : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly); + if (inner) { return inner } + + for (var depth = $pos.depth - 1; depth >= 0; depth--) { + var found = dir < 0 + ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly) + : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly); + if (found) { return found } + } + }; + + // :: (ResolvedPos, ?number) → Selection + // Find a valid cursor or leaf node selection near the given + // position. Searches forward first by default, but if `bias` is + // negative, it will search backwards first. + Selection.near = function near ($pos, bias) { + if ( bias === void 0 ) bias = 1; + + return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0)) + }; + + // :: (Node) → Selection + // Find the cursor or leaf node selection closest to the start of + // the given document. Will return an + // [`AllSelection`](#state.AllSelection) if no valid position + // exists. + Selection.atStart = function atStart (doc) { + return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc) + }; + + // :: (Node) → Selection + // Find the cursor or leaf node selection closest to the end of the + // given document. + Selection.atEnd = function atEnd (doc) { + return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc) + }; + + // :: (Node, Object) → Selection + // Deserialize the JSON representation of a selection. Must be + // implemented for custom classes (as a static class method). + Selection.fromJSON = function fromJSON (doc, json) { + if (!json || !json.type) { throw new RangeError("Invalid input for Selection.fromJSON") } + var cls = classesById[json.type]; + if (!cls) { throw new RangeError(("No selection type " + (json.type) + " defined")) } + return cls.fromJSON(doc, json) + }; + + // :: (string, constructor) + // To be able to deserialize selections from JSON, custom selection + // classes must register themselves with an ID string, so that they + // can be disambiguated. Try to pick something that's unlikely to + // clash with classes from other modules. + Selection.jsonID = function jsonID (id, selectionClass) { + if (id in classesById) { throw new RangeError("Duplicate use of selection JSON ID " + id) } + classesById[id] = selectionClass; + selectionClass.prototype.jsonID = id; + return selectionClass + }; + + // :: () → SelectionBookmark + // Get a [bookmark](#state.SelectionBookmark) for this selection, + // which is a value that can be mapped without having access to a + // current document, and later resolved to a real selection for a + // given document again. (This is used mostly by the history to + // track and restore old selections.) The default implementation of + // this method just converts the selection to a text selection and + // returns the bookmark for that. + Selection.prototype.getBookmark = function getBookmark () { + return TextSelection.between(this.$anchor, this.$head).getBookmark() + }; + + Object.defineProperties( Selection.prototype, prototypeAccessors$8 ); + + // :: bool + // Controls whether, when a selection of this type is active in the + // browser, the selected range should be visible to the user. Defaults + // to `true`. + Selection.prototype.visible = true; + + // SelectionBookmark:: interface + // A lightweight, document-independent representation of a selection. + // You can define a custom bookmark type for a custom selection class + // to make the history handle it well. + // + // map:: (mapping: Mapping) → SelectionBookmark + // Map the bookmark through a set of changes. + // + // resolve:: (doc: Node) → Selection + // Resolve the bookmark to a real selection again. This may need to + // do some error checking and may fall back to a default (usually + // [`TextSelection.between`](#state.TextSelection^between)) if + // mapping made the bookmark invalid. + + // ::- Represents a selected range in a document. + var SelectionRange = function SelectionRange($from, $to) { + // :: ResolvedPos + // The lower bound of the range. + this.$from = $from; + // :: ResolvedPos + // The upper bound of the range. + this.$to = $to; + }; + + // ::- A text selection represents a classical editor selection, with + // a head (the moving side) and anchor (immobile side), both of which + // point into textblock nodes. It can be empty (a regular cursor + // position). + var TextSelection = /*@__PURE__*/(function (Selection) { + function TextSelection($anchor, $head) { + if ( $head === void 0 ) $head = $anchor; + + Selection.call(this, $anchor, $head); + } + + if ( Selection ) TextSelection.__proto__ = Selection; + TextSelection.prototype = Object.create( Selection && Selection.prototype ); + TextSelection.prototype.constructor = TextSelection; + + var prototypeAccessors$1 = { $cursor: { configurable: true } }; + + // :: ?ResolvedPos + // Returns a resolved position if this is a cursor selection (an + // empty text selection), and null otherwise. + prototypeAccessors$1.$cursor.get = function () { return this.$anchor.pos == this.$head.pos ? this.$head : null }; + + TextSelection.prototype.map = function map (doc, mapping) { + var $head = doc.resolve(mapping.map(this.head)); + if (!$head.parent.inlineContent) { return Selection.near($head) } + var $anchor = doc.resolve(mapping.map(this.anchor)); + return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head) + }; + + TextSelection.prototype.replace = function replace (tr, content) { + if ( content === void 0 ) content = Slice.empty; + + Selection.prototype.replace.call(this, tr, content); + if (content == Slice.empty) { + var marks = this.$from.marksAcross(this.$to); + if (marks) { tr.ensureMarks(marks); } + } + }; + + TextSelection.prototype.eq = function eq (other) { + return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head + }; + + TextSelection.prototype.getBookmark = function getBookmark () { + return new TextBookmark(this.anchor, this.head) + }; + + TextSelection.prototype.toJSON = function toJSON () { + return {type: "text", anchor: this.anchor, head: this.head} + }; + + TextSelection.fromJSON = function fromJSON (doc, json) { + if (typeof json.anchor != "number" || typeof json.head != "number") + { throw new RangeError("Invalid input for TextSelection.fromJSON") } + return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head)) + }; + + // :: (Node, number, ?number) → TextSelection + // Create a text selection from non-resolved positions. + TextSelection.create = function create (doc, anchor, head) { + if ( head === void 0 ) head = anchor; + + var $anchor = doc.resolve(anchor); + return new this($anchor, head == anchor ? $anchor : doc.resolve(head)) + }; + + // :: (ResolvedPos, ResolvedPos, ?number) → Selection + // Return a text selection that spans the given positions or, if + // they aren't text positions, find a text selection near them. + // `bias` determines whether the method searches forward (default) + // or backwards (negative number) first. Will fall back to calling + // [`Selection.near`](#state.Selection^near) when the document + // doesn't contain a valid text position. + TextSelection.between = function between ($anchor, $head, bias) { + var dPos = $anchor.pos - $head.pos; + if (!bias || dPos) { bias = dPos >= 0 ? 1 : -1; } + if (!$head.parent.inlineContent) { + var found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true); + if (found) { $head = found.$head; } + else { return Selection.near($head, bias) } + } + if (!$anchor.parent.inlineContent) { + if (dPos == 0) { + $anchor = $head; + } else { + $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor; + if (($anchor.pos < $head.pos) != (dPos < 0)) { $anchor = $head; } + } + } + return new TextSelection($anchor, $head) + }; + + Object.defineProperties( TextSelection.prototype, prototypeAccessors$1 ); + + return TextSelection; + }(Selection)); + + Selection.jsonID("text", TextSelection); + + var TextBookmark = function TextBookmark(anchor, head) { + this.anchor = anchor; + this.head = head; + }; + TextBookmark.prototype.map = function map (mapping) { + return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head)) + }; + TextBookmark.prototype.resolve = function resolve (doc) { + return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head)) + }; + + // ::- A node selection is a selection that points at a single node. + // All nodes marked [selectable](#model.NodeSpec.selectable) can be + // the target of a node selection. In such a selection, `from` and + // `to` point directly before and after the selected node, `anchor` + // equals `from`, and `head` equals `to`.. + var NodeSelection = /*@__PURE__*/(function (Selection) { + function NodeSelection($pos) { + var node = $pos.nodeAfter; + var $end = $pos.node(0).resolve($pos.pos + node.nodeSize); + Selection.call(this, $pos, $end); + // :: Node The selected node. + this.node = node; + } + + if ( Selection ) NodeSelection.__proto__ = Selection; + NodeSelection.prototype = Object.create( Selection && Selection.prototype ); + NodeSelection.prototype.constructor = NodeSelection; + + NodeSelection.prototype.map = function map (doc, mapping) { + var ref = mapping.mapResult(this.anchor); + var deleted = ref.deleted; + var pos = ref.pos; + var $pos = doc.resolve(pos); + if (deleted) { return Selection.near($pos) } + return new NodeSelection($pos) + }; + + NodeSelection.prototype.content = function content () { + return new Slice(Fragment.from(this.node), 0, 0) + }; + + NodeSelection.prototype.eq = function eq (other) { + return other instanceof NodeSelection && other.anchor == this.anchor + }; + + NodeSelection.prototype.toJSON = function toJSON () { + return {type: "node", anchor: this.anchor} + }; + + NodeSelection.prototype.getBookmark = function getBookmark () { return new NodeBookmark(this.anchor) }; + + NodeSelection.fromJSON = function fromJSON (doc, json) { + if (typeof json.anchor != "number") + { throw new RangeError("Invalid input for NodeSelection.fromJSON") } + return new NodeSelection(doc.resolve(json.anchor)) + }; + + // :: (Node, number) → NodeSelection + // Create a node selection from non-resolved positions. + NodeSelection.create = function create (doc, from) { + return new this(doc.resolve(from)) + }; + + // :: (Node) → bool + // Determines whether the given node may be selected as a node + // selection. + NodeSelection.isSelectable = function isSelectable (node) { + return !node.isText && node.type.spec.selectable !== false + }; + + return NodeSelection; + }(Selection)); + + NodeSelection.prototype.visible = false; + + Selection.jsonID("node", NodeSelection); + + var NodeBookmark = function NodeBookmark(anchor) { + this.anchor = anchor; + }; + NodeBookmark.prototype.map = function map (mapping) { + var ref = mapping.mapResult(this.anchor); + var deleted = ref.deleted; + var pos = ref.pos; + return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos) + }; + NodeBookmark.prototype.resolve = function resolve (doc) { + var $pos = doc.resolve(this.anchor), node = $pos.nodeAfter; + if (node && NodeSelection.isSelectable(node)) { return new NodeSelection($pos) } + return Selection.near($pos) + }; + + // ::- A selection type that represents selecting the whole document + // (which can not necessarily be expressed with a text selection, when + // there are for example leaf block nodes at the start or end of the + // document). + var AllSelection = /*@__PURE__*/(function (Selection) { + function AllSelection(doc) { + Selection.call(this, doc.resolve(0), doc.resolve(doc.content.size)); + } + + if ( Selection ) AllSelection.__proto__ = Selection; + AllSelection.prototype = Object.create( Selection && Selection.prototype ); + AllSelection.prototype.constructor = AllSelection; + + AllSelection.prototype.replace = function replace (tr, content) { + if ( content === void 0 ) content = Slice.empty; + + if (content == Slice.empty) { + tr.delete(0, tr.doc.content.size); + var sel = Selection.atStart(tr.doc); + if (!sel.eq(tr.selection)) { tr.setSelection(sel); } + } else { + Selection.prototype.replace.call(this, tr, content); + } + }; + + AllSelection.prototype.toJSON = function toJSON () { return {type: "all"} }; + + AllSelection.fromJSON = function fromJSON (doc) { return new AllSelection(doc) }; + + AllSelection.prototype.map = function map (doc) { return new AllSelection(doc) }; + + AllSelection.prototype.eq = function eq (other) { return other instanceof AllSelection }; + + AllSelection.prototype.getBookmark = function getBookmark () { return AllBookmark }; + + return AllSelection; + }(Selection)); + + Selection.jsonID("all", AllSelection); + + var AllBookmark = { + map: function map() { return this }, + resolve: function resolve(doc) { return new AllSelection(doc) } + }; + + // FIXME we'll need some awareness of text direction when scanning for selections + + // Try to find a selection inside the given node. `pos` points at the + // position where the search starts. When `text` is true, only return + // text selections. + function findSelectionIn(doc, node, pos, index, dir, text) { + if (node.inlineContent) { return TextSelection.create(doc, pos) } + for (var i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) { + var child = node.child(i); + if (!child.isAtom) { + var inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text); + if (inner) { return inner } + } else if (!text && NodeSelection.isSelectable(child)) { + return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0)) + } + pos += child.nodeSize * dir; + } + } + + function selectionToInsertionEnd(tr, startLen, bias) { + var last = tr.steps.length - 1; + if (last < startLen) { return } + var step = tr.steps[last]; + if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) { return } + var map = tr.mapping.maps[last], end; + map.forEach(function (_from, _to, _newFrom, newTo) { if (end == null) { end = newTo; } }); + tr.setSelection(Selection.near(tr.doc.resolve(end), bias)); + } + + var UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4; + + // ::- An editor state transaction, which can be applied to a state to + // create an updated state. Use + // [`EditorState.tr`](#state.EditorState.tr) to create an instance. + // + // Transactions track changes to the document (they are a subclass of + // [`Transform`](#transform.Transform)), but also other state changes, + // like selection updates and adjustments of the set of [stored + // marks](#state.EditorState.storedMarks). In addition, you can store + // metadata properties in a transaction, which are extra pieces of + // information that client code or plugins can use to describe what a + // transacion represents, so that they can update their [own + // state](#state.StateField) accordingly. + // + // The [editor view](#view.EditorView) uses a few metadata properties: + // it will attach a property `"pointer"` with the value `true` to + // selection transactions directly caused by mouse or touch input, and + // a `"uiEvent"` property of that may be `"paste"`, `"cut"`, or `"drop"`. + var Transaction$1 = /*@__PURE__*/(function (Transform) { + function Transaction(state) { + Transform.call(this, state.doc); + // :: number + // The timestamp associated with this transaction, in the same + // format as `Date.now()`. + this.time = Date.now(); + this.curSelection = state.selection; + // The step count for which the current selection is valid. + this.curSelectionFor = 0; + // :: ?[Mark] + // The stored marks set by this transaction, if any. + this.storedMarks = state.storedMarks; + // Bitfield to track which aspects of the state were updated by + // this transaction. + this.updated = 0; + // Object used to store metadata properties for the transaction. + this.meta = Object.create(null); + } + + if ( Transform ) Transaction.__proto__ = Transform; + Transaction.prototype = Object.create( Transform && Transform.prototype ); + Transaction.prototype.constructor = Transaction; + + var prototypeAccessors = { selection: { configurable: true },selectionSet: { configurable: true },storedMarksSet: { configurable: true },isGeneric: { configurable: true },scrolledIntoView: { configurable: true } }; + + // :: Selection + // The transaction's current selection. This defaults to the editor + // selection [mapped](#state.Selection.map) through the steps in the + // transaction, but can be overwritten with + // [`setSelection`](#state.Transaction.setSelection). + prototypeAccessors.selection.get = function () { + if (this.curSelectionFor < this.steps.length) { + this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor)); + this.curSelectionFor = this.steps.length; + } + return this.curSelection + }; + + // :: (Selection) → Transaction + // Update the transaction's current selection. Will determine the + // selection that the editor gets when the transaction is applied. + Transaction.prototype.setSelection = function setSelection (selection) { + if (selection.$from.doc != this.doc) + { throw new RangeError("Selection passed to setSelection must point at the current document") } + this.curSelection = selection; + this.curSelectionFor = this.steps.length; + this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS; + this.storedMarks = null; + return this + }; + + // :: bool + // Whether the selection was explicitly updated by this transaction. + prototypeAccessors.selectionSet.get = function () { + return (this.updated & UPDATED_SEL) > 0 + }; + + // :: (?[Mark]) → Transaction + // Set the current stored marks. + Transaction.prototype.setStoredMarks = function setStoredMarks (marks) { + this.storedMarks = marks; + this.updated |= UPDATED_MARKS; + return this + }; + + // :: ([Mark]) → Transaction + // Make sure the current stored marks or, if that is null, the marks + // at the selection, match the given set of marks. Does nothing if + // this is already the case. + Transaction.prototype.ensureMarks = function ensureMarks (marks) { + if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks)) + { this.setStoredMarks(marks); } + return this + }; + + // :: (Mark) → Transaction + // Add a mark to the set of stored marks. + Transaction.prototype.addStoredMark = function addStoredMark (mark) { + return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks())) + }; + + // :: (union) → Transaction + // Remove a mark or mark type from the set of stored marks. + Transaction.prototype.removeStoredMark = function removeStoredMark (mark) { + return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks())) + }; + + // :: bool + // Whether the stored marks were explicitly set for this transaction. + prototypeAccessors.storedMarksSet.get = function () { + return (this.updated & UPDATED_MARKS) > 0 + }; + + Transaction.prototype.addStep = function addStep (step, doc) { + Transform.prototype.addStep.call(this, step, doc); + this.updated = this.updated & ~UPDATED_MARKS; + this.storedMarks = null; + }; + + // :: (number) → Transaction + // Update the timestamp for the transaction. + Transaction.prototype.setTime = function setTime (time) { + this.time = time; + return this + }; + + // :: (Slice) → Transaction + // Replace the current selection with the given slice. + Transaction.prototype.replaceSelection = function replaceSelection (slice) { + this.selection.replace(this, slice); + return this + }; + + // :: (Node, ?bool) → Transaction + // Replace the selection with the given node. When `inheritMarks` is + // true and the content is inline, it inherits the marks from the + // place where it is inserted. + Transaction.prototype.replaceSelectionWith = function replaceSelectionWith (node, inheritMarks) { + var selection = this.selection; + if (inheritMarks !== false) + { node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : (selection.$from.marksAcross(selection.$to) || Mark.none))); } + selection.replaceWith(this, node); + return this + }; + + // :: () → Transaction + // Delete the selection. + Transaction.prototype.deleteSelection = function deleteSelection () { + this.selection.replace(this); + return this + }; + + // :: (string, from: ?number, to: ?number) → Transaction + // Replace the given range, or the selection if no range is given, + // with a text node containing the given string. + Transaction.prototype.insertText = function insertText (text, from, to) { + if ( to === void 0 ) to = from; + + var schema = this.doc.type.schema; + if (from == null) { + if (!text) { return this.deleteSelection() } + return this.replaceSelectionWith(schema.text(text), true) + } else { + if (!text) { return this.deleteRange(from, to) } + var marks = this.storedMarks; + if (!marks) { + var $from = this.doc.resolve(from); + marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to)); + } + this.replaceRangeWith(from, to, schema.text(text, marks)); + if (!this.selection.empty) { this.setSelection(Selection.near(this.selection.$to)); } + return this + } + }; + + // :: (union, any) → Transaction + // Store a metadata property in this transaction, keyed either by + // name or by plugin. + Transaction.prototype.setMeta = function setMeta (key, value) { + this.meta[typeof key == "string" ? key : key.key] = value; + return this + }; + + // :: (union) → any + // Retrieve a metadata property for a given name or plugin. + Transaction.prototype.getMeta = function getMeta (key) { + return this.meta[typeof key == "string" ? key : key.key] + }; + + // :: bool + // Returns true if this transaction doesn't contain any metadata, + // and can thus safely be extended. + prototypeAccessors.isGeneric.get = function () { + for (var _ in this.meta) { return false } + return true + }; + + // :: () → Transaction + // Indicate that the editor should scroll the selection into view + // when updated to the state produced by this transaction. + Transaction.prototype.scrollIntoView = function scrollIntoView () { + this.updated |= UPDATED_SCROLL; + return this + }; + + prototypeAccessors.scrolledIntoView.get = function () { + return (this.updated & UPDATED_SCROLL) > 0 + }; + + Object.defineProperties( Transaction.prototype, prototypeAccessors ); + + return Transaction; + }(Transform)); + + function bind(f, self) { + return !self || !f ? f : f.bind(self) + } + + var FieldDesc = function FieldDesc(name, desc, self) { + this.name = name; + this.init = bind(desc.init, self); + this.apply = bind(desc.apply, self); + }; + + var baseFields = [ + new FieldDesc("doc", { + init: function init(config) { return config.doc || config.schema.topNodeType.createAndFill() }, + apply: function apply(tr) { return tr.doc } + }), + + new FieldDesc("selection", { + init: function init(config, instance) { return config.selection || Selection.atStart(instance.doc) }, + apply: function apply(tr) { return tr.selection } + }), + + new FieldDesc("storedMarks", { + init: function init(config) { return config.storedMarks || null }, + apply: function apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null } + }), + + new FieldDesc("scrollToSelection", { + init: function init() { return 0 }, + apply: function apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev } + }) + ]; + + // Object wrapping the part of a state object that stays the same + // across transactions. Stored in the state's `config` property. + var Configuration = function Configuration(schema, plugins) { + var this$1 = this; + + this.schema = schema; + this.fields = baseFields.concat(); + this.plugins = []; + this.pluginsByKey = Object.create(null); + if (plugins) { plugins.forEach(function (plugin) { + if (this$1.pluginsByKey[plugin.key]) + { throw new RangeError("Adding different instances of a keyed plugin (" + plugin.key + ")") } + this$1.plugins.push(plugin); + this$1.pluginsByKey[plugin.key] = plugin; + if (plugin.spec.state) + { this$1.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin)); } + }); } + }; + + // ::- The state of a ProseMirror editor is represented by an object + // of this type. A state is a persistent data structure—it isn't + // updated, but rather a new state value is computed from an old one + // using the [`apply`](#state.EditorState.apply) method. + // + // A state holds a number of built-in fields, and plugins can + // [define](#state.PluginSpec.state) additional fields. + var EditorState = function EditorState(config) { + this.config = config; + }; + + var prototypeAccessors$1$5 = { schema: { configurable: true },plugins: { configurable: true },tr: { configurable: true } }; + + // doc:: Node + // The current document. + + // selection:: Selection + // The selection. + + // storedMarks:: ?[Mark] + // A set of marks to apply to the next input. Will be null when + // no explicit marks have been set. + + // :: Schema + // The schema of the state's document. + prototypeAccessors$1$5.schema.get = function () { + return this.config.schema + }; + + // :: [Plugin] + // The plugins that are active in this state. + prototypeAccessors$1$5.plugins.get = function () { + return this.config.plugins + }; + + // :: (Transaction) → EditorState + // Apply the given transaction to produce a new state. + EditorState.prototype.apply = function apply (tr) { + return this.applyTransaction(tr).state + }; + + // : (Transaction) → bool + EditorState.prototype.filterTransaction = function filterTransaction (tr, ignore) { + if ( ignore === void 0 ) ignore = -1; + + for (var i = 0; i < this.config.plugins.length; i++) { if (i != ignore) { + var plugin = this.config.plugins[i]; + if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this)) + { return false } + } } + return true + }; + + // :: (Transaction) → {state: EditorState, transactions: [Transaction]} + // Verbose variant of [`apply`](#state.EditorState.apply) that + // returns the precise transactions that were applied (which might + // be influenced by the [transaction + // hooks](#state.PluginSpec.filterTransaction) of + // plugins) along with the new state. + EditorState.prototype.applyTransaction = function applyTransaction (rootTr) { + if (!this.filterTransaction(rootTr)) { return {state: this, transactions: []} } + + var trs = [rootTr], newState = this.applyInner(rootTr), seen = null; + // This loop repeatedly gives plugins a chance to respond to + // transactions as new transactions are added, making sure to only + // pass the transactions the plugin did not see before. + for (;;) { + var haveNew = false; + for (var i = 0; i < this.config.plugins.length; i++) { + var plugin = this.config.plugins[i]; + if (plugin.spec.appendTransaction) { + var n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this; + var tr = n < trs.length && + plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState); + if (tr && newState.filterTransaction(tr, i)) { + tr.setMeta("appendedTransaction", rootTr); + if (!seen) { + seen = []; + for (var j = 0; j < this.config.plugins.length; j++) + { seen.push(j < i ? {state: newState, n: trs.length} : {state: this, n: 0}); } + } + trs.push(tr); + newState = newState.applyInner(tr); + haveNew = true; + } + if (seen) { seen[i] = {state: newState, n: trs.length}; } + } + } + if (!haveNew) { return {state: newState, transactions: trs} } + } + }; + + // : (Transaction) → EditorState + EditorState.prototype.applyInner = function applyInner (tr) { + if (!tr.before.eq(this.doc)) { throw new RangeError("Applying a mismatched transaction") } + var newInstance = new EditorState(this.config), fields = this.config.fields; + for (var i = 0; i < fields.length; i++) { + var field = fields[i]; + newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance); + } + for (var i$1 = 0; i$1 < applyListeners.length; i$1++) { applyListeners[i$1](this, tr, newInstance); } + return newInstance + }; + + // :: Transaction + // Start a [transaction](#state.Transaction) from this state. + prototypeAccessors$1$5.tr.get = function () { return new Transaction$1(this) }; + + // :: (Object) → EditorState + // Create a new state. + // + // config::- Configuration options. Must contain `schema` or `doc` (or both). + // + // schema:: ?Schema + // The schema to use. + // + // doc:: ?Node + // The starting document. + // + // selection:: ?Selection + // A valid selection in the document. + // + // storedMarks:: ?[Mark] + // The initial set of [stored marks](#state.EditorState.storedMarks). + // + // plugins:: ?[Plugin] + // The plugins that should be active in this state. + EditorState.create = function create (config) { + var $config = new Configuration(config.schema || config.doc.type.schema, config.plugins); + var instance = new EditorState($config); + for (var i = 0; i < $config.fields.length; i++) + { instance[$config.fields[i].name] = $config.fields[i].init(config, instance); } + return instance + }; + + // :: (Object) → EditorState + // Create a new state based on this one, but with an adjusted set of + // active plugins. State fields that exist in both sets of plugins + // are kept unchanged. Those that no longer exist are dropped, and + // those that are new are initialized using their + // [`init`](#state.StateField.init) method, passing in the new + // configuration object.. + // + // config::- configuration options + // + // schema:: ?Schema + // New schema to use. + // + // plugins:: ?[Plugin] + // New set of active plugins. + EditorState.prototype.reconfigure = function reconfigure (config) { + var $config = new Configuration(config.schema || this.schema, config.plugins); + var fields = $config.fields, instance = new EditorState($config); + for (var i = 0; i < fields.length; i++) { + var name = fields[i].name; + instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance); + } + return instance + }; + + // :: (?union, string, number>) → Object + // Serialize this state to JSON. If you want to serialize the state + // of plugins, pass an object mapping property names to use in the + // resulting JSON object to plugin objects. The argument may also be + // a string or number, in which case it is ignored, to support the + // way `JSON.stringify` calls `toString` methods. + EditorState.prototype.toJSON = function toJSON (pluginFields) { + var result = {doc: this.doc.toJSON(), selection: this.selection.toJSON()}; + if (this.storedMarks) { result.storedMarks = this.storedMarks.map(function (m) { return m.toJSON(); }); } + if (pluginFields && typeof pluginFields == 'object') { for (var prop in pluginFields) { + if (prop == "doc" || prop == "selection") + { throw new RangeError("The JSON fields `doc` and `selection` are reserved") } + var plugin = pluginFields[prop], state = plugin.spec.state; + if (state && state.toJSON) { result[prop] = state.toJSON.call(plugin, this[plugin.key]); } + } } + return result + }; + + // :: (Object, Object, ?Object) → EditorState + // Deserialize a JSON representation of a state. `config` should + // have at least a `schema` field, and should contain array of + // plugins to initialize the state with. `pluginFields` can be used + // to deserialize the state of plugins, by associating plugin + // instances with the property names they use in the JSON object. + // + // config::- configuration options + // + // schema:: Schema + // The schema to use. + // + // plugins:: ?[Plugin] + // The set of active plugins. + EditorState.fromJSON = function fromJSON (config, json, pluginFields) { + if (!json) { throw new RangeError("Invalid input for EditorState.fromJSON") } + if (!config.schema) { throw new RangeError("Required config field 'schema' missing") } + var $config = new Configuration(config.schema, config.plugins); + var instance = new EditorState($config); + $config.fields.forEach(function (field) { + if (field.name == "doc") { + instance.doc = Node.fromJSON(config.schema, json.doc); + } else if (field.name == "selection") { + instance.selection = Selection.fromJSON(instance.doc, json.selection); + } else if (field.name == "storedMarks") { + if (json.storedMarks) { instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON); } + } else { + if (pluginFields) { for (var prop in pluginFields) { + var plugin = pluginFields[prop], state = plugin.spec.state; + if (plugin.key == field.name && state && state.fromJSON && + Object.prototype.hasOwnProperty.call(json, prop)) { + // This field belongs to a plugin mapped to a JSON field, read it from there. + instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance); + return + } + } } + instance[field.name] = field.init(config, instance); + } + }); + return instance + }; + + // Kludge to allow the view to track mappings between different + // instances of a state. + // + // FIXME this is no longer needed as of prosemirror-view 1.9.0, + // though due to backwards-compat we should probably keep it around + // for a while (if only as a no-op) + EditorState.addApplyListener = function addApplyListener (f) { + applyListeners.push(f); + }; + EditorState.removeApplyListener = function removeApplyListener (f) { + var found = applyListeners.indexOf(f); + if (found > -1) { applyListeners.splice(found, 1); } + }; + + Object.defineProperties( EditorState.prototype, prototypeAccessors$1$5 ); + + var applyListeners = []; + + // PluginSpec:: interface + // + // This is the type passed to the [`Plugin`](#state.Plugin) + // constructor. It provides a definition for a plugin. + // + // props:: ?EditorProps + // The [view props](#view.EditorProps) added by this plugin. Props + // that are functions will be bound to have the plugin instance as + // their `this` binding. + // + // state:: ?StateField + // Allows a plugin to define a [state field](#state.StateField), an + // extra slot in the state object in which it can keep its own data. + // + // key:: ?PluginKey + // Can be used to make this a keyed plugin. You can have only one + // plugin with a given key in a given state, but it is possible to + // access the plugin's configuration and state through the key, + // without having access to the plugin instance object. + // + // view:: ?(EditorView) → Object + // When the plugin needs to interact with the editor view, or + // set something up in the DOM, use this field. The function + // will be called when the plugin's state is associated with an + // editor view. + // + // return::- + // Should return an object with the following optional + // properties: + // + // update:: ?(view: EditorView, prevState: EditorState) + // Called whenever the view's state is updated. + // + // destroy:: ?() + // Called when the view is destroyed or receives a state + // with different plugins. + // + // filterTransaction:: ?(Transaction, EditorState) → bool + // When present, this will be called before a transaction is + // applied by the state, allowing the plugin to cancel it (by + // returning false). + // + // appendTransaction:: ?(transactions: [Transaction], oldState: EditorState, newState: EditorState) → ?Transaction + // Allows the plugin to append another transaction to be applied + // after the given array of transactions. When another plugin + // appends a transaction after this was called, it is called again + // with the new state and new transactions—but only the new + // transactions, i.e. it won't be passed transactions that it + // already saw. + + function bindProps(obj, self, target) { + for (var prop in obj) { + var val = obj[prop]; + if (val instanceof Function) { val = val.bind(self); } + else if (prop == "handleDOMEvents") { val = bindProps(val, self, {}); } + target[prop] = val; + } + return target + } + + // ::- Plugins bundle functionality that can be added to an editor. + // They are part of the [editor state](#state.EditorState) and + // may influence that state and the view that contains it. + var Plugin = function Plugin(spec) { + // :: EditorProps + // The [props](#view.EditorProps) exported by this plugin. + this.props = {}; + if (spec.props) { bindProps(spec.props, this, this.props); } + // :: Object + // The plugin's [spec object](#state.PluginSpec). + this.spec = spec; + this.key = spec.key ? spec.key.key : createKey("plugin"); + }; + + // :: (EditorState) → any + // Extract the plugin's state field from an editor state. + Plugin.prototype.getState = function getState (state) { return state[this.key] }; + + // StateField:: interface + // A plugin spec may provide a state field (under its + // [`state`](#state.PluginSpec.state) property) of this type, which + // describes the state it wants to keep. Functions provided here are + // always called with the plugin instance as their `this` binding. + // + // init:: (config: Object, instance: EditorState) → T + // Initialize the value of the field. `config` will be the object + // passed to [`EditorState.create`](#state.EditorState^create). Note + // that `instance` is a half-initialized state instance, and will + // not have values for plugin fields initialized after this one. + // + // apply:: (tr: Transaction, value: T, oldState: EditorState, newState: EditorState) → T + // Apply the given transaction to this state field, producing a new + // field value. Note that the `newState` argument is again a partially + // constructed state does not yet contain the state from plugins + // coming after this one. + // + // toJSON:: ?(value: T) → * + // Convert this field to JSON. Optional, can be left off to disable + // JSON serialization for the field. + // + // fromJSON:: ?(config: Object, value: *, state: EditorState) → T + // Deserialize the JSON representation of this field. Note that the + // `state` argument is again a half-initialized state. + + var keys$1 = Object.create(null); + + function createKey(name) { + if (name in keys$1) { return name + "$" + ++keys$1[name] } + keys$1[name] = 0; + return name + "$" + } + + // ::- A key is used to [tag](#state.PluginSpec.key) + // plugins in a way that makes it possible to find them, given an + // editor state. Assigning a key does mean only one plugin of that + // type can be active in a state. + var PluginKey = function PluginKey(name) { + if ( name === void 0 ) name = "key"; + this.key = createKey(name); }; + + // :: (EditorState) → ?Plugin + // Get the active plugin with this key, if any, from an editor + // state. + PluginKey.prototype.get = function get (state) { return state.config.pluginsByKey[this.key] }; + + // :: (EditorState) → ?any + // Get the plugin's state from an editor state. + PluginKey.prototype.getState = function getState (state) { return state[this.key] }; + + var result = {}; + + if (typeof navigator != "undefined" && typeof document != "undefined") { + var ie_edge = /Edge\/(\d+)/.exec(navigator.userAgent); + var ie_upto10 = /MSIE \d/.test(navigator.userAgent); + var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); + + result.mac = /Mac/.test(navigator.platform); + var ie = result.ie = !!(ie_upto10 || ie_11up || ie_edge); + result.ie_version = ie_upto10 ? document.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : null; + result.gecko = !ie && /gecko\/(\d+)/i.test(navigator.userAgent); + result.gecko_version = result.gecko && +(/Firefox\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1]; + var chrome = !ie && /Chrome\/(\d+)/.exec(navigator.userAgent); + result.chrome = !!chrome; + result.chrome_version = chrome && +chrome[1]; + result.ios = !ie && /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); + result.android = /Android \d/.test(navigator.userAgent); + result.webkit = "webkitFontSmoothing" in document.documentElement.style; + result.safari = /Apple Computer/.test(navigator.vendor); + result.webkit_version = result.webkit && +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1]; + } + + var domIndex = function(node) { + for (var index = 0;; index++) { + node = node.previousSibling; + if (!node) { return index } + } + }; + + var parentNode = function(node) { + var parent = node.parentNode; + return parent && parent.nodeType == 11 ? parent.host : parent + }; + + var reusedRange = null; + + // Note that this will always return the same range, because DOM range + // objects are every expensive, and keep slowing down subsequent DOM + // updates, for some reason. + var textRange = function(node, from, to) { + var range = reusedRange || (reusedRange = document.createRange()); + range.setEnd(node, to == null ? node.nodeValue.length : to); + range.setStart(node, from || 0); + return range + }; + + // Scans forward and backward through DOM positions equivalent to the + // given one to see if the two are in the same place (i.e. after a + // text node vs at the end of that text node) + var isEquivalentPosition = function(node, off, targetNode, targetOff) { + return targetNode && (scanFor(node, off, targetNode, targetOff, -1) || + scanFor(node, off, targetNode, targetOff, 1)) + }; + + var atomElements = /^(img|br|input|textarea|hr)$/i; + + function scanFor(node, off, targetNode, targetOff, dir) { + for (;;) { + if (node == targetNode && off == targetOff) { return true } + if (off == (dir < 0 ? 0 : nodeSize(node))) { + var parent = node.parentNode; + if (parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == "false") + { return false } + off = domIndex(node) + (dir < 0 ? 0 : 1); + node = parent; + } else if (node.nodeType == 1) { + node = node.childNodes[off + (dir < 0 ? -1 : 0)]; + if (node.contentEditable == "false") { return false } + off = dir < 0 ? nodeSize(node) : 0; + } else { + return false + } + } + } + + function nodeSize(node) { + return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length + } + + function isOnEdge(node, offset, parent) { + for (var atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd;) { + if (node == parent) { return true } + var index = domIndex(node); + node = node.parentNode; + if (!node) { return false } + atStart = atStart && index == 0; + atEnd = atEnd && index == nodeSize(node); + } + } + + function hasBlockDesc(dom) { + var desc; + for (var cur = dom; cur; cur = cur.parentNode) { if (desc = cur.pmViewDesc) { break } } + return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom) + } + + // Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523 + // (isCollapsed inappropriately returns true in shadow dom) + var selectionCollapsed = function(domSel) { + var collapsed = domSel.isCollapsed; + if (collapsed && result.chrome && domSel.rangeCount && !domSel.getRangeAt(0).collapsed) + { collapsed = false; } + return collapsed + }; + + function keyEvent(keyCode, key) { + var event = document.createEvent("Event"); + event.initEvent("keydown", true, true); + event.keyCode = keyCode; + event.key = event.code = key; + return event + } + + function windowRect(doc) { + return {left: 0, right: doc.documentElement.clientWidth, + top: 0, bottom: doc.documentElement.clientHeight} + } + + function getSide(value, side) { + return typeof value == "number" ? value : value[side] + } + + function clientRect(node) { + var rect = node.getBoundingClientRect(); + // Make sure scrollbar width isn't included in the rectangle + return {left: rect.left, right: rect.left + node.clientWidth, + top: rect.top, bottom: rect.top + node.clientHeight} + } + + function scrollRectIntoView(view, rect, startDOM) { + var scrollThreshold = view.someProp("scrollThreshold") || 0, scrollMargin = view.someProp("scrollMargin") || 5; + var doc = view.dom.ownerDocument; + for (var parent = startDOM || view.dom;; parent = parentNode(parent)) { + if (!parent) { break } + if (parent.nodeType != 1) { continue } + var atTop = parent == doc.body || parent.nodeType != 1; + var bounding = atTop ? windowRect(doc) : clientRect(parent); + var moveX = 0, moveY = 0; + if (rect.top < bounding.top + getSide(scrollThreshold, "top")) + { moveY = -(bounding.top - rect.top + getSide(scrollMargin, "top")); } + else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, "bottom")) + { moveY = rect.bottom - bounding.bottom + getSide(scrollMargin, "bottom"); } + if (rect.left < bounding.left + getSide(scrollThreshold, "left")) + { moveX = -(bounding.left - rect.left + getSide(scrollMargin, "left")); } + else if (rect.right > bounding.right - getSide(scrollThreshold, "right")) + { moveX = rect.right - bounding.right + getSide(scrollMargin, "right"); } + if (moveX || moveY) { + if (atTop) { + doc.defaultView.scrollBy(moveX, moveY); + } else { + var startX = parent.scrollLeft, startY = parent.scrollTop; + if (moveY) { parent.scrollTop += moveY; } + if (moveX) { parent.scrollLeft += moveX; } + var dX = parent.scrollLeft - startX, dY = parent.scrollTop - startY; + rect = {left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY}; + } + } + if (atTop) { break } + } + } + + // Store the scroll position of the editor's parent nodes, along with + // the top position of an element near the top of the editor, which + // will be used to make sure the visible viewport remains stable even + // when the size of the content above changes. + function storeScrollPos(view) { + var rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top); + var refDOM, refTop; + for (var x = (rect.left + rect.right) / 2, y = startY + 1; + y < Math.min(innerHeight, rect.bottom); y += 5) { + var dom = view.root.elementFromPoint(x, y); + if (dom == view.dom || !view.dom.contains(dom)) { continue } + var localRect = dom.getBoundingClientRect(); + if (localRect.top >= startY - 20) { + refDOM = dom; + refTop = localRect.top; + break + } + } + return {refDOM: refDOM, refTop: refTop, stack: scrollStack(view.dom)} + } + + function scrollStack(dom) { + var stack = [], doc = dom.ownerDocument; + for (; dom; dom = parentNode(dom)) { + stack.push({dom: dom, top: dom.scrollTop, left: dom.scrollLeft}); + if (dom == doc) { break } + } + return stack + } + + // Reset the scroll position of the editor's parent nodes to that what + // it was before, when storeScrollPos was called. + function resetScrollPos(ref) { + var refDOM = ref.refDOM; + var refTop = ref.refTop; + var stack = ref.stack; + + var newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0; + restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop); + } + + function restoreScrollStack(stack, dTop) { + for (var i = 0; i < stack.length; i++) { + var ref = stack[i]; + var dom = ref.dom; + var top = ref.top; + var left = ref.left; + if (dom.scrollTop != top + dTop) { dom.scrollTop = top + dTop; } + if (dom.scrollLeft != left) { dom.scrollLeft = left; } + } + } + + var preventScrollSupported = null; + // Feature-detects support for .focus({preventScroll: true}), and uses + // a fallback kludge when not supported. + function focusPreventScroll(dom) { + if (dom.setActive) { return dom.setActive() } // in IE + if (preventScrollSupported) { return dom.focus(preventScrollSupported) } + + var stored = scrollStack(dom); + dom.focus(preventScrollSupported == null ? { + get preventScroll() { + preventScrollSupported = {preventScroll: true}; + return true + } + } : undefined); + if (!preventScrollSupported) { + preventScrollSupported = false; + restoreScrollStack(stored, 0); + } + } + + function findOffsetInNode(node, coords) { + var closest, dxClosest = 2e8, coordsClosest, offset = 0; + var rowBot = coords.top, rowTop = coords.top; + for (var child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) { + var rects = (void 0); + if (child.nodeType == 1) { rects = child.getClientRects(); } + else if (child.nodeType == 3) { rects = textRange(child).getClientRects(); } + else { continue } + + for (var i = 0; i < rects.length; i++) { + var rect = rects[i]; + if (rect.top <= rowBot && rect.bottom >= rowTop) { + rowBot = Math.max(rect.bottom, rowBot); + rowTop = Math.min(rect.top, rowTop); + var dx = rect.left > coords.left ? rect.left - coords.left + : rect.right < coords.left ? coords.left - rect.right : 0; + if (dx < dxClosest) { + closest = child; + dxClosest = dx; + coordsClosest = dx && closest.nodeType == 3 ? {left: rect.right < coords.left ? rect.right : rect.left, top: coords.top} : coords; + if (child.nodeType == 1 && dx) + { offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0); } + continue + } + } + if (!closest && (coords.left >= rect.right && coords.top >= rect.top || + coords.left >= rect.left && coords.top >= rect.bottom)) + { offset = childIndex + 1; } + } + } + if (closest && closest.nodeType == 3) { return findOffsetInText(closest, coordsClosest) } + if (!closest || (dxClosest && closest.nodeType == 1)) { return {node: node, offset: offset} } + return findOffsetInNode(closest, coordsClosest) + } + + function findOffsetInText(node, coords) { + var len = node.nodeValue.length; + var range = document.createRange(); + for (var i = 0; i < len; i++) { + range.setEnd(node, i + 1); + range.setStart(node, i); + var rect = singleRect(range, 1); + if (rect.top == rect.bottom) { continue } + if (inRect(coords, rect)) + { return {node: node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0)} } + } + return {node: node, offset: 0} + } + + function inRect(coords, rect) { + return coords.left >= rect.left - 1 && coords.left <= rect.right + 1&& + coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1 + } + + function targetKludge(dom, coords) { + var parent = dom.parentNode; + if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left) + { return parent } + return dom + } + + function posFromElement(view, elt, coords) { + var ref = findOffsetInNode(elt, coords); + var node = ref.node; + var offset = ref.offset; + var bias = -1; + if (node.nodeType == 1 && !node.firstChild) { + var rect = node.getBoundingClientRect(); + bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1; + } + return view.docView.posFromDOM(node, offset, bias) + } + + function posFromCaret(view, node, offset, coords) { + // Browser (in caretPosition/RangeFromPoint) will agressively + // normalize towards nearby inline nodes. Since we are interested in + // positions between block nodes too, we first walk up the hierarchy + // of nodes to see if there are block nodes that the coordinates + // fall outside of. If so, we take the position before/after that + // block. If not, we call `posFromDOM` on the raw node/offset. + var outside = -1; + for (var cur = node;;) { + if (cur == view.dom) { break } + var desc = view.docView.nearestDesc(cur, true); + if (!desc) { return null } + if (desc.node.isBlock && desc.parent) { + var rect = desc.dom.getBoundingClientRect(); + if (rect.left > coords.left || rect.top > coords.top) { outside = desc.posBefore; } + else if (rect.right < coords.left || rect.bottom < coords.top) { outside = desc.posAfter; } + else { break } + } + cur = desc.dom.parentNode; + } + return outside > -1 ? outside : view.docView.posFromDOM(node, offset) + } + + function elementFromPoint(element, coords, box) { + var len = element.childNodes.length; + if (len && box.top < box.bottom) { + for (var startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI;;) { + var child = element.childNodes[i]; + if (child.nodeType == 1) { + var rects = child.getClientRects(); + for (var j = 0; j < rects.length; j++) { + var rect = rects[j]; + if (inRect(coords, rect)) { return elementFromPoint(child, coords, rect) } + } + } + if ((i = (i + 1) % len) == startI) { break } + } + } + return element + } + + // Given an x,y position on the editor, get the position in the document. + function posAtCoords(view, coords) { + var assign, assign$1; + + var root = view.root, node, offset; + if (root.caretPositionFromPoint) { + try { // Firefox throws for this call in hard-to-predict circumstances (#994) + var pos$1 = root.caretPositionFromPoint(coords.left, coords.top); + if (pos$1) { ((assign = pos$1, node = assign.offsetNode, offset = assign.offset)); } + } catch (_) {} + } + if (!node && root.caretRangeFromPoint) { + var range = root.caretRangeFromPoint(coords.left, coords.top); + if (range) { ((assign$1 = range, node = assign$1.startContainer, offset = assign$1.startOffset)); } + } + + var elt = root.elementFromPoint(coords.left, coords.top + 1), pos; + if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) { + var box = view.dom.getBoundingClientRect(); + if (!inRect(coords, box)) { return null } + elt = elementFromPoint(view.dom, coords, box); + if (!elt) { return null } + } + // Safari's caretRangeFromPoint returns nonsense when on a draggable element + if (result.safari && elt.draggable) { node = offset = null; } + elt = targetKludge(elt, coords); + if (node) { + if (result.gecko && node.nodeType == 1) { + // Firefox will sometimes return offsets into nodes, which + // have no actual children, from caretPositionFromPoint (#953) + offset = Math.min(offset, node.childNodes.length); + // It'll also move the returned position before image nodes, + // even if those are behind it. + if (offset < node.childNodes.length) { + var next = node.childNodes[offset], box$1; + if (next.nodeName == "IMG" && (box$1 = next.getBoundingClientRect()).right <= coords.left && + box$1.bottom > coords.top) + { offset++; } + } + } + // Suspiciously specific kludge to work around caret*FromPoint + // never returning a position at the end of the document + if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 && + coords.top > node.lastChild.getBoundingClientRect().bottom) + { pos = view.state.doc.content.size; } + // Ignore positions directly after a BR, since caret*FromPoint + // 'round up' positions that would be more accurately placed + // before the BR node. + else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != "BR") + { pos = posFromCaret(view, node, offset, coords); } + } + if (pos == null) { pos = posFromElement(view, elt, coords); } + + var desc = view.docView.nearestDesc(elt, true); + return {pos: pos, inside: desc ? desc.posAtStart - desc.border : -1} + } + + function singleRect(object, bias) { + var rects = object.getClientRects(); + return !rects.length ? object.getBoundingClientRect() : rects[bias < 0 ? 0 : rects.length - 1] + } + + var BIDI = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + + // : (EditorView, number, number) → {left: number, top: number, right: number, bottom: number} + // Given a position in the document model, get a bounding box of the + // character at that position, relative to the window. + function coordsAtPos(view, pos, side) { + var ref = view.docView.domFromPos(pos); + var node = ref.node; + var offset = ref.offset; + var $pos = view.state.doc.resolve(pos), inline = $pos.parent.inlineContent; + + // These browsers support querying empty text ranges. Prefer that in + // bidi context. + var supportEmptyRange = result.webkit || result.gecko; + if (node.nodeType == 3 && supportEmptyRange && BIDI.test(node.nodeValue)) { + var rect = singleRect(textRange(node, offset, offset), side); + // Firefox returns bad results (the position before the space) + // when querying a position directly after line-broken + // whitespace. Detect this situation and and kludge around it + if (result.gecko && offset && /\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) { + var rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1); + if (rectBefore.top == rect.top) { + var rectAfter = singleRect(textRange(node, offset, offset + 1), -1); + if (rectAfter.top != rect.top) + { return flattenV(rectAfter, rectAfter.left < rectBefore.left) } + } + } + return rect + } + + // Move up the DOM as far as possible when in inline context. + if (inline) { + var parent = $pos.depth ? view.docView.domAfterPos($pos.before()) : view.dom; + while (side < 0 && !offset && node != parent) { + offset = domIndex(node); + node = node.parentNode; + } + while (side >= 0 && offset == nodeSize(node) && node != parent) { + offset = domIndex(node) + 1; + node = node.parentNode; + } + } + + if (node.nodeType == 3) { + if (side < 0) { return flattenV(singleRect(textRange(node, offset - 1, offset), 1), false) } + return flattenV(singleRect(textRange(node, offset, offset + 1), -1), true) + } + + // Return a horizontal line in block context + if (!inline) { + if (offset && (side < 0 || offset == nodeSize(node))) { + var before = node.childNodes[offset - 1]; + if (before.nodeType == 1) { return flattenH(before.getBoundingClientRect(), false) } + } + if (offset < nodeSize(node)) { + var after = node.childNodes[offset]; + if (after.nodeType == 1) { return flattenH(after.getBoundingClientRect(), true) } + } + return flattenH(node.getBoundingClientRect(), side >= 0) + } + + // Inline, not in text node (this is not Bidi-safe) + if (offset && (side < 0 || offset == nodeSize(node))) { + var before$1 = node.childNodes[offset - 1]; + var target = before$1.nodeType == 3 ? textRange(before$1, nodeSize(before$1) - (supportEmptyRange ? 0 : 1)) + // BR nodes tend to only return the rectangle before them + : before$1.nodeType == 1 && before$1.nodeName != "BR" ? before$1 : null; + if (target) { return flattenV(singleRect(target, 1), false) } + } + if (offset < nodeSize(node)) { + var after$1 = node.childNodes[offset]; + var target$1 = after$1.nodeType == 3 ? textRange(after$1, 0, (supportEmptyRange ? 0 : 1)) + : after$1.nodeType == 1 ? after$1 : null; + if (target$1) { return flattenV(singleRect(target$1, -1), true) } + } + // All else failed, just try to get a rectangle for the target node + return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, -side), side >= 0) + } + + function flattenV(rect, left) { + if (rect.width == 0) { return rect } + var x = left ? rect.left : rect.right; + return {top: rect.top, bottom: rect.bottom, left: x, right: x} + } + + function flattenH(rect, top) { + if (rect.height == 0) { return rect } + var y = top ? rect.top : rect.bottom; + return {top: y, bottom: y, left: rect.left, right: rect.right} + } + + function withFlushedState(view, state, f) { + var viewState = view.state, active = view.root.activeElement; + if (viewState != state) { view.updateState(state); } + if (active != view.dom) { view.focus(); } + try { + return f() + } finally { + if (viewState != state) { view.updateState(viewState); } + if (active != view.dom && active) { active.focus(); } + } + } + + // : (EditorView, number, number) + // Whether vertical position motion in a given direction + // from a position would leave a text block. + function endOfTextblockVertical(view, state, dir) { + var sel = state.selection; + var $pos = dir == "up" ? sel.$anchor.min(sel.$head) : sel.$anchor.max(sel.$head); + return withFlushedState(view, state, function () { + var ref = view.docView.domFromPos($pos.pos); + var dom = ref.node; + for (;;) { + var nearest = view.docView.nearestDesc(dom, true); + if (!nearest) { break } + if (nearest.node.isBlock) { dom = nearest.dom; break } + dom = nearest.dom.parentNode; + } + var coords = coordsAtPos(view, $pos.pos, 1); + for (var child = dom.firstChild; child; child = child.nextSibling) { + var boxes = (void 0); + if (child.nodeType == 1) { boxes = child.getClientRects(); } + else if (child.nodeType == 3) { boxes = textRange(child, 0, child.nodeValue.length).getClientRects(); } + else { continue } + for (var i = 0; i < boxes.length; i++) { + var box = boxes[i]; + if (box.bottom > box.top && (dir == "up" ? box.bottom < coords.top + 1 : box.top > coords.bottom - 1)) + { return false } + } + } + return true + }) + } + + var maybeRTL = /[\u0590-\u08ac]/; + + function endOfTextblockHorizontal(view, state, dir) { + var ref = state.selection; + var $head = ref.$head; + if (!$head.parent.isTextblock) { return false } + var offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size; + var sel = getSelection(); + // If the textblock is all LTR, or the browser doesn't support + // Selection.modify (Edge), fall back to a primitive approach + if (!maybeRTL.test($head.parent.textContent) || !sel.modify) + { return dir == "left" || dir == "backward" ? atStart : atEnd } + + return withFlushedState(view, state, function () { + // This is a huge hack, but appears to be the best we can + // currently do: use `Selection.modify` to move the selection by + // one character, and see if that moves the cursor out of the + // textblock (or doesn't move it at all, when at the start/end of + // the document). + var oldRange = sel.getRangeAt(0), oldNode = sel.focusNode, oldOff = sel.focusOffset; + var oldBidiLevel = sel.caretBidiLevel; // Only for Firefox + sel.modify("move", dir, "character"); + var parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom; + var result = !parentDOM.contains(sel.focusNode.nodeType == 1 ? sel.focusNode : sel.focusNode.parentNode) || + (oldNode == sel.focusNode && oldOff == sel.focusOffset); + // Restore the previous selection + sel.removeAllRanges(); + sel.addRange(oldRange); + if (oldBidiLevel != null) { sel.caretBidiLevel = oldBidiLevel; } + return result + }) + } + + var cachedState = null, cachedDir = null, cachedResult = false; + function endOfTextblock(view, state, dir) { + if (cachedState == state && cachedDir == dir) { return cachedResult } + cachedState = state; cachedDir = dir; + return cachedResult = dir == "up" || dir == "down" + ? endOfTextblockVertical(view, state, dir) + : endOfTextblockHorizontal(view, state, dir) + } + + // NodeView:: interface + // + // By default, document nodes are rendered using the result of the + // [`toDOM`](#model.NodeSpec.toDOM) method of their spec, and managed + // entirely by the editor. For some use cases, such as embedded + // node-specific editing interfaces, you want more control over + // the behavior of a node's in-editor representation, and need to + // [define](#view.EditorProps.nodeViews) a custom node view. + // + // Mark views only support `dom` and `contentDOM`, and don't support + // any of the node view methods. + // + // Objects returned as node views must conform to this interface. + // + // dom:: ?dom.Node + // The outer DOM node that represents the document node. When not + // given, the default strategy is used to create a DOM node. + // + // contentDOM:: ?dom.Node + // The DOM node that should hold the node's content. Only meaningful + // if the node view also defines a `dom` property and if its node + // type is not a leaf node type. When this is present, ProseMirror + // will take care of rendering the node's children into it. When it + // is not present, the node view itself is responsible for rendering + // (or deciding not to render) its child nodes. + // + // update:: ?(node: Node, decorations: [Decoration]) → bool + // When given, this will be called when the view is updating itself. + // It will be given a node (possibly of a different type), and an + // array of active decorations (which are automatically drawn, and + // the node view may ignore if it isn't interested in them), and + // should return true if it was able to update to that node, and + // false otherwise. If the node view has a `contentDOM` property (or + // no `dom` property), updating its child nodes will be handled by + // ProseMirror. + // + // selectNode:: ?() + // Can be used to override the way the node's selected status (as a + // node selection) is displayed. + // + // deselectNode:: ?() + // When defining a `selectNode` method, you should also provide a + // `deselectNode` method to remove the effect again. + // + // setSelection:: ?(anchor: number, head: number, root: dom.Document) + // This will be called to handle setting the selection inside the + // node. The `anchor` and `head` positions are relative to the start + // of the node. By default, a DOM selection will be created between + // the DOM positions corresponding to those positions, but if you + // override it you can do something else. + // + // stopEvent:: ?(event: dom.Event) → bool + // Can be used to prevent the editor view from trying to handle some + // or all DOM events that bubble up from the node view. Events for + // which this returns true are not handled by the editor. + // + // ignoreMutation:: ?(dom.MutationRecord) → bool + // Called when a DOM + // [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) + // or a selection change happens within the view. When the change is + // a selection change, the record will have a `type` property of + // `"selection"` (which doesn't occur for native mutation records). + // Return false if the editor should re-read the selection or + // re-parse the range around the mutation, true if it can safely be + // ignored. + // + // destroy:: ?() + // Called when the node view is removed from the editor or the whole + // editor is destroyed. + + // View descriptions are data structures that describe the DOM that is + // used to represent the editor's content. They are used for: + // + // - Incremental redrawing when the document changes + // + // - Figuring out what part of the document a given DOM position + // corresponds to + // + // - Wiring in custom implementations of the editing interface for a + // given node + // + // They form a doubly-linked mutable tree, starting at `view.docView`. + + var NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3; + + // Superclass for the various kinds of descriptions. Defines their + // basic structure and shared methods. + var ViewDesc = function ViewDesc(parent, children, dom, contentDOM) { + this.parent = parent; + this.children = children; + this.dom = dom; + // An expando property on the DOM node provides a link back to its + // description. + dom.pmViewDesc = this; + // This is the node that holds the child views. It may be null for + // descs that don't have children. + this.contentDOM = contentDOM; + this.dirty = NOT_DIRTY; + }; + + var prototypeAccessors$9 = { beforePosition: { configurable: true },size: { configurable: true },border: { configurable: true },posBefore: { configurable: true },posAtStart: { configurable: true },posAfter: { configurable: true },posAtEnd: { configurable: true },contentLost: { configurable: true } }; + + // Used to check whether a given description corresponds to a + // widget/mark/node. + ViewDesc.prototype.matchesWidget = function matchesWidget () { return false }; + ViewDesc.prototype.matchesMark = function matchesMark () { return false }; + ViewDesc.prototype.matchesNode = function matchesNode () { return false }; + ViewDesc.prototype.matchesHack = function matchesHack () { return false }; + + prototypeAccessors$9.beforePosition.get = function () { return false }; + + // : () → ?ParseRule + // When parsing in-editor content (in domchange.js), we allow + // descriptions to determine the parse rules that should be used to + // parse them. + ViewDesc.prototype.parseRule = function parseRule () { return null }; + + // : (dom.Event) → bool + // Used by the editor's event handler to ignore events that come + // from certain descs. + ViewDesc.prototype.stopEvent = function stopEvent () { return false }; + + // The size of the content represented by this desc. + prototypeAccessors$9.size.get = function () { + var size = 0; + for (var i = 0; i < this.children.length; i++) { size += this.children[i].size; } + return size + }; + + // For block nodes, this represents the space taken up by their + // start/end tokens. + prototypeAccessors$9.border.get = function () { return 0 }; + + ViewDesc.prototype.destroy = function destroy () { + this.parent = null; + if (this.dom.pmViewDesc == this) { this.dom.pmViewDesc = null; } + for (var i = 0; i < this.children.length; i++) + { this.children[i].destroy(); } + }; + + ViewDesc.prototype.posBeforeChild = function posBeforeChild (child) { + for (var i = 0, pos = this.posAtStart; i < this.children.length; i++) { + var cur = this.children[i]; + if (cur == child) { return pos } + pos += cur.size; + } + }; + + prototypeAccessors$9.posBefore.get = function () { + return this.parent.posBeforeChild(this) + }; + + prototypeAccessors$9.posAtStart.get = function () { + return this.parent ? this.parent.posBeforeChild(this) + this.border : 0 + }; + + prototypeAccessors$9.posAfter.get = function () { + return this.posBefore + this.size + }; + + prototypeAccessors$9.posAtEnd.get = function () { + return this.posAtStart + this.size - 2 * this.border + }; + + // : (dom.Node, number, ?number) → number + ViewDesc.prototype.localPosFromDOM = function localPosFromDOM (dom, offset, bias) { + // If the DOM position is in the content, use the child desc after + // it to figure out a position. + if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) { + if (bias < 0) { + var domBefore, desc; + if (dom == this.contentDOM) { + domBefore = dom.childNodes[offset - 1]; + } else { + while (dom.parentNode != this.contentDOM) { dom = dom.parentNode; } + domBefore = dom.previousSibling; + } + while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this)) { domBefore = domBefore.previousSibling; } + return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart + } else { + var domAfter, desc$1; + if (dom == this.contentDOM) { + domAfter = dom.childNodes[offset]; + } else { + while (dom.parentNode != this.contentDOM) { dom = dom.parentNode; } + domAfter = dom.nextSibling; + } + while (domAfter && !((desc$1 = domAfter.pmViewDesc) && desc$1.parent == this)) { domAfter = domAfter.nextSibling; } + return domAfter ? this.posBeforeChild(desc$1) : this.posAtEnd + } + } + // Otherwise, use various heuristics, falling back on the bias + // parameter, to determine whether to return the position at the + // start or at the end of this view desc. + var atEnd; + if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) { + atEnd = dom.compareDocumentPosition(this.contentDOM) & 2; + } else if (this.dom.firstChild) { + if (offset == 0) { for (var search = dom;; search = search.parentNode) { + if (search == this.dom) { atEnd = false; break } + if (search.parentNode.firstChild != search) { break } + } } + if (atEnd == null && offset == dom.childNodes.length) { for (var search$1 = dom;; search$1 = search$1.parentNode) { + if (search$1 == this.dom) { atEnd = true; break } + if (search$1.parentNode.lastChild != search$1) { break } + } } + } + return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart + }; + + // Scan up the dom finding the first desc that is a descendant of + // this one. + ViewDesc.prototype.nearestDesc = function nearestDesc (dom, onlyNodes) { + for (var first = true, cur = dom; cur; cur = cur.parentNode) { + var desc = this.getDesc(cur); + if (desc && (!onlyNodes || desc.node)) { + // If dom is outside of this desc's nodeDOM, don't count it. + if (first && desc.nodeDOM && + !(desc.nodeDOM.nodeType == 1 ? desc.nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : desc.nodeDOM == dom)) + { first = false; } + else + { return desc } + } + } + }; + + ViewDesc.prototype.getDesc = function getDesc (dom) { + var desc = dom.pmViewDesc; + for (var cur = desc; cur; cur = cur.parent) { if (cur == this) { return desc } } + }; + + ViewDesc.prototype.posFromDOM = function posFromDOM (dom, offset, bias) { + for (var scan = dom; scan; scan = scan.parentNode) { + var desc = this.getDesc(scan); + if (desc) { return desc.localPosFromDOM(dom, offset, bias) } + } + return -1 + }; + + // : (number) → ?NodeViewDesc + // Find the desc for the node after the given pos, if any. (When a + // parent node overrode rendering, there might not be one.) + ViewDesc.prototype.descAt = function descAt (pos) { + for (var i = 0, offset = 0; i < this.children.length; i++) { + var child = this.children[i], end = offset + child.size; + if (offset == pos && end != offset) { + while (!child.border && child.children.length) { child = child.children[0]; } + return child + } + if (pos < end) { return child.descAt(pos - offset - child.border) } + offset = end; + } + }; + + // : (number) → {node: dom.Node, offset: number} + ViewDesc.prototype.domFromPos = function domFromPos (pos) { + if (!this.contentDOM) { return {node: this.dom, offset: 0} } + for (var offset = 0, i = 0;; i++) { + if (offset == pos) { + while (i < this.children.length && (this.children[i].beforePosition || this.children[i].dom.parentNode != this.contentDOM)) { i++; } + return {node: this.contentDOM, + offset: i == this.children.length ? this.contentDOM.childNodes.length : domIndex(this.children[i].dom)} + } + if (i == this.children.length) { throw new Error("Invalid position " + pos) } + var child = this.children[i], end = offset + child.size; + if (pos < end) { return child.domFromPos(pos - offset - child.border) } + offset = end; + } + }; + + // Used to find a DOM range in a single parent for a given changed + // range. + ViewDesc.prototype.parseRange = function parseRange (from, to, base) { + if ( base === void 0 ) base = 0; + + if (this.children.length == 0) + { return {node: this.contentDOM, from: from, to: to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length} } + + var fromOffset = -1, toOffset = -1; + for (var offset = base, i = 0;; i++) { + var child = this.children[i], end = offset + child.size; + if (fromOffset == -1 && from <= end) { + var childBase = offset + child.border; + // FIXME maybe descend mark views to parse a narrower range? + if (from >= childBase && to <= end - child.border && child.node && + child.contentDOM && this.contentDOM.contains(child.contentDOM)) + { return child.parseRange(from, to, childBase) } + + from = offset; + for (var j = i; j > 0; j--) { + var prev = this.children[j - 1]; + if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) { + fromOffset = domIndex(prev.dom) + 1; + break + } + from -= prev.size; + } + if (fromOffset == -1) { fromOffset = 0; } + } + if (fromOffset > -1 && (end > to || i == this.children.length - 1)) { + to = end; + for (var j$1 = i + 1; j$1 < this.children.length; j$1++) { + var next = this.children[j$1]; + if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) { + toOffset = domIndex(next.dom); + break + } + to += next.size; + } + if (toOffset == -1) { toOffset = this.contentDOM.childNodes.length; } + break + } + offset = end; + } + return {node: this.contentDOM, from: from, to: to, fromOffset: fromOffset, toOffset: toOffset} + }; + + ViewDesc.prototype.emptyChildAt = function emptyChildAt (side) { + if (this.border || !this.contentDOM || !this.children.length) { return false } + var child = this.children[side < 0 ? 0 : this.children.length - 1]; + return child.size == 0 || child.emptyChildAt(side) + }; + + // : (number) → dom.Node + ViewDesc.prototype.domAfterPos = function domAfterPos (pos) { + var ref = this.domFromPos(pos); + var node = ref.node; + var offset = ref.offset; + if (node.nodeType != 1 || offset == node.childNodes.length) + { throw new RangeError("No node after pos " + pos) } + return node.childNodes[offset] + }; + + // : (number, number, dom.Document) + // View descs are responsible for setting any selection that falls + // entirely inside of them, so that custom implementations can do + // custom things with the selection. Note that this falls apart when + // a selection starts in such a node and ends in another, in which + // case we just use whatever domFromPos produces as a best effort. + ViewDesc.prototype.setSelection = function setSelection (anchor, head, root, force) { + // If the selection falls entirely in a child, give it to that child + var from = Math.min(anchor, head), to = Math.max(anchor, head); + for (var i = 0, offset = 0; i < this.children.length; i++) { + var child = this.children[i], end = offset + child.size; + if (from > offset && to < end) + { return child.setSelection(anchor - offset - child.border, head - offset - child.border, root, force) } + offset = end; + } + + var anchorDOM = this.domFromPos(anchor), headDOM = this.domFromPos(head); + var domSel = root.getSelection(); + + var brKludge = false; + // On Firefox, using Selection.collapse to put the cursor after a + // BR node for some reason doesn't always work (#1073). On Safari, + // the cursor sometimes inexplicable visually lags behind its + // reported position in such situations (#1092). + if ((result.gecko || result.safari) && anchor == head) { + var prev = anchorDOM.node.childNodes[anchorDOM.offset - 1]; + brKludge = prev && (prev.nodeName == "BR" || prev.contentEditable == "false"); + } + + if (!(force || brKludge && result.safari) && + isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset) && + isEquivalentPosition(headDOM.node, headDOM.offset, domSel.focusNode, domSel.focusOffset)) + { return } + + // Selection.extend can be used to create an 'inverted' selection + // (one where the focus is before the anchor), but not all + // browsers support it yet. + var domSelExtended = false; + if ((domSel.extend || anchor == head) && !brKludge) { + domSel.collapse(anchorDOM.node, anchorDOM.offset); + try { + if (anchor != head) { domSel.extend(headDOM.node, headDOM.offset); } + domSelExtended = true; + } catch (err) { + // In some cases with Chrome the selection is empty after calling + // collapse, even when it should be valid. This appears to be a bug, but + // it is difficult to isolate. If this happens fallback to the old path + // without using extend. + if (!(err instanceof DOMException)) { throw err } + // declare global: DOMException + } + } + if (!domSelExtended) { + if (anchor > head) { var tmp = anchorDOM; anchorDOM = headDOM; headDOM = tmp; } + var range = document.createRange(); + range.setEnd(headDOM.node, headDOM.offset); + range.setStart(anchorDOM.node, anchorDOM.offset); + domSel.removeAllRanges(); + domSel.addRange(range); + } + }; + + // : (dom.MutationRecord) → bool + ViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) { + return !this.contentDOM && mutation.type != "selection" + }; + + prototypeAccessors$9.contentLost.get = function () { + return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM) + }; + + // Remove a subtree of the element tree that has been touched + // by a DOM change, so that the next update will redraw it. + ViewDesc.prototype.markDirty = function markDirty (from, to) { + for (var offset = 0, i = 0; i < this.children.length; i++) { + var child = this.children[i], end = offset + child.size; + if (offset == end ? from <= end && to >= offset : from < end && to > offset) { + var startInside = offset + child.border, endInside = end - child.border; + if (from >= startInside && to <= endInside) { + this.dirty = from == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY; + if (from == startInside && to == endInside && + (child.contentLost || child.dom.parentNode != this.contentDOM)) { child.dirty = NODE_DIRTY; } + else { child.markDirty(from - startInside, to - startInside); } + return + } else { + child.dirty = NODE_DIRTY; + } + } + offset = end; + } + this.dirty = CONTENT_DIRTY; + }; + + ViewDesc.prototype.markParentsDirty = function markParentsDirty () { + var level = 1; + for (var node = this.parent; node; node = node.parent, level++) { + var dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY; + if (node.dirty < dirty) { node.dirty = dirty; } + } + }; + + Object.defineProperties( ViewDesc.prototype, prototypeAccessors$9 ); + + // Reused array to avoid allocating fresh arrays for things that will + // stay empty anyway. + var nothing = []; + + // A widget desc represents a widget decoration, which is a DOM node + // drawn between the document nodes. + var WidgetViewDesc = /*@__PURE__*/(function (ViewDesc) { + function WidgetViewDesc(parent, widget, view, pos) { + var self, dom = widget.type.toDOM; + if (typeof dom == "function") { dom = dom(view, function () { + if (!self) { return pos } + if (self.parent) { return self.parent.posBeforeChild(self) } + }); } + if (!widget.type.spec.raw) { + if (dom.nodeType != 1) { + var wrap = document.createElement("span"); + wrap.appendChild(dom); + dom = wrap; + } + dom.contentEditable = false; + dom.classList.add("ProseMirror-widget"); + } + ViewDesc.call(this, parent, nothing, dom, null); + this.widget = widget; + self = this; + } + + if ( ViewDesc ) WidgetViewDesc.__proto__ = ViewDesc; + WidgetViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype ); + WidgetViewDesc.prototype.constructor = WidgetViewDesc; + + var prototypeAccessors$1 = { beforePosition: { configurable: true } }; + + prototypeAccessors$1.beforePosition.get = function () { + return this.widget.type.side < 0 + }; + + WidgetViewDesc.prototype.matchesWidget = function matchesWidget (widget) { + return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type) + }; + + WidgetViewDesc.prototype.parseRule = function parseRule () { return {ignore: true} }; + + WidgetViewDesc.prototype.stopEvent = function stopEvent (event) { + var stop = this.widget.spec.stopEvent; + return stop ? stop(event) : false + }; + + WidgetViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) { + return mutation.type != "selection" || this.widget.spec.ignoreSelection + }; + + Object.defineProperties( WidgetViewDesc.prototype, prototypeAccessors$1 ); + + return WidgetViewDesc; + }(ViewDesc)); + + var CompositionViewDesc = /*@__PURE__*/(function (ViewDesc) { + function CompositionViewDesc(parent, dom, textDOM, text) { + ViewDesc.call(this, parent, nothing, dom, null); + this.textDOM = textDOM; + this.text = text; + } + + if ( ViewDesc ) CompositionViewDesc.__proto__ = ViewDesc; + CompositionViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype ); + CompositionViewDesc.prototype.constructor = CompositionViewDesc; + + var prototypeAccessors$2 = { size: { configurable: true } }; + + prototypeAccessors$2.size.get = function () { return this.text.length }; + + CompositionViewDesc.prototype.localPosFromDOM = function localPosFromDOM (dom, offset) { + if (dom != this.textDOM) { return this.posAtStart + (offset ? this.size : 0) } + return this.posAtStart + offset + }; + + CompositionViewDesc.prototype.domFromPos = function domFromPos (pos) { + return {node: this.textDOM, offset: pos} + }; + + CompositionViewDesc.prototype.ignoreMutation = function ignoreMutation (mut) { + return mut.type === 'characterData' && mut.target.nodeValue == mut.oldValue + }; + + Object.defineProperties( CompositionViewDesc.prototype, prototypeAccessors$2 ); + + return CompositionViewDesc; + }(ViewDesc)); + + // A mark desc represents a mark. May have multiple children, + // depending on how the mark is split. Note that marks are drawn using + // a fixed nesting order, for simplicity and predictability, so in + // some cases they will be split more often than would appear + // necessary. + var MarkViewDesc = /*@__PURE__*/(function (ViewDesc) { + function MarkViewDesc(parent, mark, dom, contentDOM) { + ViewDesc.call(this, parent, [], dom, contentDOM); + this.mark = mark; + } + + if ( ViewDesc ) MarkViewDesc.__proto__ = ViewDesc; + MarkViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype ); + MarkViewDesc.prototype.constructor = MarkViewDesc; + + MarkViewDesc.create = function create (parent, mark, inline, view) { + var custom = view.nodeViews[mark.type.name]; + var spec = custom && custom(mark, view, inline); + if (!spec || !spec.dom) + { spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline)); } + return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom) + }; + + MarkViewDesc.prototype.parseRule = function parseRule () { return {mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM} }; + + MarkViewDesc.prototype.matchesMark = function matchesMark (mark) { return this.dirty != NODE_DIRTY && this.mark.eq(mark) }; + + MarkViewDesc.prototype.markDirty = function markDirty (from, to) { + ViewDesc.prototype.markDirty.call(this, from, to); + // Move dirty info to nearest node view + if (this.dirty != NOT_DIRTY) { + var parent = this.parent; + while (!parent.node) { parent = parent.parent; } + if (parent.dirty < this.dirty) { parent.dirty = this.dirty; } + this.dirty = NOT_DIRTY; + } + }; + + MarkViewDesc.prototype.slice = function slice (from, to, view) { + var copy = MarkViewDesc.create(this.parent, this.mark, true, view); + var nodes = this.children, size = this.size; + if (to < size) { nodes = replaceNodes(nodes, to, size, view); } + if (from > 0) { nodes = replaceNodes(nodes, 0, from, view); } + for (var i = 0; i < nodes.length; i++) { nodes[i].parent = copy; } + copy.children = nodes; + return copy + }; + + return MarkViewDesc; + }(ViewDesc)); + + // Node view descs are the main, most common type of view desc, and + // correspond to an actual node in the document. Unlike mark descs, + // they populate their child array themselves. + var NodeViewDesc = /*@__PURE__*/(function (ViewDesc) { + function NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) { + ViewDesc.call(this, parent, node.isLeaf ? nothing : [], dom, contentDOM); + this.nodeDOM = nodeDOM; + this.node = node; + this.outerDeco = outerDeco; + this.innerDeco = innerDeco; + if (contentDOM) { this.updateChildren(view, pos); } + } + + if ( ViewDesc ) NodeViewDesc.__proto__ = ViewDesc; + NodeViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype ); + NodeViewDesc.prototype.constructor = NodeViewDesc; + + var prototypeAccessors$3 = { size: { configurable: true },border: { configurable: true } }; + + // By default, a node is rendered using the `toDOM` method from the + // node type spec. But client code can use the `nodeViews` spec to + // supply a custom node view, which can influence various aspects of + // the way the node works. + // + // (Using subclassing for this was intentionally decided against, + // since it'd require exposing a whole slew of finnicky + // implementation details to the user code that they probably will + // never need.) + NodeViewDesc.create = function create (parent, node, outerDeco, innerDeco, view, pos) { + var assign; + + var custom = view.nodeViews[node.type.name], descObj; + var spec = custom && custom(node, view, function () { + // (This is a function that allows the custom view to find its + // own position) + if (!descObj) { return pos } + if (descObj.parent) { return descObj.parent.posBeforeChild(descObj) } + }, outerDeco); + + var dom = spec && spec.dom, contentDOM = spec && spec.contentDOM; + if (node.isText) { + if (!dom) { dom = document.createTextNode(node.text); } + else if (dom.nodeType != 3) { throw new RangeError("Text must be rendered as a DOM text node") } + } else if (!dom) { + ((assign = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node)), dom = assign.dom, contentDOM = assign.contentDOM)); + } + if (!contentDOM && !node.isText && dom.nodeName != "BR") { // Chrome gets confused by
+ if (!dom.hasAttribute("contenteditable")) { dom.contentEditable = false; } + if (node.type.spec.draggable) { dom.draggable = true; } + } + + var nodeDOM = dom; + dom = applyOuterDeco(dom, outerDeco, node); + + if (spec) + { return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, + spec, view, pos + 1) } + else if (node.isText) + { return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) } + else + { return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos + 1) } + }; + + NodeViewDesc.prototype.parseRule = function parseRule () { + var this$1 = this; + + // Experimental kludge to allow opt-in re-parsing of nodes + if (this.node.type.spec.reparseInView) { return null } + // FIXME the assumption that this can always return the current + // attrs means that if the user somehow manages to change the + // attrs in the dom, that won't be picked up. Not entirely sure + // whether this is a problem + var rule = {node: this.node.type.name, attrs: this.node.attrs}; + if (this.node.type.spec.code) { rule.preserveWhitespace = "full"; } + if (this.contentDOM && !this.contentLost) { rule.contentElement = this.contentDOM; } + else { rule.getContent = function () { return this$1.contentDOM ? Fragment.empty : this$1.node.content; }; } + return rule + }; + + NodeViewDesc.prototype.matchesNode = function matchesNode (node, outerDeco, innerDeco) { + return this.dirty == NOT_DIRTY && node.eq(this.node) && + sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco) + }; + + prototypeAccessors$3.size.get = function () { return this.node.nodeSize }; + + prototypeAccessors$3.border.get = function () { return this.node.isLeaf ? 0 : 1 }; + + // Syncs `this.children` to match `this.node.content` and the local + // decorations, possibly introducing nesting for marks. Then, in a + // separate step, syncs the DOM inside `this.contentDOM` to + // `this.children`. + NodeViewDesc.prototype.updateChildren = function updateChildren (view, pos) { + var this$1 = this; + + var inline = this.node.inlineContent, off = pos; + var composition = inline && view.composing && this.localCompositionNode(view, pos); + var updater = new ViewTreeUpdater(this, composition && composition.node); + iterDeco(this.node, this.innerDeco, function (widget, i, insideNode) { + if (widget.spec.marks) + { updater.syncToMarks(widget.spec.marks, inline, view); } + else if (widget.type.side >= 0 && !insideNode) + { updater.syncToMarks(i == this$1.node.childCount ? Mark.none : this$1.node.child(i).marks, inline, view); } + // If the next node is a desc matching this widget, reuse it, + // otherwise insert the widget as a new view desc. + updater.placeWidget(widget, view, off); + }, function (child, outerDeco, innerDeco, i) { + // Make sure the wrapping mark descs match the node's marks. + updater.syncToMarks(child.marks, inline, view); + // Either find an existing desc that exactly matches this node, + // and drop the descs before it. + updater.findNodeMatch(child, outerDeco, innerDeco, i) || + // Or try updating the next desc to reflect this node. + updater.updateNextNode(child, outerDeco, innerDeco, view, i) || + // Or just add it as a new desc. + updater.addNode(child, outerDeco, innerDeco, view, off); + off += child.nodeSize; + }); + // Drop all remaining descs after the current position. + updater.syncToMarks(nothing, inline, view); + if (this.node.isTextblock) { updater.addTextblockHacks(); } + updater.destroyRest(); + + // Sync the DOM if anything changed + if (updater.changed || this.dirty == CONTENT_DIRTY) { + // May have to protect focused DOM from being changed if a composition is active + if (composition) { this.protectLocalComposition(view, composition); } + renderDescs(this.contentDOM, this.children, view); + if (result.ios) { iosHacks(this.dom); } + } + }; + + NodeViewDesc.prototype.localCompositionNode = function localCompositionNode (view, pos) { + // Only do something if both the selection and a focused text node + // are inside of this node, and the node isn't already part of a + // view that's a child of this view + var ref = view.state.selection; + var from = ref.from; + var to = ref.to; + if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size) { return } + var sel = view.root.getSelection(); + var textNode = nearbyTextNode(sel.focusNode, sel.focusOffset); + if (!textNode || !this.dom.contains(textNode.parentNode)) { return } + + // Find the text in the focused node in the node, stop if it's not + // there (may have been modified through other means, in which + // case it should overwritten) + var text = textNode.nodeValue; + var textPos = findTextInFragment(this.node.content, text, from - pos, to - pos); + + return textPos < 0 ? null : {node: textNode, pos: textPos, text: text} + }; + + NodeViewDesc.prototype.protectLocalComposition = function protectLocalComposition (view, ref) { + var node = ref.node; + var pos = ref.pos; + var text = ref.text; + + // The node is already part of a local view desc, leave it there + if (this.getDesc(node)) { return } + + // Create a composition view for the orphaned nodes + var topNode = node; + for (;; topNode = topNode.parentNode) { + if (topNode.parentNode == this.contentDOM) { break } + while (topNode.previousSibling) { topNode.parentNode.removeChild(topNode.previousSibling); } + while (topNode.nextSibling) { topNode.parentNode.removeChild(topNode.nextSibling); } + if (topNode.pmViewDesc) { topNode.pmViewDesc = null; } + } + var desc = new CompositionViewDesc(this, topNode, node, text); + view.compositionNodes.push(desc); + + // Patch up this.children to contain the composition view + this.children = replaceNodes(this.children, pos, pos + text.length, view, desc); + }; + + // : (Node, [Decoration], DecorationSet, EditorView) → bool + // If this desc be updated to match the given node decoration, + // do so and return true. + NodeViewDesc.prototype.update = function update (node, outerDeco, innerDeco, view) { + if (this.dirty == NODE_DIRTY || + !node.sameMarkup(this.node)) { return false } + this.updateInner(node, outerDeco, innerDeco, view); + return true + }; + + NodeViewDesc.prototype.updateInner = function updateInner (node, outerDeco, innerDeco, view) { + this.updateOuterDeco(outerDeco); + this.node = node; + this.innerDeco = innerDeco; + if (this.contentDOM) { this.updateChildren(view, this.posAtStart); } + this.dirty = NOT_DIRTY; + }; + + NodeViewDesc.prototype.updateOuterDeco = function updateOuterDeco (outerDeco) { + if (sameOuterDeco(outerDeco, this.outerDeco)) { return } + var needsWrap = this.nodeDOM.nodeType != 1; + var oldDOM = this.dom; + this.dom = patchOuterDeco(this.dom, this.nodeDOM, + computeOuterDeco(this.outerDeco, this.node, needsWrap), + computeOuterDeco(outerDeco, this.node, needsWrap)); + if (this.dom != oldDOM) { + oldDOM.pmViewDesc = null; + this.dom.pmViewDesc = this; + } + this.outerDeco = outerDeco; + }; + + // Mark this node as being the selected node. + NodeViewDesc.prototype.selectNode = function selectNode () { + this.nodeDOM.classList.add("ProseMirror-selectednode"); + if (this.contentDOM || !this.node.type.spec.draggable) { this.dom.draggable = true; } + }; + + // Remove selected node marking from this node. + NodeViewDesc.prototype.deselectNode = function deselectNode () { + this.nodeDOM.classList.remove("ProseMirror-selectednode"); + if (this.contentDOM || !this.node.type.spec.draggable) { this.dom.removeAttribute("draggable"); } + }; + + Object.defineProperties( NodeViewDesc.prototype, prototypeAccessors$3 ); + + return NodeViewDesc; + }(ViewDesc)); + + // Create a view desc for the top-level document node, to be exported + // and used by the view class. + function docViewDesc(doc, outerDeco, innerDeco, dom, view) { + applyOuterDeco(dom, outerDeco, doc); + return new NodeViewDesc(null, doc, outerDeco, innerDeco, dom, dom, dom, view, 0) + } + + var TextViewDesc = /*@__PURE__*/(function (NodeViewDesc) { + function TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) { + NodeViewDesc.call(this, parent, node, outerDeco, innerDeco, dom, null, nodeDOM, view); + } + + if ( NodeViewDesc ) TextViewDesc.__proto__ = NodeViewDesc; + TextViewDesc.prototype = Object.create( NodeViewDesc && NodeViewDesc.prototype ); + TextViewDesc.prototype.constructor = TextViewDesc; + + TextViewDesc.prototype.parseRule = function parseRule () { + var skip = this.nodeDOM.parentNode; + while (skip && skip != this.dom && !skip.pmIsDeco) { skip = skip.parentNode; } + return {skip: skip || true} + }; + + TextViewDesc.prototype.update = function update (node, outerDeco, _, view) { + if (this.dirty == NODE_DIRTY || (this.dirty != NOT_DIRTY && !this.inParent()) || + !node.sameMarkup(this.node)) { return false } + this.updateOuterDeco(outerDeco); + if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) { + this.nodeDOM.nodeValue = node.text; + if (view.trackWrites == this.nodeDOM) { view.trackWrites = null; } + } + this.node = node; + this.dirty = NOT_DIRTY; + return true + }; + + TextViewDesc.prototype.inParent = function inParent () { + var parentDOM = this.parent.contentDOM; + for (var n = this.nodeDOM; n; n = n.parentNode) { if (n == parentDOM) { return true } } + return false + }; + + TextViewDesc.prototype.domFromPos = function domFromPos (pos) { + return {node: this.nodeDOM, offset: pos} + }; + + TextViewDesc.prototype.localPosFromDOM = function localPosFromDOM (dom, offset, bias) { + if (dom == this.nodeDOM) { return this.posAtStart + Math.min(offset, this.node.text.length) } + return NodeViewDesc.prototype.localPosFromDOM.call(this, dom, offset, bias) + }; + + TextViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) { + return mutation.type != "characterData" && mutation.type != "selection" + }; + + TextViewDesc.prototype.slice = function slice (from, to, view) { + var node = this.node.cut(from, to), dom = document.createTextNode(node.text); + return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view) + }; + + return TextViewDesc; + }(NodeViewDesc)); + + // A dummy desc used to tag trailing BR or span nodes created to work + // around contentEditable terribleness. + var BRHackViewDesc = /*@__PURE__*/(function (ViewDesc) { + function BRHackViewDesc () { + ViewDesc.apply(this, arguments); + } + + if ( ViewDesc ) BRHackViewDesc.__proto__ = ViewDesc; + BRHackViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype ); + BRHackViewDesc.prototype.constructor = BRHackViewDesc; + + BRHackViewDesc.prototype.parseRule = function parseRule () { return {ignore: true} }; + BRHackViewDesc.prototype.matchesHack = function matchesHack () { return this.dirty == NOT_DIRTY }; + + return BRHackViewDesc; + }(ViewDesc)); + + // A separate subclass is used for customized node views, so that the + // extra checks only have to be made for nodes that are actually + // customized. + var CustomNodeViewDesc = /*@__PURE__*/(function (NodeViewDesc) { + function CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) { + NodeViewDesc.call(this, parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos); + this.spec = spec; + } + + if ( NodeViewDesc ) CustomNodeViewDesc.__proto__ = NodeViewDesc; + CustomNodeViewDesc.prototype = Object.create( NodeViewDesc && NodeViewDesc.prototype ); + CustomNodeViewDesc.prototype.constructor = CustomNodeViewDesc; + + // A custom `update` method gets to decide whether the update goes + // through. If it does, and there's a `contentDOM` node, our logic + // updates the children. + CustomNodeViewDesc.prototype.update = function update (node, outerDeco, innerDeco, view) { + if (this.dirty == NODE_DIRTY) { return false } + if (this.spec.update) { + var result = this.spec.update(node, outerDeco); + if (result) { this.updateInner(node, outerDeco, innerDeco, view); } + return result + } else if (!this.contentDOM && !node.isLeaf) { + return false + } else { + return NodeViewDesc.prototype.update.call(this, node, outerDeco, innerDeco, view) + } + }; + + CustomNodeViewDesc.prototype.selectNode = function selectNode () { + this.spec.selectNode ? this.spec.selectNode() : NodeViewDesc.prototype.selectNode.call(this); + }; + + CustomNodeViewDesc.prototype.deselectNode = function deselectNode () { + this.spec.deselectNode ? this.spec.deselectNode() : NodeViewDesc.prototype.deselectNode.call(this); + }; + + CustomNodeViewDesc.prototype.setSelection = function setSelection (anchor, head, root, force) { + this.spec.setSelection ? this.spec.setSelection(anchor, head, root) + : NodeViewDesc.prototype.setSelection.call(this, anchor, head, root, force); + }; + + CustomNodeViewDesc.prototype.destroy = function destroy () { + if (this.spec.destroy) { this.spec.destroy(); } + NodeViewDesc.prototype.destroy.call(this); + }; + + CustomNodeViewDesc.prototype.stopEvent = function stopEvent (event) { + return this.spec.stopEvent ? this.spec.stopEvent(event) : false + }; + + CustomNodeViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) { + return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : NodeViewDesc.prototype.ignoreMutation.call(this, mutation) + }; + + return CustomNodeViewDesc; + }(NodeViewDesc)); + + // : (dom.Node, [ViewDesc]) + // Sync the content of the given DOM node with the nodes associated + // with the given array of view descs, recursing into mark descs + // because this should sync the subtree for a whole node at a time. + function renderDescs(parentDOM, descs, view) { + var dom = parentDOM.firstChild, written = false; + for (var i = 0; i < descs.length; i++) { + var desc = descs[i], childDOM = desc.dom; + if (childDOM.parentNode == parentDOM) { + while (childDOM != dom) { dom = rm(dom); written = true; } + dom = dom.nextSibling; + } else { + written = true; + parentDOM.insertBefore(childDOM, dom); + } + if (desc instanceof MarkViewDesc) { + var pos = dom ? dom.previousSibling : parentDOM.lastChild; + renderDescs(desc.contentDOM, desc.children, view); + dom = pos ? pos.nextSibling : parentDOM.firstChild; + } + } + while (dom) { dom = rm(dom); written = true; } + if (written && view.trackWrites == parentDOM) { view.trackWrites = null; } + } + + function OuterDecoLevel(nodeName) { + if (nodeName) { this.nodeName = nodeName; } + } + OuterDecoLevel.prototype = Object.create(null); + + var noDeco = [new OuterDecoLevel]; + + function computeOuterDeco(outerDeco, node, needsWrap) { + if (outerDeco.length == 0) { return noDeco } + + var top = needsWrap ? noDeco[0] : new OuterDecoLevel, result = [top]; + + for (var i = 0; i < outerDeco.length; i++) { + var attrs = outerDeco[i].type.attrs, cur = top; + if (!attrs) { continue } + if (attrs.nodeName) + { result.push(cur = new OuterDecoLevel(attrs.nodeName)); } + + for (var name in attrs) { + var val = attrs[name]; + if (val == null) { continue } + if (needsWrap && result.length == 1) + { result.push(cur = top = new OuterDecoLevel(node.isInline ? "span" : "div")); } + if (name == "class") { cur.class = (cur.class ? cur.class + " " : "") + val; } + else if (name == "style") { cur.style = (cur.style ? cur.style + ";" : "") + val; } + else if (name != "nodeName") { cur[name] = val; } + } + } + + return result + } + + function patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) { + // Shortcut for trivial case + if (prevComputed == noDeco && curComputed == noDeco) { return nodeDOM } + + var curDOM = nodeDOM; + for (var i = 0; i < curComputed.length; i++) { + var deco = curComputed[i], prev = prevComputed[i]; + if (i) { + var parent = (void 0); + if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM && + (parent = curDOM.parentNode) && parent.tagName.toLowerCase() == deco.nodeName) { + curDOM = parent; + } else { + parent = document.createElement(deco.nodeName); + parent.pmIsDeco = true; + parent.appendChild(curDOM); + prev = noDeco[0]; + curDOM = parent; + } + } + patchAttributes(curDOM, prev || noDeco[0], deco); + } + return curDOM + } + + function patchAttributes(dom, prev, cur) { + for (var name in prev) + { if (name != "class" && name != "style" && name != "nodeName" && !(name in cur)) + { dom.removeAttribute(name); } } + for (var name$1 in cur) + { if (name$1 != "class" && name$1 != "style" && name$1 != "nodeName" && cur[name$1] != prev[name$1]) + { dom.setAttribute(name$1, cur[name$1]); } } + if (prev.class != cur.class) { + var prevList = prev.class ? prev.class.split(" ") : nothing; + var curList = cur.class ? cur.class.split(" ") : nothing; + for (var i = 0; i < prevList.length; i++) { if (curList.indexOf(prevList[i]) == -1) + { dom.classList.remove(prevList[i]); } } + for (var i$1 = 0; i$1 < curList.length; i$1++) { if (prevList.indexOf(curList[i$1]) == -1) + { dom.classList.add(curList[i$1]); } } + } + if (prev.style != cur.style) { + if (prev.style) { + var prop = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g, m; + while (m = prop.exec(prev.style)) + { dom.style.removeProperty(m[1]); } + } + if (cur.style) + { dom.style.cssText += cur.style; } + } + } + + function applyOuterDeco(dom, deco, node) { + return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1)) + } + + // : ([Decoration], [Decoration]) → bool + function sameOuterDeco(a, b) { + if (a.length != b.length) { return false } + for (var i = 0; i < a.length; i++) { if (!a[i].type.eq(b[i].type)) { return false } } + return true + } + + // Remove a DOM node and return its next sibling. + function rm(dom) { + var next = dom.nextSibling; + dom.parentNode.removeChild(dom); + return next + } + + // Helper class for incrementally updating a tree of mark descs and + // the widget and node descs inside of them. + var ViewTreeUpdater = function ViewTreeUpdater(top, lockedNode) { + this.top = top; + this.lock = lockedNode; + // Index into `this.top`'s child array, represents the current + // update position. + this.index = 0; + // When entering a mark, the current top and index are pushed + // onto this. + this.stack = []; + // Tracks whether anything was changed + this.changed = false; + + var pre = preMatch(top.node.content, top.children); + this.preMatched = pre.nodes; + this.preMatchOffset = pre.offset; + }; + + ViewTreeUpdater.prototype.getPreMatch = function getPreMatch (index) { + return index >= this.preMatchOffset ? this.preMatched[index - this.preMatchOffset] : null + }; + + // Destroy and remove the children between the given indices in + // `this.top`. + ViewTreeUpdater.prototype.destroyBetween = function destroyBetween (start, end) { + if (start == end) { return } + for (var i = start; i < end; i++) { this.top.children[i].destroy(); } + this.top.children.splice(start, end - start); + this.changed = true; + }; + + // Destroy all remaining children in `this.top`. + ViewTreeUpdater.prototype.destroyRest = function destroyRest () { + this.destroyBetween(this.index, this.top.children.length); + }; + + // : ([Mark], EditorView) + // Sync the current stack of mark descs with the given array of + // marks, reusing existing mark descs when possible. + ViewTreeUpdater.prototype.syncToMarks = function syncToMarks (marks, inline, view) { + var keep = 0, depth = this.stack.length >> 1; + var maxKeep = Math.min(depth, marks.length); + while (keep < maxKeep && + (keep == depth - 1 ? this.top : this.stack[(keep + 1) << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false) + { keep++; } + + while (keep < depth) { + this.destroyRest(); + this.top.dirty = NOT_DIRTY; + this.index = this.stack.pop(); + this.top = this.stack.pop(); + depth--; + } + while (depth < marks.length) { + this.stack.push(this.top, this.index + 1); + var found = -1; + for (var i = this.index; i < Math.min(this.index + 3, this.top.children.length); i++) { + if (this.top.children[i].matchesMark(marks[depth])) { found = i; break } + } + if (found > -1) { + if (found > this.index) { + this.changed = true; + this.destroyBetween(this.index, found); + } + this.top = this.top.children[this.index]; + } else { + var markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view); + this.top.children.splice(this.index, 0, markDesc); + this.top = markDesc; + this.changed = true; + } + this.index = 0; + depth++; + } + }; + + // : (Node, [Decoration], DecorationSet) → bool + // Try to find a node desc matching the given data. Skip over it and + // return true when successful. + ViewTreeUpdater.prototype.findNodeMatch = function findNodeMatch (node, outerDeco, innerDeco, index) { + var found = -1, preMatch = index < 0 ? undefined : this.getPreMatch(index), children = this.top.children; + if (preMatch && preMatch.matchesNode(node, outerDeco, innerDeco)) { + found = children.indexOf(preMatch); + } else { + for (var i = this.index, e = Math.min(children.length, i + 5); i < e; i++) { + var child = children[i]; + if (child.matchesNode(node, outerDeco, innerDeco) && this.preMatched.indexOf(child) < 0) { + found = i; + break + } + } + } + if (found < 0) { return false } + this.destroyBetween(this.index, found); + this.index++; + return true + }; + + // : (Node, [Decoration], DecorationSet, EditorView, Fragment, number) → bool + // Try to update the next node, if any, to the given data. Checks + // pre-matches to avoid overwriting nodes that could still be used. + ViewTreeUpdater.prototype.updateNextNode = function updateNextNode (node, outerDeco, innerDeco, view, index) { + for (var i = this.index; i < this.top.children.length; i++) { + var next = this.top.children[i]; + if (next instanceof NodeViewDesc) { + var preMatch = this.preMatched.indexOf(next); + if (preMatch > -1 && preMatch + this.preMatchOffset != index) { return false } + var nextDOM = next.dom; + + // Can't update if nextDOM is or contains this.lock, except if + // it's a text node whose content already matches the new text + // and whose decorations match the new ones. + var locked = this.lock && (nextDOM == this.lock || nextDOM.nodeType == 1 && nextDOM.contains(this.lock.parentNode)) && + !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text && + next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco)); + if (!locked && next.update(node, outerDeco, innerDeco, view)) { + this.destroyBetween(this.index, i); + if (next.dom != nextDOM) { this.changed = true; } + this.index++; + return true + } + break + } + } + return false + }; + + // : (Node, [Decoration], DecorationSet, EditorView) + // Insert the node as a newly created node desc. + ViewTreeUpdater.prototype.addNode = function addNode (node, outerDeco, innerDeco, view, pos) { + this.top.children.splice(this.index++, 0, NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos)); + this.changed = true; + }; + + ViewTreeUpdater.prototype.placeWidget = function placeWidget (widget, view, pos) { + var next = this.index < this.top.children.length ? this.top.children[this.index] : null; + if (next && next.matchesWidget(widget) && (widget == next.widget || !next.widget.type.toDOM.parentNode)) { + this.index++; + } else { + var desc = new WidgetViewDesc(this.top, widget, view, pos); + this.top.children.splice(this.index++, 0, desc); + this.changed = true; + } + }; + + // Make sure a textblock looks and behaves correctly in + // contentEditable. + ViewTreeUpdater.prototype.addTextblockHacks = function addTextblockHacks () { + var lastChild = this.top.children[this.index - 1]; + while (lastChild instanceof MarkViewDesc) { lastChild = lastChild.children[lastChild.children.length - 1]; } + + if (!lastChild || // Empty textblock + !(lastChild instanceof TextViewDesc) || + /\n$/.test(lastChild.node.text)) { + if (this.index < this.top.children.length && this.top.children[this.index].matchesHack()) { + this.index++; + } else { + var dom = document.createElement("br"); + this.top.children.splice(this.index++, 0, new BRHackViewDesc(this.top, nothing, dom, null)); + this.changed = true; + } + } + }; + + // : (Fragment, [ViewDesc]) → [ViewDesc] + // Iterate from the end of the fragment and array of descs to find + // directly matching ones, in order to avoid overeagerly reusing + // those for other nodes. Returns an array whose positions correspond + // to node positions in the fragment, and whose elements are either + // descs matched to the child at that index, or empty. + function preMatch(frag, descs) { + var result = [], end = frag.childCount; + for (var i = descs.length - 1; end > 0 && i >= 0; i--) { + var desc = descs[i], node = desc.node; + if (!node) { continue } + if (node != frag.child(end - 1)) { break } + result.push(desc); + --end; + } + return {nodes: result.reverse(), offset: end} + } + + function compareSide(a, b) { return a.type.side - b.type.side } + + // : (ViewDesc, DecorationSet, (Decoration, number), (Node, [Decoration], DecorationSet, number)) + // This function abstracts iterating over the nodes and decorations in + // a fragment. Calls `onNode` for each node, with its local and child + // decorations. Splits text nodes when there is a decoration starting + // or ending inside of them. Calls `onWidget` for each widget. + function iterDeco(parent, deco, onWidget, onNode) { + var locals = deco.locals(parent), offset = 0; + // Simple, cheap variant for when there are no local decorations + if (locals.length == 0) { + for (var i = 0; i < parent.childCount; i++) { + var child = parent.child(i); + onNode(child, locals, deco.forChild(offset, child), i); + offset += child.nodeSize; + } + return + } + + var decoIndex = 0, active = [], restNode = null; + for (var parentIndex = 0;;) { + if (decoIndex < locals.length && locals[decoIndex].to == offset) { + var widget = locals[decoIndex++], widgets = (void 0); + while (decoIndex < locals.length && locals[decoIndex].to == offset) + { (widgets || (widgets = [widget])).push(locals[decoIndex++]); } + if (widgets) { + widgets.sort(compareSide); + for (var i$1 = 0; i$1 < widgets.length; i$1++) { onWidget(widgets[i$1], parentIndex, !!restNode); } + } else { + onWidget(widget, parentIndex, !!restNode); + } + } + + var child$1 = (void 0), index = (void 0); + if (restNode) { + index = -1; + child$1 = restNode; + restNode = null; + } else if (parentIndex < parent.childCount) { + index = parentIndex; + child$1 = parent.child(parentIndex++); + } else { + break + } + + for (var i$2 = 0; i$2 < active.length; i$2++) { if (active[i$2].to <= offset) { active.splice(i$2--, 1); } } + while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset) + { active.push(locals[decoIndex++]); } + + var end = offset + child$1.nodeSize; + if (child$1.isText) { + var cutAt = end; + if (decoIndex < locals.length && locals[decoIndex].from < cutAt) { cutAt = locals[decoIndex].from; } + for (var i$3 = 0; i$3 < active.length; i$3++) { if (active[i$3].to < cutAt) { cutAt = active[i$3].to; } } + if (cutAt < end) { + restNode = child$1.cut(cutAt - offset); + child$1 = child$1.cut(0, cutAt - offset); + end = cutAt; + index = -1; + } + } + + var outerDeco = !active.length ? nothing + : child$1.isInline && !child$1.isLeaf ? active.filter(function (d) { return !d.inline; }) + : active.slice(); + onNode(child$1, outerDeco, deco.forChild(offset, child$1), index); + offset = end; + } + } + + // List markers in Mobile Safari will mysteriously disappear + // sometimes. This works around that. + function iosHacks(dom) { + if (dom.nodeName == "UL" || dom.nodeName == "OL") { + var oldCSS = dom.style.cssText; + dom.style.cssText = oldCSS + "; list-style: square !important"; + window.getComputedStyle(dom).listStyle; + dom.style.cssText = oldCSS; + } + } + + function nearbyTextNode(node, offset) { + for (;;) { + if (node.nodeType == 3) { return node } + if (node.nodeType == 1 && offset > 0) { + if (node.childNodes.length > offset && node.childNodes[offset].nodeType == 3) + { return node.childNodes[offset] } + node = node.childNodes[offset - 1]; + offset = nodeSize(node); + } else if (node.nodeType == 1 && offset < node.childNodes.length) { + node = node.childNodes[offset]; + offset = 0; + } else { + return null + } + } + } + + // Find a piece of text in an inline fragment, overlapping from-to + function findTextInFragment(frag, text, from, to) { + for (var i = 0, pos = 0; i < frag.childCount && pos <= to;) { + var child = frag.child(i++), childStart = pos; + pos += child.nodeSize; + if (!child.isText) { continue } + var str = child.text; + while (i < frag.childCount) { + var next = frag.child(i++); + pos += next.nodeSize; + if (!next.isText) { break } + str += next.text; + } + if (pos >= from) { + var found = str.lastIndexOf(text, to - childStart); + if (found >= 0 && found + text.length + childStart >= from) + { return childStart + found } + } + } + return -1 + } + + // Replace range from-to in an array of view descs with replacement + // (may be null to just delete). This goes very much against the grain + // of the rest of this code, which tends to create nodes with the + // right shape in one go, rather than messing with them after + // creation, but is necessary in the composition hack. + function replaceNodes(nodes, from, to, view, replacement) { + var result = []; + for (var i = 0, off = 0; i < nodes.length; i++) { + var child = nodes[i], start = off, end = off += child.size; + if (start >= to || end <= from) { + result.push(child); + } else { + if (start < from) { result.push(child.slice(0, from - start, view)); } + if (replacement) { + result.push(replacement); + replacement = null; + } + if (end > to) { result.push(child.slice(to - start, child.size, view)); } + } + } + return result + } + + function selectionFromDOM(view, origin) { + var domSel = view.root.getSelection(), doc = view.state.doc; + if (!domSel.focusNode) { return null } + var nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0; + var head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset); + if (head < 0) { return null } + var $head = doc.resolve(head), $anchor, selection; + if (selectionCollapsed(domSel)) { + $anchor = $head; + while (nearestDesc && !nearestDesc.node) { nearestDesc = nearestDesc.parent; } + if (nearestDesc && nearestDesc.node.isAtom && NodeSelection.isSelectable(nearestDesc.node) && nearestDesc.parent + && !(nearestDesc.node.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) { + var pos = nearestDesc.posBefore; + selection = new NodeSelection(head == pos ? $head : doc.resolve(pos)); + } + } else { + var anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset); + if (anchor < 0) { return null } + $anchor = doc.resolve(anchor); + } + + if (!selection) { + var bias = origin == "pointer" || (view.state.selection.head < $head.pos && !inWidget) ? 1 : -1; + selection = selectionBetween(view, $anchor, $head, bias); + } + return selection + } + + function selectionToDOM(view, force) { + var sel = view.state.selection; + syncNodeSelection(view, sel); + + if (view.editable ? !view.hasFocus() : + !(hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom))) { return } + + view.domObserver.disconnectSelection(); + + if (view.cursorWrapper) { + selectCursorWrapper(view); + } else { + var anchor = sel.anchor; + var head = sel.head; + var resetEditableFrom, resetEditableTo; + if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) { + if (!sel.$from.parent.inlineContent) + { resetEditableFrom = temporarilyEditableNear(view, sel.from); } + if (!sel.empty && !sel.$from.parent.inlineContent) + { resetEditableTo = temporarilyEditableNear(view, sel.to); } + } + view.docView.setSelection(anchor, head, view.root, force); + if (brokenSelectBetweenUneditable) { + if (resetEditableFrom) { resetEditable(resetEditableFrom); } + if (resetEditableTo) { resetEditable(resetEditableTo); } + } + if (sel.visible) { + view.dom.classList.remove("ProseMirror-hideselection"); + } else { + view.dom.classList.add("ProseMirror-hideselection"); + if ("onselectionchange" in document) { removeClassOnSelectionChange(view); } + } + } + + view.domObserver.setCurSelection(); + view.domObserver.connectSelection(); + } + + // Kludge to work around Webkit not allowing a selection to start/end + // between non-editable block nodes. We briefly make something + // editable, set the selection, then set it uneditable again. + + var brokenSelectBetweenUneditable = result.safari || result.chrome && result.chrome_version < 63; + + function temporarilyEditableNear(view, pos) { + var ref = view.docView.domFromPos(pos); + var node = ref.node; + var offset = ref.offset; + var after = offset < node.childNodes.length ? node.childNodes[offset] : null; + var before = offset ? node.childNodes[offset - 1] : null; + if (result.safari && after && after.contentEditable == "false") { return setEditable(after) } + if ((!after || after.contentEditable == "false") && (!before || before.contentEditable == "false")) { + if (after) { return setEditable(after) } + else if (before) { return setEditable(before) } + } + } + + function setEditable(element) { + element.contentEditable = "true"; + if (result.safari && element.draggable) { element.draggable = false; element.wasDraggable = true; } + return element + } + + function resetEditable(element) { + element.contentEditable = "false"; + if (element.wasDraggable) { element.draggable = true; element.wasDraggable = null; } + } + + function removeClassOnSelectionChange(view) { + var doc = view.dom.ownerDocument; + doc.removeEventListener("selectionchange", view.hideSelectionGuard); + var domSel = view.root.getSelection(); + var node = domSel.anchorNode, offset = domSel.anchorOffset; + doc.addEventListener("selectionchange", view.hideSelectionGuard = function () { + if (domSel.anchorNode != node || domSel.anchorOffset != offset) { + doc.removeEventListener("selectionchange", view.hideSelectionGuard); + view.dom.classList.remove("ProseMirror-hideselection"); + } + }); + } + + function selectCursorWrapper(view) { + var domSel = view.root.getSelection(), range = document.createRange(); + var node = view.cursorWrapper.dom, img = node.nodeName == "IMG"; + if (img) { range.setEnd(node.parentNode, domIndex(node) + 1); } + else { range.setEnd(node, 0); } + range.collapse(false); + domSel.removeAllRanges(); + domSel.addRange(range); + // Kludge to kill 'control selection' in IE11 when selecting an + // invisible cursor wrapper, since that would result in those weird + // resize handles and a selection that considers the absolutely + // positioned wrapper, rather than the root editable node, the + // focused element. + if (!img && !view.state.selection.visible && result.ie && result.ie_version <= 11) { + node.disabled = true; + node.disabled = false; + } + } + + function syncNodeSelection(view, sel) { + if (sel instanceof NodeSelection) { + var desc = view.docView.descAt(sel.from); + if (desc != view.lastSelectedViewDesc) { + clearNodeSelection(view); + if (desc) { desc.selectNode(); } + view.lastSelectedViewDesc = desc; + } + } else { + clearNodeSelection(view); + } + } + + // Clear all DOM statefulness of the last node selection. + function clearNodeSelection(view) { + if (view.lastSelectedViewDesc) { + if (view.lastSelectedViewDesc.parent) + { view.lastSelectedViewDesc.deselectNode(); } + view.lastSelectedViewDesc = null; + } + } + + function selectionBetween(view, $anchor, $head, bias) { + return view.someProp("createSelectionBetween", function (f) { return f(view, $anchor, $head); }) + || TextSelection.between($anchor, $head, bias) + } + + function hasFocusAndSelection(view) { + if (view.editable && view.root.activeElement != view.dom) { return false } + return hasSelection(view) + } + + function hasSelection(view) { + var sel = view.root.getSelection(); + if (!sel.anchorNode) { return false } + try { + // Firefox will raise 'permission denied' errors when accessing + // properties of `sel.anchorNode` when it's in a generated CSS + // element. + return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) && + (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode)) + } catch(_) { + return false + } + } + + function anchorInRightPlace(view) { + var anchorDOM = view.docView.domFromPos(view.state.selection.anchor); + var domSel = view.root.getSelection(); + return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset) + } + + function moveSelectionBlock(state, dir) { + var ref = state.selection; + var $anchor = ref.$anchor; + var $head = ref.$head; + var $side = dir > 0 ? $anchor.max($head) : $anchor.min($head); + var $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null; + return $start && Selection.findFrom($start, dir) + } + + function apply(view, sel) { + view.dispatch(view.state.tr.setSelection(sel).scrollIntoView()); + return true + } + + function selectHorizontally(view, dir, mods) { + var sel = view.state.selection; + if (sel instanceof TextSelection) { + if (!sel.empty || mods.indexOf("s") > -1) { + return false + } else if (view.endOfTextblock(dir > 0 ? "right" : "left")) { + var next = moveSelectionBlock(view.state, dir); + if (next && (next instanceof NodeSelection)) { return apply(view, next) } + return false + } else if (!(result.mac && mods.indexOf("m") > -1)) { + var $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc; + if (!node || node.isText) { return false } + var nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos; + if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM)) { return false } + if (NodeSelection.isSelectable(node)) { + return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head)) + } else if (result.webkit) { + // Chrome and Safari will introduce extra pointless cursor + // positions around inline uneditable nodes, so we have to + // take over and move the cursor past them (#937) + return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize))) + } else { + return false + } + } + } else if (sel instanceof NodeSelection && sel.node.isInline) { + return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from)) + } else { + var next$1 = moveSelectionBlock(view.state, dir); + if (next$1) { return apply(view, next$1) } + return false + } + } + + function nodeLen(node) { + return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length + } + + function isIgnorable(dom) { + var desc = dom.pmViewDesc; + return desc && desc.size == 0 && (dom.nextSibling || dom.nodeName != "BR") + } + + // Make sure the cursor isn't directly after one or more ignored + // nodes, which will confuse the browser's cursor motion logic. + function skipIgnoredNodesLeft(view) { + var sel = view.root.getSelection(); + var node = sel.focusNode, offset = sel.focusOffset; + if (!node) { return } + var moveNode, moveOffset, force = false; + // Gecko will do odd things when the selection is directly in front + // of a non-editable node, so in that case, move it into the next + // node if possible. Issue prosemirror/prosemirror#832. + if (result.gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset])) { force = true; } + for (;;) { + if (offset > 0) { + if (node.nodeType != 1) { + break + } else { + var before = node.childNodes[offset - 1]; + if (isIgnorable(before)) { + moveNode = node; + moveOffset = --offset; + } else if (before.nodeType == 3) { + node = before; + offset = node.nodeValue.length; + } else { break } + } + } else if (isBlockNode(node)) { + break + } else { + var prev = node.previousSibling; + while (prev && isIgnorable(prev)) { + moveNode = node.parentNode; + moveOffset = domIndex(prev); + prev = prev.previousSibling; + } + if (!prev) { + node = node.parentNode; + if (node == view.dom) { break } + offset = 0; + } else { + node = prev; + offset = nodeLen(node); + } + } + } + if (force) { setSelFocus(view, sel, node, offset); } + else if (moveNode) { setSelFocus(view, sel, moveNode, moveOffset); } + } + + // Make sure the cursor isn't directly before one or more ignored + // nodes. + function skipIgnoredNodesRight(view) { + var sel = view.root.getSelection(); + var node = sel.focusNode, offset = sel.focusOffset; + if (!node) { return } + var len = nodeLen(node); + var moveNode, moveOffset; + for (;;) { + if (offset < len) { + if (node.nodeType != 1) { break } + var after = node.childNodes[offset]; + if (isIgnorable(after)) { + moveNode = node; + moveOffset = ++offset; + } + else { break } + } else if (isBlockNode(node)) { + break + } else { + var next = node.nextSibling; + while (next && isIgnorable(next)) { + moveNode = next.parentNode; + moveOffset = domIndex(next) + 1; + next = next.nextSibling; + } + if (!next) { + node = node.parentNode; + if (node == view.dom) { break } + offset = len = 0; + } else { + node = next; + offset = 0; + len = nodeLen(node); + } + } + } + if (moveNode) { setSelFocus(view, sel, moveNode, moveOffset); } + } + + function isBlockNode(dom) { + var desc = dom.pmViewDesc; + return desc && desc.node && desc.node.isBlock + } + + function setSelFocus(view, sel, node, offset) { + if (selectionCollapsed(sel)) { + var range = document.createRange(); + range.setEnd(node, offset); + range.setStart(node, offset); + sel.removeAllRanges(); + sel.addRange(range); + } else if (sel.extend) { + sel.extend(node, offset); + } + view.domObserver.setCurSelection(); + var state = view.state; + // If no state update ends up happening, reset the selection. + setTimeout(function () { + if (view.state == state) { selectionToDOM(view); } + }, 50); + } + + // : (EditorState, number) + // Check whether vertical selection motion would involve node + // selections. If so, apply it (if not, the result is left to the + // browser) + function selectVertically(view, dir, mods) { + var sel = view.state.selection; + if (sel instanceof TextSelection && !sel.empty || mods.indexOf("s") > -1) { return false } + if (result.mac && mods.indexOf("m") > -1) { return false } + var $from = sel.$from; + var $to = sel.$to; + + if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? "up" : "down")) { + var next = moveSelectionBlock(view.state, dir); + if (next && (next instanceof NodeSelection)) + { return apply(view, next) } + } + if (!$from.parent.inlineContent) { + var beyond = Selection.findFrom(dir < 0 ? $from : $to, dir); + return beyond ? apply(view, beyond) : true + } + return false + } + + function stopNativeHorizontalDelete(view, dir) { + if (!(view.state.selection instanceof TextSelection)) { return true } + var ref = view.state.selection; + var $head = ref.$head; + var $anchor = ref.$anchor; + var empty = ref.empty; + if (!$head.sameParent($anchor)) { return true } + if (!empty) { return false } + if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) { return true } + var nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter); + if (nextNode && !nextNode.isText) { + var tr = view.state.tr; + if (dir < 0) { tr.delete($head.pos - nextNode.nodeSize, $head.pos); } + else { tr.delete($head.pos, $head.pos + nextNode.nodeSize); } + view.dispatch(tr); + return true + } + return false + } + + function switchEditable(view, node, state) { + view.domObserver.stop(); + node.contentEditable = state; + view.domObserver.start(); + } + + // Issue #867 / #1090 / https://bugs.chromium.org/p/chromium/issues/detail?id=903821 + // In which Safari (and at some point in the past, Chrome) does really + // wrong things when the down arrow is pressed when the cursor is + // directly at the start of a textblock and has an uneditable node + // after it + function safariDownArrowBug(view) { + if (!result.safari || view.state.selection.$head.parentOffset > 0) { return } + var ref = view.root.getSelection(); + var focusNode = ref.focusNode; + var focusOffset = ref.focusOffset; + if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 && + focusNode.firstChild && focusNode.firstChild.contentEditable == "false") { + var child = focusNode.firstChild; + switchEditable(view, child, true); + setTimeout(function () { return switchEditable(view, child, false); }, 20); + } + } + + // A backdrop key mapping used to make sure we always suppress keys + // that have a dangerous default effect, even if the commands they are + // bound to return false, and to make sure that cursor-motion keys + // find a cursor (as opposed to a node selection) when pressed. For + // cursor-motion keys, the code in the handlers also takes care of + // block selections. + + function getMods(event) { + var result = ""; + if (event.ctrlKey) { result += "c"; } + if (event.metaKey) { result += "m"; } + if (event.altKey) { result += "a"; } + if (event.shiftKey) { result += "s"; } + return result + } + + function captureKeyDown(view, event) { + var code = event.keyCode, mods = getMods(event); + if (code == 8 || (result.mac && code == 72 && mods == "c")) { // Backspace, Ctrl-h on Mac + return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodesLeft(view) + } else if (code == 46 || (result.mac && code == 68 && mods == "c")) { // Delete, Ctrl-d on Mac + return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodesRight(view) + } else if (code == 13 || code == 27) { // Enter, Esc + return true + } else if (code == 37) { // Left arrow + return selectHorizontally(view, -1, mods) || skipIgnoredNodesLeft(view) + } else if (code == 39) { // Right arrow + return selectHorizontally(view, 1, mods) || skipIgnoredNodesRight(view) + } else if (code == 38) { // Up arrow + return selectVertically(view, -1, mods) || skipIgnoredNodesLeft(view) + } else if (code == 40) { // Down arrow + return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodesRight(view) + } else if (mods == (result.mac ? "m" : "c") && + (code == 66 || code == 73 || code == 89 || code == 90)) { // Mod-[biyz] + return true + } + return false + } + + // Note that all referencing and parsing is done with the + // start-of-operation selection and document, since that's the one + // that the DOM represents. If any changes came in in the meantime, + // the modification is mapped over those before it is applied, in + // readDOMChange. + + function parseBetween(view, from_, to_) { + var ref = view.docView.parseRange(from_, to_); + var parent = ref.node; + var fromOffset = ref.fromOffset; + var toOffset = ref.toOffset; + var from = ref.from; + var to = ref.to; + + var domSel = view.root.getSelection(), find = null, anchor = domSel.anchorNode; + if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) { + find = [{node: anchor, offset: domSel.anchorOffset}]; + if (!selectionCollapsed(domSel)) + { find.push({node: domSel.focusNode, offset: domSel.focusOffset}); } + } + // Work around issue in Chrome where backspacing sometimes replaces + // the deleted content with a random BR node (issues #799, #831) + if (result.chrome && view.lastKeyCode === 8) { + for (var off = toOffset; off > fromOffset; off--) { + var node = parent.childNodes[off - 1], desc = node.pmViewDesc; + if (node.nodeType == "BR" && !desc) { toOffset = off; break } + if (!desc || desc.size) { break } + } + } + var startDoc = view.state.doc; + var parser = view.someProp("domParser") || DOMParser$1.fromSchema(view.state.schema); + var $from = startDoc.resolve(from); + + var sel = null, doc = parser.parse(parent, { + topNode: $from.parent, + topMatch: $from.parent.contentMatchAt($from.index()), + topOpen: true, + from: fromOffset, + to: toOffset, + preserveWhitespace: $from.parent.type.spec.code ? "full" : true, + editableContent: true, + findPositions: find, + ruleFromNode: ruleFromNode, + context: $from + }); + if (find && find[0].pos != null) { + var anchor$1 = find[0].pos, head = find[1] && find[1].pos; + if (head == null) { head = anchor$1; } + sel = {anchor: anchor$1 + from, head: head + from}; + } + return {doc: doc, sel: sel, from: from, to: to} + } + + function ruleFromNode(dom) { + var desc = dom.pmViewDesc; + if (desc) { + return desc.parseRule() + } else if (dom.nodeName == "BR" && dom.parentNode) { + // Safari replaces the list item or table cell with a BR + // directly in the list node (?!) if you delete the last + // character in a list item or table cell (#708, #862) + if (result.safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) { + var skip = document.createElement("div"); + skip.appendChild(document.createElement("li")); + return {skip: skip} + } else if (dom.parentNode.lastChild == dom || result.safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) { + return {ignore: true} + } + } else if (dom.nodeName == "IMG" && dom.getAttribute("mark-placeholder")) { + return {ignore: true} + } + } + + function readDOMChange(view, from, to, typeOver, addedNodes) { + if (from < 0) { + var origin = view.lastSelectionTime > Date.now() - 50 ? view.lastSelectionOrigin : null; + var newSel = selectionFromDOM(view, origin); + if (newSel && !view.state.selection.eq(newSel)) { + var tr$1 = view.state.tr.setSelection(newSel); + if (origin == "pointer") { tr$1.setMeta("pointer", true); } + else if (origin == "key") { tr$1.scrollIntoView(); } + view.dispatch(tr$1); + } + return + } + + var $before = view.state.doc.resolve(from); + var shared = $before.sharedDepth(to); + from = $before.before(shared + 1); + to = view.state.doc.resolve(to).after(shared + 1); + + var sel = view.state.selection; + var parse = parseBetween(view, from, to); + + var doc = view.state.doc, compare = doc.slice(parse.from, parse.to); + var preferredPos, preferredSide; + // Prefer anchoring to end when Backspace is pressed + if (view.lastKeyCode === 8 && Date.now() - 100 < view.lastKeyCodeTime) { + preferredPos = view.state.selection.to; + preferredSide = "end"; + } else { + preferredPos = view.state.selection.from; + preferredSide = "start"; + } + view.lastKeyCode = null; + + var change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide); + if (!change) { + if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) && + !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) { + change = {start: sel.from, endA: sel.to, endB: sel.to}; + } else { + if (parse.sel) { + var sel$1 = resolveSelection(view, view.state.doc, parse.sel); + if (sel$1 && !sel$1.eq(view.state.selection)) { view.dispatch(view.state.tr.setSelection(sel$1)); } + } + return + } + } + view.domChangeCount++; + // Handle the case where overwriting a selection by typing matches + // the start or end of the selected content, creating a change + // that's smaller than what was actually overwritten. + if (view.state.selection.from < view.state.selection.to && + change.start == change.endB && + view.state.selection instanceof TextSelection) { + if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2) { + change.start = view.state.selection.from; + } else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2) { + change.endB += (view.state.selection.to - change.endA); + change.endA = view.state.selection.to; + } + } + + // IE11 will insert a non-breaking space _ahead_ of the space after + // the cursor space when adding a space before another space. When + // that happened, adjust the change to cover the space instead. + if (result.ie && result.ie_version <= 11 && change.endB == change.start + 1 && + change.endA == change.start && change.start > parse.from && + parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == " \u00a0") { + change.start--; + change.endA--; + change.endB--; + } + + var $from = parse.doc.resolveNoCache(change.start - parse.from); + var $to = parse.doc.resolveNoCache(change.endB - parse.from); + var inlineChange = $from.sameParent($to) && $from.parent.inlineContent; + var nextSel; + // If this looks like the effect of pressing Enter (or was recorded + // as being an iOS enter press), just dispatch an Enter key instead. + if (((result.ios && view.lastIOSEnter > Date.now() - 225 && + (!inlineChange || addedNodes.some(function (n) { return n.nodeName == "DIV" || n.nodeName == "P"; }))) || + (!inlineChange && $from.pos < parse.doc.content.size && + (nextSel = Selection.findFrom(parse.doc.resolve($from.pos + 1), 1, true)) && + nextSel.head == $to.pos)) && + view.someProp("handleKeyDown", function (f) { return f(view, keyEvent(13, "Enter")); })) { + view.lastIOSEnter = 0; + return + } + // Same for backspace + if (view.state.selection.anchor > change.start && + looksLikeJoin(doc, change.start, change.endA, $from, $to) && + view.someProp("handleKeyDown", function (f) { return f(view, keyEvent(8, "Backspace")); })) { + if (result.android && result.chrome) { view.domObserver.suppressSelectionUpdates(); } // #820 + return + } + + // This tries to detect Android virtual keyboard + // enter-and-pick-suggestion action. That sometimes (see issue + // #1059) first fires a DOM mutation, before moving the selection to + // the newly created block. And then, because ProseMirror cleans up + // the DOM selection, it gives up moving the selection entirely, + // leaving the cursor in the wrong place. When that happens, we drop + // the new paragraph from the initial change, and fire a simulated + // enter key afterwards. + if (result.android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth && + parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) { + change.endB -= 2; + $to = parse.doc.resolveNoCache(change.endB - parse.from); + setTimeout(function () { + view.someProp("handleKeyDown", function (f) { return f(view, keyEvent(13, "Enter")); }); + }, 20); + } + + var chFrom = change.start, chTo = change.endA; + + var tr, storedMarks, markChange, $from1; + if (inlineChange) { + if ($from.pos == $to.pos) { // Deletion + // IE11 sometimes weirdly moves the DOM selection around after + // backspacing out the first element in a textblock + if (result.ie && result.ie_version <= 11 && $from.parentOffset == 0) { + view.domObserver.suppressSelectionUpdates(); + setTimeout(function () { return selectionToDOM(view); }, 20); + } + tr = view.state.tr.delete(chFrom, chTo); + storedMarks = doc.resolve(change.start).marksAcross(doc.resolve(change.endA)); + } else if ( // Adding or removing a mark + change.endA == change.endB && ($from1 = doc.resolve(change.start)) && + (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), + $from1.parent.content.cut($from1.parentOffset, change.endA - $from1.start()))) + ) { + tr = view.state.tr; + if (markChange.type == "add") { tr.addMark(chFrom, chTo, markChange.mark); } + else { tr.removeMark(chFrom, chTo, markChange.mark); } + } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) { + // Both positions in the same text node -- simply insert text + var text = $from.parent.textBetween($from.parentOffset, $to.parentOffset); + if (view.someProp("handleTextInput", function (f) { return f(view, chFrom, chTo, text); })) { return } + tr = view.state.tr.insertText(text, chFrom, chTo); + } + } + + if (!tr) + { tr = view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from)); } + if (parse.sel) { + var sel$2 = resolveSelection(view, tr.doc, parse.sel); + // Chrome Android will sometimes, during composition, report the + // selection in the wrong place. If it looks like that is + // happening, don't update the selection. + // Edge just doesn't move the cursor forward when you start typing + // in an empty block or between br nodes. + if (sel$2 && !(result.chrome && result.android && view.composing && sel$2.empty && + (sel$2.head == chFrom || sel$2.head == tr.mapping.map(chTo) - 1) || + result.ie && sel$2.empty && sel$2.head == chFrom)) + { tr.setSelection(sel$2); } + } + if (storedMarks) { tr.ensureMarks(storedMarks); } + view.dispatch(tr.scrollIntoView()); + } + + function resolveSelection(view, doc, parsedSel) { + if (Math.max(parsedSel.anchor, parsedSel.head) > doc.content.size) { return null } + return selectionBetween(view, doc.resolve(parsedSel.anchor), doc.resolve(parsedSel.head)) + } + + // : (Fragment, Fragment) → ?{mark: Mark, type: string} + // Given two same-length, non-empty fragments of inline content, + // determine whether the first could be created from the second by + // removing or adding a single mark type. + function isMarkChange(cur, prev) { + var curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks; + var added = curMarks, removed = prevMarks, type, mark, update; + for (var i = 0; i < prevMarks.length; i++) { added = prevMarks[i].removeFromSet(added); } + for (var i$1 = 0; i$1 < curMarks.length; i$1++) { removed = curMarks[i$1].removeFromSet(removed); } + if (added.length == 1 && removed.length == 0) { + mark = added[0]; + type = "add"; + update = function (node) { return node.mark(mark.addToSet(node.marks)); }; + } else if (added.length == 0 && removed.length == 1) { + mark = removed[0]; + type = "remove"; + update = function (node) { return node.mark(mark.removeFromSet(node.marks)); }; + } else { + return null + } + var updated = []; + for (var i$2 = 0; i$2 < prev.childCount; i$2++) { updated.push(update(prev.child(i$2))); } + if (Fragment.from(updated).eq(cur)) { return {mark: mark, type: type} } + } + + function looksLikeJoin(old, start, end, $newStart, $newEnd) { + if (!$newStart.parent.isTextblock || + // The content must have shrunk + end - start <= $newEnd.pos - $newStart.pos || + // newEnd must point directly at or after the end of the block that newStart points into + skipClosingAndOpening($newStart, true, false) < $newEnd.pos) + { return false } + + var $start = old.resolve(start); + // Start must be at the end of a block + if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock) + { return false } + var $next = old.resolve(skipClosingAndOpening($start, true, true)); + // The next textblock must start before end and end near it + if (!$next.parent.isTextblock || $next.pos > end || + skipClosingAndOpening($next, true, false) < end) + { return false } + + // The fragments after the join point must match + return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content) + } + + function skipClosingAndOpening($pos, fromEnd, mayOpen) { + var depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos; + while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) { + depth--; + end++; + fromEnd = false; + } + if (mayOpen) { + var next = $pos.node(depth).maybeChild($pos.indexAfter(depth)); + while (next && !next.isLeaf) { + next = next.firstChild; + end++; + } + } + return end + } + + function findDiff(a, b, pos, preferredPos, preferredSide) { + var start = a.findDiffStart(b, pos); + if (start == null) { return null } + var ref = a.findDiffEnd(b, pos + a.size, pos + b.size); + var endA = ref.a; + var endB = ref.b; + if (preferredSide == "end") { + var adjust = Math.max(0, start - Math.min(endA, endB)); + preferredPos -= endA + adjust - start; + } + if (endA < start && a.size < b.size) { + var move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0; + start -= move; + endB = start + (endB - endA); + endA = start; + } else if (endB < start) { + var move$1 = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0; + start -= move$1; + endA = start + (endA - endB); + endB = start; + } + return {start: start, endA: endA, endB: endB} + } + + function serializeForClipboard(view, slice) { + var context = []; + var content = slice.content; + var openStart = slice.openStart; + var openEnd = slice.openEnd; + while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) { + openStart--; + openEnd--; + var node = content.firstChild; + context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null); + content = node.content; + } + + var serializer = view.someProp("clipboardSerializer") || DOMSerializer.fromSchema(view.state.schema); + var doc = detachedDoc(), wrap = doc.createElement("div"); + wrap.appendChild(serializer.serializeFragment(content, {document: doc})); + + var firstChild = wrap.firstChild, needsWrap; + while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) { + for (var i = needsWrap.length - 1; i >= 0; i--) { + var wrapper = doc.createElement(needsWrap[i]); + while (wrap.firstChild) { wrapper.appendChild(wrap.firstChild); } + wrap.appendChild(wrapper); + } + firstChild = wrap.firstChild; + } + + if (firstChild && firstChild.nodeType == 1) + { firstChild.setAttribute("data-pm-slice", (openStart + " " + openEnd + " " + (JSON.stringify(context)))); } + + var text = view.someProp("clipboardTextSerializer", function (f) { return f(slice); }) || + slice.content.textBetween(0, slice.content.size, "\n\n"); + + return {dom: wrap, text: text} + } + + // : (EditorView, string, string, ?bool, ResolvedPos) → ?Slice + // Read a slice of content from the clipboard (or drop data). + function parseFromClipboard(view, text, html, plainText, $context) { + var dom, inCode = $context.parent.type.spec.code, slice; + if (!html && !text) { return null } + var asText = text && (plainText || inCode || !html); + if (asText) { + view.someProp("transformPastedText", function (f) { text = f(text, inCode || plainText); }); + if (inCode) { return new Slice(Fragment.from(view.state.schema.text(text)), 0, 0) } + var parsed = view.someProp("clipboardTextParser", function (f) { return f(text, $context, plainText); }); + if (parsed) { + slice = parsed; + } else { + dom = document.createElement("div"); + text.trim().split(/(?:\r\n?|\n)+/).forEach(function (block) { + dom.appendChild(document.createElement("p")).textContent = block; + }); + } + } else { + view.someProp("transformPastedHTML", function (f) { html = f(html); }); + dom = readHTML(html); + } + + var contextNode = dom && dom.querySelector("[data-pm-slice]"); + var sliceData = contextNode && /^(\d+) (\d+) (.*)/.exec(contextNode.getAttribute("data-pm-slice")); + if (!slice) { + var parser = view.someProp("clipboardParser") || view.someProp("domParser") || DOMParser$1.fromSchema(view.state.schema); + slice = parser.parseSlice(dom, {preserveWhitespace: !!(asText || sliceData), context: $context}); + } + if (sliceData) + { slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[3]); } + else // HTML wasn't created by ProseMirror. Make sure top-level siblings are coherent + { slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), false); } + + view.someProp("transformPasted", function (f) { slice = f(slice); }); + return slice + } + + // Takes a slice parsed with parseSlice, which means there hasn't been + // any content-expression checking done on the top nodes, tries to + // find a parent node in the current context that might fit the nodes, + // and if successful, rebuilds the slice so that it fits into that parent. + // + // This addresses the problem that Transform.replace expects a + // coherent slice, and will fail to place a set of siblings that don't + // fit anywhere in the schema. + function normalizeSiblings(fragment, $context) { + if (fragment.childCount < 2) { return fragment } + var loop = function ( d ) { + var parent = $context.node(d); + var match = parent.contentMatchAt($context.index(d)); + var lastWrap = (void 0), result = []; + fragment.forEach(function (node) { + if (!result) { return } + var wrap = match.findWrapping(node.type), inLast; + if (!wrap) { return result = null } + if (inLast = result.length && lastWrap.length && addToSibling(wrap, lastWrap, node, result[result.length - 1], 0)) { + result[result.length - 1] = inLast; + } else { + if (result.length) { result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length); } + var wrapped = withWrappers(node, wrap); + result.push(wrapped); + match = match.matchType(wrapped.type, wrapped.attrs); + lastWrap = wrap; + } + }); + if (result) { return { v: Fragment.from(result) } } + }; + + for (var d = $context.depth; d >= 0; d--) { + var returned = loop( d ); + + if ( returned ) return returned.v; + } + return fragment + } + + function withWrappers(node, wrap, from) { + if ( from === void 0 ) from = 0; + + for (var i = wrap.length - 1; i >= from; i--) + { node = wrap[i].create(null, Fragment.from(node)); } + return node + } + + // Used to group adjacent nodes wrapped in similar parents by + // normalizeSiblings into the same parent node + function addToSibling(wrap, lastWrap, node, sibling, depth) { + if (depth < wrap.length && depth < lastWrap.length && wrap[depth] == lastWrap[depth]) { + var inner = addToSibling(wrap, lastWrap, node, sibling.lastChild, depth + 1); + if (inner) { return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner)) } + var match = sibling.contentMatchAt(sibling.childCount); + if (match.matchType(depth == wrap.length - 1 ? node.type : wrap[depth + 1])) + { return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap, depth + 1)))) } + } + } + + function closeRight(node, depth) { + if (depth == 0) { return node } + var fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1)); + var fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true); + return node.copy(fragment.append(fill)) + } + + function closeRange(fragment, side, from, to, depth, openEnd) { + var node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content; + if (depth < to - 1) { inner = closeRange(inner, side, from, to, depth + 1, openEnd); } + if (depth >= from) + { inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, fragment.childCount > 1 || openEnd <= depth).append(inner) + : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true)); } + return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner)) + } + + function closeSlice(slice, openStart, openEnd) { + if (openStart < slice.openStart) + { slice = new Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd); } + if (openEnd < slice.openEnd) + { slice = new Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd); } + return slice + } + + // Trick from jQuery -- some elements must be wrapped in other + // elements for innerHTML to work. I.e. if you do `div.innerHTML = + // ".."` the table cells are ignored. + var wrapMap = { + thead: ["table"], + tbody: ["table"], + tfoot: ["table"], + caption: ["table"], + colgroup: ["table"], + col: ["table", "colgroup"], + tr: ["table", "tbody"], + td: ["table", "tbody", "tr"], + th: ["table", "tbody", "tr"] + }; + + var _detachedDoc = null; + function detachedDoc() { + return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument("title")) + } + + function readHTML(html) { + var metas = /(\s*]*>)*/.exec(html); + if (metas) { html = html.slice(metas[0].length); } + var elt = detachedDoc().createElement("div"); + var firstTag = /(?:]*>)*<([a-z][^>\s]+)/i.exec(html), wrap, depth = 0; + if (wrap = firstTag && wrapMap[firstTag[1].toLowerCase()]) { + html = wrap.map(function (n) { return "<" + n + ">"; }).join("") + html + wrap.map(function (n) { return ""; }).reverse().join(""); + depth = wrap.length; + } + elt.innerHTML = html; + for (var i = 0; i < depth; i++) { elt = elt.firstChild; } + return elt + } + + function addContext(slice, context) { + if (!slice.size) { return slice } + var schema = slice.content.firstChild.type.schema, array; + try { array = JSON.parse(context); } + catch(e) { return slice } + var content = slice.content; + var openStart = slice.openStart; + var openEnd = slice.openEnd; + for (var i = array.length - 2; i >= 0; i -= 2) { + var type = schema.nodes[array[i]]; + if (!type || type.hasRequiredAttrs()) { break } + content = Fragment.from(type.create(array[i + 1], content)); + openStart++; openEnd++; + } + return new Slice(content, openStart, openEnd) + } + + var observeOptions = { + childList: true, + characterData: true, + characterDataOldValue: true, + attributes: true, + attributeOldValue: true, + subtree: true + }; + // IE11 has very broken mutation observers, so we also listen to DOMCharacterDataModified + var useCharData = result.ie && result.ie_version <= 11; + + var SelectionState = function SelectionState() { + this.anchorNode = this.anchorOffset = this.focusNode = this.focusOffset = null; + }; + + SelectionState.prototype.set = function set (sel) { + this.anchorNode = sel.anchorNode; this.anchorOffset = sel.anchorOffset; + this.focusNode = sel.focusNode; this.focusOffset = sel.focusOffset; + }; + + SelectionState.prototype.eq = function eq (sel) { + return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset && + sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset + }; + + var DOMObserver = function DOMObserver(view, handleDOMChange) { + var this$1 = this; + + this.view = view; + this.handleDOMChange = handleDOMChange; + this.queue = []; + this.flushingSoon = -1; + this.observer = window.MutationObserver && + new window.MutationObserver(function (mutations) { + for (var i = 0; i < mutations.length; i++) { this$1.queue.push(mutations[i]); } + // IE11 will sometimes (on backspacing out a single character + // text node after a BR node) call the observer callback + // before actually updating the DOM, which will cause + // ProseMirror to miss the change (see #930) + if (result.ie && result.ie_version <= 11 && mutations.some( + function (m) { return m.type == "childList" && m.removedNodes.length || + m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length; })) + { this$1.flushSoon(); } + else + { this$1.flush(); } + }); + this.currentSelection = new SelectionState; + if (useCharData) { + this.onCharData = function (e) { + this$1.queue.push({target: e.target, type: "characterData", oldValue: e.prevValue}); + this$1.flushSoon(); + }; + } + this.onSelectionChange = this.onSelectionChange.bind(this); + this.suppressingSelectionUpdates = false; + }; + + DOMObserver.prototype.flushSoon = function flushSoon () { + var this$1 = this; + + if (this.flushingSoon < 0) + { this.flushingSoon = window.setTimeout(function () { this$1.flushingSoon = -1; this$1.flush(); }, 20); } + }; + + DOMObserver.prototype.forceFlush = function forceFlush () { + if (this.flushingSoon > -1) { + window.clearTimeout(this.flushingSoon); + this.flushingSoon = -1; + this.flush(); + } + }; + + DOMObserver.prototype.start = function start () { + if (this.observer) + { this.observer.observe(this.view.dom, observeOptions); } + if (useCharData) + { this.view.dom.addEventListener("DOMCharacterDataModified", this.onCharData); } + this.connectSelection(); + }; + + DOMObserver.prototype.stop = function stop () { + var this$1 = this; + + if (this.observer) { + var take = this.observer.takeRecords(); + if (take.length) { + for (var i = 0; i < take.length; i++) { this.queue.push(take[i]); } + window.setTimeout(function () { return this$1.flush(); }, 20); + } + this.observer.disconnect(); + } + if (useCharData) { this.view.dom.removeEventListener("DOMCharacterDataModified", this.onCharData); } + this.disconnectSelection(); + }; + + DOMObserver.prototype.connectSelection = function connectSelection () { + this.view.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange); + }; + + DOMObserver.prototype.disconnectSelection = function disconnectSelection () { + this.view.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange); + }; + + DOMObserver.prototype.suppressSelectionUpdates = function suppressSelectionUpdates () { + var this$1 = this; + + this.suppressingSelectionUpdates = true; + setTimeout(function () { return this$1.suppressingSelectionUpdates = false; }, 50); + }; + + DOMObserver.prototype.onSelectionChange = function onSelectionChange () { + if (!hasFocusAndSelection(this.view)) { return } + if (this.suppressingSelectionUpdates) { return selectionToDOM(this.view) } + // Deletions on IE11 fire their events in the wrong order, giving + // us a selection change event before the DOM changes are + // reported. + if (result.ie && result.ie_version <= 11 && !this.view.state.selection.empty) { + var sel = this.view.root.getSelection(); + // Selection.isCollapsed isn't reliable on IE + if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) + { return this.flushSoon() } + } + this.flush(); + }; + + DOMObserver.prototype.setCurSelection = function setCurSelection () { + this.currentSelection.set(this.view.root.getSelection()); + }; + + DOMObserver.prototype.ignoreSelectionChange = function ignoreSelectionChange (sel) { + if (sel.rangeCount == 0) { return true } + var container = sel.getRangeAt(0).commonAncestorContainer; + var desc = this.view.docView.nearestDesc(container); + if (desc && desc.ignoreMutation({type: "selection", target: container.nodeType == 3 ? container.parentNode : container})) { + this.setCurSelection(); + return true + } + }; + + DOMObserver.prototype.flush = function flush () { + if (!this.view.docView || this.flushingSoon > -1) { return } + var mutations = this.observer ? this.observer.takeRecords() : []; + if (this.queue.length) { + mutations = this.queue.concat(mutations); + this.queue.length = 0; + } + + var sel = this.view.root.getSelection(); + var newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasSelection(this.view) && !this.ignoreSelectionChange(sel); + + var from = -1, to = -1, typeOver = false, added = []; + if (this.view.editable) { + for (var i = 0; i < mutations.length; i++) { + var result$1 = this.registerMutation(mutations[i], added); + if (result$1) { + from = from < 0 ? result$1.from : Math.min(result$1.from, from); + to = to < 0 ? result$1.to : Math.max(result$1.to, to); + if (result$1.typeOver) { typeOver = true; } + } + } + } + + if (result.gecko && added.length > 1) { + var brs = added.filter(function (n) { return n.nodeName == "BR"; }); + if (brs.length == 2) { + var a = brs[0]; + var b = brs[1]; + if (a.parentNode && a.parentNode.parentNode == b.parentNode) { b.remove(); } + else { a.remove(); } + } + } + + if (from > -1 || newSel) { + if (from > -1) { + this.view.docView.markDirty(from, to); + checkCSS(this.view); + } + this.handleDOMChange(from, to, typeOver, added); + if (this.view.docView.dirty) { this.view.updateState(this.view.state); } + else if (!this.currentSelection.eq(sel)) { selectionToDOM(this.view); } + } + }; + + DOMObserver.prototype.registerMutation = function registerMutation (mut, added) { + // Ignore mutations inside nodes that were already noted as inserted + if (added.indexOf(mut.target) > -1) { return null } + var desc = this.view.docView.nearestDesc(mut.target); + if (mut.type == "attributes" && + (desc == this.view.docView || mut.attributeName == "contenteditable" || + // Firefox sometimes fires spurious events for null/empty styles + (mut.attributeName == "style" && !mut.oldValue && !mut.target.getAttribute("style")))) + { return null } + if (!desc || desc.ignoreMutation(mut)) { return null } + + if (mut.type == "childList") { + var prev = mut.previousSibling, next = mut.nextSibling; + if (result.ie && result.ie_version <= 11 && mut.addedNodes.length) { + // IE11 gives us incorrect next/prev siblings for some + // insertions, so if there are added nodes, recompute those + for (var i = 0; i < mut.addedNodes.length; i++) { + var ref = mut.addedNodes[i]; + var previousSibling = ref.previousSibling; + var nextSibling = ref.nextSibling; + if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0) { prev = previousSibling; } + if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0) { next = nextSibling; } + } + } + var fromOffset = prev && prev.parentNode == mut.target + ? domIndex(prev) + 1 : 0; + var from = desc.localPosFromDOM(mut.target, fromOffset, -1); + var toOffset = next && next.parentNode == mut.target + ? domIndex(next) : mut.target.childNodes.length; + for (var i$1 = 0; i$1 < mut.addedNodes.length; i$1++) { added.push(mut.addedNodes[i$1]); } + var to = desc.localPosFromDOM(mut.target, toOffset, 1); + return {from: from, to: to} + } else if (mut.type == "attributes") { + return {from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border} + } else { // "characterData" + return { + from: desc.posAtStart, + to: desc.posAtEnd, + // An event was generated for a text change that didn't change + // any text. Mark the dom change to fall back to assuming the + // selection was typed over with an identical value if it can't + // find another change. + typeOver: mut.target.nodeValue == mut.oldValue + } + } + }; + + var cssChecked = false; + + function checkCSS(view) { + if (cssChecked) { return } + cssChecked = true; + if (getComputedStyle(view.dom).whiteSpace == "normal") + { console["warn"]("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package."); } + } + + // A collection of DOM events that occur within the editor, and callback functions + // to invoke when the event fires. + var handlers = {}, editHandlers = {}; + + function initInput(view) { + view.shiftKey = false; + view.mouseDown = null; + view.lastKeyCode = null; + view.lastKeyCodeTime = 0; + view.lastClick = {time: 0, x: 0, y: 0, type: ""}; + view.lastSelectionOrigin = null; + view.lastSelectionTime = 0; + + view.lastIOSEnter = 0; + view.lastIOSEnterFallbackTimeout = null; + + view.composing = false; + view.composingTimeout = null; + view.compositionNodes = []; + view.compositionEndedAt = -2e8; + + view.domObserver = new DOMObserver(view, function (from, to, typeOver, added) { return readDOMChange(view, from, to, typeOver, added); }); + view.domObserver.start(); + // Used by hacks like the beforeinput handler to check whether anything happened in the DOM + view.domChangeCount = 0; + + view.eventHandlers = Object.create(null); + var loop = function ( event ) { + var handler = handlers[event]; + view.dom.addEventListener(event, view.eventHandlers[event] = function (event) { + if (eventBelongsToView(view, event) && !runCustomHandler(view, event) && + (view.editable || !(event.type in editHandlers))) + { handler(view, event); } + }); + }; + + for (var event in handlers) loop( event ); + // On Safari, for reasons beyond my understanding, adding an input + // event handler makes an issue where the composition vanishes when + // you press enter go away. + if (result.safari) { view.dom.addEventListener("input", function () { return null; }); } + + ensureListeners(view); + } + + function setSelectionOrigin(view, origin) { + view.lastSelectionOrigin = origin; + view.lastSelectionTime = Date.now(); + } + + function destroyInput(view) { + view.domObserver.stop(); + for (var type in view.eventHandlers) + { view.dom.removeEventListener(type, view.eventHandlers[type]); } + clearTimeout(view.composingTimeout); + clearTimeout(view.lastIOSEnterFallbackTimeout); + } + + function ensureListeners(view) { + view.someProp("handleDOMEvents", function (currentHandlers) { + for (var type in currentHandlers) { if (!view.eventHandlers[type]) + { view.dom.addEventListener(type, view.eventHandlers[type] = function (event) { return runCustomHandler(view, event); }); } } + }); + } + + function runCustomHandler(view, event) { + return view.someProp("handleDOMEvents", function (handlers) { + var handler = handlers[event.type]; + return handler ? handler(view, event) || event.defaultPrevented : false + }) + } + + function eventBelongsToView(view, event) { + if (!event.bubbles) { return true } + if (event.defaultPrevented) { return false } + for (var node = event.target; node != view.dom; node = node.parentNode) + { if (!node || node.nodeType == 11 || + (node.pmViewDesc && node.pmViewDesc.stopEvent(event))) + { return false } } + return true + } + + function dispatchEvent(view, event) { + if (!runCustomHandler(view, event) && handlers[event.type] && + (view.editable || !(event.type in editHandlers))) + { handlers[event.type](view, event); } + } + + editHandlers.keydown = function (view, event) { + view.shiftKey = event.keyCode == 16 || event.shiftKey; + if (inOrNearComposition(view, event)) { return } + view.domObserver.forceFlush(); + view.lastKeyCode = event.keyCode; + view.lastKeyCodeTime = Date.now(); + // On iOS, if we preventDefault enter key presses, the virtual + // keyboard gets confused. So the hack here is to set a flag that + // makes the DOM change code recognize that what just happens should + // be replaced by whatever the Enter key handlers do. + if (result.ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) { + var now = Date.now(); + view.lastIOSEnter = now; + view.lastIOSEnterFallbackTimeout = setTimeout(function () { + if (view.lastIOSEnter == now) { + view.someProp("handleKeyDown", function (f) { return f(view, keyEvent(13, "Enter")); }); + view.lastIOSEnter = 0; + } + }, 200); + } else if (view.someProp("handleKeyDown", function (f) { return f(view, event); }) || captureKeyDown(view, event)) { + event.preventDefault(); + } else { + setSelectionOrigin(view, "key"); + } + }; + + editHandlers.keyup = function (view, e) { + if (e.keyCode == 16) { view.shiftKey = false; } + }; + + editHandlers.keypress = function (view, event) { + if (inOrNearComposition(view, event) || !event.charCode || + event.ctrlKey && !event.altKey || result.mac && event.metaKey) { return } + + if (view.someProp("handleKeyPress", function (f) { return f(view, event); })) { + event.preventDefault(); + return + } + + var sel = view.state.selection; + if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) { + var text = String.fromCharCode(event.charCode); + if (!view.someProp("handleTextInput", function (f) { return f(view, sel.$from.pos, sel.$to.pos, text); })) + { view.dispatch(view.state.tr.insertText(text).scrollIntoView()); } + event.preventDefault(); + } + }; + + function eventCoords(event) { return {left: event.clientX, top: event.clientY} } + + function isNear(event, click) { + var dx = click.x - event.clientX, dy = click.y - event.clientY; + return dx * dx + dy * dy < 100 + } + + function runHandlerOnContext(view, propName, pos, inside, event) { + if (inside == -1) { return false } + var $pos = view.state.doc.resolve(inside); + var loop = function ( i ) { + if (view.someProp(propName, function (f) { return i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true) + : f(view, pos, $pos.node(i), $pos.before(i), event, false); })) + { return { v: true } } + }; + + for (var i = $pos.depth + 1; i > 0; i--) { + var returned = loop( i ); + + if ( returned ) return returned.v; + } + return false + } + + function updateSelection(view, selection, origin) { + if (!view.focused) { view.focus(); } + var tr = view.state.tr.setSelection(selection); + if (origin == "pointer") { tr.setMeta("pointer", true); } + view.dispatch(tr); + } + + function selectClickedLeaf(view, inside) { + if (inside == -1) { return false } + var $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter; + if (node && node.isAtom && NodeSelection.isSelectable(node)) { + updateSelection(view, new NodeSelection($pos), "pointer"); + return true + } + return false + } + + function selectClickedNode(view, inside) { + if (inside == -1) { return false } + var sel = view.state.selection, selectedNode, selectAt; + if (sel instanceof NodeSelection) { selectedNode = sel.node; } + + var $pos = view.state.doc.resolve(inside); + for (var i = $pos.depth + 1; i > 0; i--) { + var node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i); + if (NodeSelection.isSelectable(node)) { + if (selectedNode && sel.$from.depth > 0 && + i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos) + { selectAt = $pos.before(sel.$from.depth); } + else + { selectAt = $pos.before(i); } + break + } + } + + if (selectAt != null) { + updateSelection(view, NodeSelection.create(view.state.doc, selectAt), "pointer"); + return true + } else { + return false + } + } + + function handleSingleClick(view, pos, inside, event, selectNode) { + return runHandlerOnContext(view, "handleClickOn", pos, inside, event) || + view.someProp("handleClick", function (f) { return f(view, pos, event); }) || + (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside)) + } + + function handleDoubleClick(view, pos, inside, event) { + return runHandlerOnContext(view, "handleDoubleClickOn", pos, inside, event) || + view.someProp("handleDoubleClick", function (f) { return f(view, pos, event); }) + } + + function handleTripleClick(view, pos, inside, event) { + return runHandlerOnContext(view, "handleTripleClickOn", pos, inside, event) || + view.someProp("handleTripleClick", function (f) { return f(view, pos, event); }) || + defaultTripleClick(view, inside) + } + + function defaultTripleClick(view, inside) { + var doc = view.state.doc; + if (inside == -1) { + if (doc.inlineContent) { + updateSelection(view, TextSelection.create(doc, 0, doc.content.size), "pointer"); + return true + } + return false + } + + var $pos = doc.resolve(inside); + for (var i = $pos.depth + 1; i > 0; i--) { + var node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i); + var nodePos = $pos.before(i); + if (node.inlineContent) + { updateSelection(view, TextSelection.create(doc, nodePos + 1, nodePos + 1 + node.content.size), "pointer"); } + else if (NodeSelection.isSelectable(node)) + { updateSelection(view, NodeSelection.create(doc, nodePos), "pointer"); } + else + { continue } + return true + } + } + + function forceDOMFlush(view) { + return endComposition(view) + } + + var selectNodeModifier = result.mac ? "metaKey" : "ctrlKey"; + + handlers.mousedown = function (view, event) { + view.shiftKey = event.shiftKey; + var flushed = forceDOMFlush(view); + var now = Date.now(), type = "singleClick"; + if (now - view.lastClick.time < 500 && isNear(event, view.lastClick) && !event[selectNodeModifier]) { + if (view.lastClick.type == "singleClick") { type = "doubleClick"; } + else if (view.lastClick.type == "doubleClick") { type = "tripleClick"; } + } + view.lastClick = {time: now, x: event.clientX, y: event.clientY, type: type}; + + var pos = view.posAtCoords(eventCoords(event)); + if (!pos) { return } + + if (type == "singleClick") + { view.mouseDown = new MouseDown(view, pos, event, flushed); } + else if ((type == "doubleClick" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) + { event.preventDefault(); } + else + { setSelectionOrigin(view, "pointer"); } + }; + + var MouseDown = function MouseDown(view, pos, event, flushed) { + var this$1 = this; + + this.view = view; + this.startDoc = view.state.doc; + this.pos = pos; + this.event = event; + this.flushed = flushed; + this.selectNode = event[selectNodeModifier]; + this.allowDefault = event.shiftKey; + + var targetNode, targetPos; + if (pos.inside > -1) { + targetNode = view.state.doc.nodeAt(pos.inside); + targetPos = pos.inside; + } else { + var $pos = view.state.doc.resolve(pos.pos); + targetNode = $pos.parent; + targetPos = $pos.depth ? $pos.before() : 0; + } + + this.mightDrag = null; + + var target = flushed ? null : event.target; + var targetDesc = target ? view.docView.nearestDesc(target, true) : null; + this.target = targetDesc ? targetDesc.dom : null; + + if (targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false || + view.state.selection instanceof NodeSelection && targetPos == view.state.selection.from) + { this.mightDrag = {node: targetNode, + pos: targetPos, + addAttr: this.target && !this.target.draggable, + setUneditable: this.target && result.gecko && !this.target.hasAttribute("contentEditable")}; } + + if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) { + this.view.domObserver.stop(); + if (this.mightDrag.addAttr) { this.target.draggable = true; } + if (this.mightDrag.setUneditable) + { setTimeout(function () { return this$1.target.setAttribute("contentEditable", "false"); }, 20); } + this.view.domObserver.start(); + } + + view.root.addEventListener("mouseup", this.up = this.up.bind(this)); + view.root.addEventListener("mousemove", this.move = this.move.bind(this)); + setSelectionOrigin(view, "pointer"); + }; + + MouseDown.prototype.done = function done () { + this.view.root.removeEventListener("mouseup", this.up); + this.view.root.removeEventListener("mousemove", this.move); + if (this.mightDrag && this.target) { + this.view.domObserver.stop(); + if (this.mightDrag.addAttr) { this.target.removeAttribute("draggable"); } + if (this.mightDrag.setUneditable) { this.target.removeAttribute("contentEditable"); } + this.view.domObserver.start(); + } + this.view.mouseDown = null; + }; + + MouseDown.prototype.up = function up (event) { + this.done(); + + if (!this.view.dom.contains(event.target.nodeType == 3 ? event.target.parentNode : event.target)) + { return } + + var pos = this.pos; + if (this.view.state.doc != this.startDoc) { pos = this.view.posAtCoords(eventCoords(event)); } + + if (this.allowDefault || !pos) { + setSelectionOrigin(this.view, "pointer"); + } else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) { + event.preventDefault(); + } else if (this.flushed || + // Safari ignores clicks on draggable elements + (result.safari && this.mightDrag && !this.mightDrag.node.isAtom) || + // Chrome will sometimes treat a node selection as a + // cursor, but still report that the node is selected + // when asked through getSelection. You'll then get a + // situation where clicking at the point where that + // (hidden) cursor is doesn't change the selection, and + // thus doesn't get a reaction from ProseMirror. This + // works around that. + (result.chrome && !(this.view.state.selection instanceof TextSelection) && + (pos.pos == this.view.state.selection.from || pos.pos == this.view.state.selection.to))) { + updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)), "pointer"); + event.preventDefault(); + } else { + setSelectionOrigin(this.view, "pointer"); + } + }; + + MouseDown.prototype.move = function move (event) { + if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 || + Math.abs(this.event.y - event.clientY) > 4)) + { this.allowDefault = true; } + setSelectionOrigin(this.view, "pointer"); + }; + + handlers.touchdown = function (view) { + forceDOMFlush(view); + setSelectionOrigin(view, "pointer"); + }; + + handlers.contextmenu = function (view) { return forceDOMFlush(view); }; + + function inOrNearComposition(view, event) { + if (view.composing) { return true } + // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/. + // On Japanese input method editors (IMEs), the Enter key is used to confirm character + // selection. On Safari, when Enter is pressed, compositionend and keydown events are + // emitted. The keydown event triggers newline insertion, which we don't want. + // This method returns true if the keydown event should be ignored. + // We only ignore it once, as pressing Enter a second time *should* insert a newline. + // Furthermore, the keydown event timestamp must be close to the compositionEndedAt timestamp. + // This guards against the case where compositionend is triggered without the keyboard + // (e.g. character confirmation may be done with the mouse), and keydown is triggered + // afterwards- we wouldn't want to ignore the keydown event in this case. + if (result.safari && Math.abs(event.timeStamp - view.compositionEndedAt) < 500) { + view.compositionEndedAt = -2e8; + return true + } + return false + } + + // Drop active composition after 5 seconds of inactivity on Android + var timeoutComposition = result.android ? 5000 : -1; + + editHandlers.compositionstart = editHandlers.compositionupdate = function (view) { + if (!view.composing) { + view.domObserver.flush(); + var state = view.state; + var $pos = state.selection.$from; + if (state.selection.empty && + (state.storedMarks || (!$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some(function (m) { return m.type.spec.inclusive === false; })))) { + // Need to wrap the cursor in mark nodes different from the ones in the DOM context + view.markCursor = view.state.storedMarks || $pos.marks(); + endComposition(view, true); + view.markCursor = null; + } else { + endComposition(view); + // In firefox, if the cursor is after but outside a marked node, + // the inserted text won't inherit the marks. So this moves it + // inside if necessary. + if (result.gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) { + var sel = view.root.getSelection(); + for (var node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0;) { + var before = offset < 0 ? node.lastChild : node.childNodes[offset - 1]; + if (!before) { break } + if (before.nodeType == 3) { + sel.collapse(before, before.nodeValue.length); + break + } else { + node = before; + offset = -1; + } + } + } + } + view.composing = true; + } + scheduleComposeEnd(view, timeoutComposition); + }; + + editHandlers.compositionend = function (view, event) { + if (view.composing) { + view.composing = false; + view.compositionEndedAt = event.timeStamp; + scheduleComposeEnd(view, 20); + } + }; + + function scheduleComposeEnd(view, delay) { + clearTimeout(view.composingTimeout); + if (delay > -1) { view.composingTimeout = setTimeout(function () { return endComposition(view); }, delay); } + } + + function clearComposition(view) { + view.composing = false; + while (view.compositionNodes.length > 0) { view.compositionNodes.pop().markParentsDirty(); } + } + + function endComposition(view, forceUpdate) { + view.domObserver.forceFlush(); + clearComposition(view); + if (forceUpdate || view.docView.dirty) { + var sel = selectionFromDOM(view); + if (sel && !sel.eq(view.state.selection)) { view.dispatch(view.state.tr.setSelection(sel)); } + else { view.updateState(view.state); } + return true + } + return false + } + + function captureCopy(view, dom) { + // The extra wrapper is somehow necessary on IE/Edge to prevent the + // content from being mangled when it is put onto the clipboard + if (!view.dom.parentNode) { return } + var wrap = view.dom.parentNode.appendChild(document.createElement("div")); + wrap.appendChild(dom); + wrap.style.cssText = "position: fixed; left: -10000px; top: 10px"; + var sel = getSelection(), range = document.createRange(); + range.selectNodeContents(dom); + // Done because IE will fire a selectionchange moving the selection + // to its start when removeAllRanges is called and the editor still + // has focus (which will mess up the editor's selection state). + view.dom.blur(); + sel.removeAllRanges(); + sel.addRange(range); + setTimeout(function () { + if (wrap.parentNode) { wrap.parentNode.removeChild(wrap); } + view.focus(); + }, 50); + } + + // This is very crude, but unfortunately both these browsers _pretend_ + // that they have a clipboard API—all the objects and methods are + // there, they just don't work, and they are hard to test. + var brokenClipboardAPI = (result.ie && result.ie_version < 15) || + (result.ios && result.webkit_version < 604); + + handlers.copy = editHandlers.cut = function (view, e) { + var sel = view.state.selection, cut = e.type == "cut"; + if (sel.empty) { return } + + // IE and Edge's clipboard interface is completely broken + var data = brokenClipboardAPI ? null : e.clipboardData; + var slice = sel.content(); + var ref = serializeForClipboard(view, slice); + var dom = ref.dom; + var text = ref.text; + if (data) { + e.preventDefault(); + data.clearData(); + data.setData("text/html", dom.innerHTML); + data.setData("text/plain", text); + } else { + captureCopy(view, dom); + } + if (cut) { view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut")); } + }; + + function sliceSingleNode(slice) { + return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null + } + + function capturePaste(view, e) { + if (!view.dom.parentNode) { return } + var plainText = view.shiftKey || view.state.selection.$from.parent.type.spec.code; + var target = view.dom.parentNode.appendChild(document.createElement(plainText ? "textarea" : "div")); + if (!plainText) { target.contentEditable = "true"; } + target.style.cssText = "position: fixed; left: -10000px; top: 10px"; + target.focus(); + setTimeout(function () { + view.focus(); + if (target.parentNode) { target.parentNode.removeChild(target); } + if (plainText) { doPaste(view, target.value, null, e); } + else { doPaste(view, target.textContent, target.innerHTML, e); } + }, 50); + } + + function doPaste(view, text, html, e) { + var slice = parseFromClipboard(view, text, html, view.shiftKey, view.state.selection.$from); + if (view.someProp("handlePaste", function (f) { return f(view, e, slice || Slice.empty); }) || !slice) { return } + + var singleNode = sliceSingleNode(slice); + var tr = singleNode ? view.state.tr.replaceSelectionWith(singleNode, view.shiftKey) : view.state.tr.replaceSelection(slice); + view.dispatch(tr.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste")); + } + + editHandlers.paste = function (view, e) { + var data = brokenClipboardAPI ? null : e.clipboardData; + var html = data && data.getData("text/html"), text = data && data.getData("text/plain"); + if (data && (html || text || data.files.length)) { + doPaste(view, text, html, e); + e.preventDefault(); + } else { + capturePaste(view, e); + } + }; + + var Dragging = function Dragging(slice, move) { + this.slice = slice; + this.move = move; + }; + + var dragCopyModifier = result.mac ? "altKey" : "ctrlKey"; + + handlers.dragstart = function (view, e) { + var mouseDown = view.mouseDown; + if (mouseDown) { mouseDown.done(); } + if (!e.dataTransfer) { return } + + var sel = view.state.selection; + var pos = sel.empty ? null : view.posAtCoords(eventCoords(e)); + if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1: sel.to)) ; else if (mouseDown && mouseDown.mightDrag) { + view.dispatch(view.state.tr.setSelection(NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos))); + } else if (e.target && e.target.nodeType == 1) { + var desc = view.docView.nearestDesc(e.target, true); + if (!desc || !desc.node.type.spec.draggable || desc == view.docView) { return } + view.dispatch(view.state.tr.setSelection(NodeSelection.create(view.state.doc, desc.posBefore))); + } + var slice = view.state.selection.content(); + var ref = serializeForClipboard(view, slice); + var dom = ref.dom; + var text = ref.text; + e.dataTransfer.clearData(); + e.dataTransfer.setData(brokenClipboardAPI ? "Text" : "text/html", dom.innerHTML); + if (!brokenClipboardAPI) { e.dataTransfer.setData("text/plain", text); } + view.dragging = new Dragging(slice, !e[dragCopyModifier]); + }; + + handlers.dragend = function (view) { + var dragging = view.dragging; + window.setTimeout(function () { + if (view.dragging == dragging) { view.dragging = null; } + }, 50); + }; + + editHandlers.dragover = editHandlers.dragenter = function (_, e) { return e.preventDefault(); }; + + editHandlers.drop = function (view, e) { + var dragging = view.dragging; + view.dragging = null; + + if (!e.dataTransfer) { return } + + var eventPos = view.posAtCoords(eventCoords(e)); + if (!eventPos) { return } + var $mouse = view.state.doc.resolve(eventPos.pos); + if (!$mouse) { return } + var slice = dragging && dragging.slice || + parseFromClipboard(view, e.dataTransfer.getData(brokenClipboardAPI ? "Text" : "text/plain"), + brokenClipboardAPI ? null : e.dataTransfer.getData("text/html"), false, $mouse); + var move = dragging && !e[dragCopyModifier]; + if (view.someProp("handleDrop", function (f) { return f(view, e, slice || Slice.empty, move); })) { + e.preventDefault(); + return + } + if (!slice) { return } + + e.preventDefault(); + var insertPos = slice ? dropPoint(view.state.doc, $mouse.pos, slice) : $mouse.pos; + if (insertPos == null) { insertPos = $mouse.pos; } + + var tr = view.state.tr; + if (move) { tr.deleteSelection(); } + + var pos = tr.mapping.map(insertPos); + var isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1; + var beforeInsert = tr.doc; + if (isNode) + { tr.replaceRangeWith(pos, pos, slice.content.firstChild); } + else + { tr.replaceRange(pos, pos, slice); } + if (tr.doc.eq(beforeInsert)) { return } + + var $pos = tr.doc.resolve(pos); + if (isNode && NodeSelection.isSelectable(slice.content.firstChild) && + $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice.content.firstChild)) { + tr.setSelection(new NodeSelection($pos)); + } else { + var end = tr.mapping.map(insertPos); + tr.mapping.maps[tr.mapping.maps.length - 1].forEach(function (_from, _to, _newFrom, newTo) { return end = newTo; }); + tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(end))); + } + view.focus(); + view.dispatch(tr.setMeta("uiEvent", "drop")); + }; + + handlers.focus = function (view) { + if (!view.focused) { + view.domObserver.stop(); + view.dom.classList.add("ProseMirror-focused"); + view.domObserver.start(); + view.focused = true; + setTimeout(function () { + if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.root.getSelection())) + { selectionToDOM(view); } + }, 20); + } + }; + + handlers.blur = function (view) { + if (view.focused) { + view.domObserver.stop(); + view.dom.classList.remove("ProseMirror-focused"); + view.domObserver.start(); + view.domObserver.currentSelection.set({}); + view.focused = false; + } + }; + + handlers.beforeinput = function (view, event) { + // We should probably do more with beforeinput events, but support + // is so spotty that I'm still waiting to see where they are going. + + // Very specific hack to deal with backspace sometimes failing on + // Chrome Android when after an uneditable node. + if (result.chrome && result.android && event.inputType == "deleteContentBackward") { + var domChangeCount = view.domChangeCount; + setTimeout(function () { + if (view.domChangeCount != domChangeCount) { return } // Event already had some effect + // This bug tends to close the virtual keyboard, so we refocus + view.dom.blur(); + view.focus(); + if (view.someProp("handleKeyDown", function (f) { return f(view, keyEvent(8, "Backspace")); })) { return } + var ref = view.state.selection; + var $cursor = ref.$cursor; + // Crude approximation of backspace behavior when no command handled it + if ($cursor && $cursor.pos > 0) { view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView()); } + }, 50); + } + }; + + // Make sure all handlers get registered + for (var prop in editHandlers) { handlers[prop] = editHandlers[prop]; } + + function compareObjs(a, b) { + if (a == b) { return true } + for (var p in a) { if (a[p] !== b[p]) { return false } } + for (var p$1 in b) { if (!(p$1 in a)) { return false } } + return true + } + + var WidgetType = function WidgetType(toDOM, spec) { + this.spec = spec || noSpec; + this.side = this.spec.side || 0; + this.toDOM = toDOM; + }; + + WidgetType.prototype.map = function map (mapping, span, offset, oldOffset) { + var ref = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1); + var pos = ref.pos; + var deleted = ref.deleted; + return deleted ? null : new Decoration(pos - offset, pos - offset, this) + }; + + WidgetType.prototype.valid = function valid () { return true }; + + WidgetType.prototype.eq = function eq (other) { + return this == other || + (other instanceof WidgetType && + (this.spec.key && this.spec.key == other.spec.key || + this.toDOM == other.toDOM && compareObjs(this.spec, other.spec))) + }; + + var InlineType = function InlineType(attrs, spec) { + this.spec = spec || noSpec; + this.attrs = attrs; + }; + + InlineType.prototype.map = function map (mapping, span, offset, oldOffset) { + var from = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset; + var to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset; + return from >= to ? null : new Decoration(from, to, this) + }; + + InlineType.prototype.valid = function valid (_, span) { return span.from < span.to }; + + InlineType.prototype.eq = function eq (other) { + return this == other || + (other instanceof InlineType && compareObjs(this.attrs, other.attrs) && + compareObjs(this.spec, other.spec)) + }; + + InlineType.is = function is (span) { return span.type instanceof InlineType }; + + var NodeType$1 = function NodeType(attrs, spec) { + this.spec = spec || noSpec; + this.attrs = attrs; + }; + + NodeType$1.prototype.map = function map (mapping, span, offset, oldOffset) { + var from = mapping.mapResult(span.from + oldOffset, 1); + if (from.deleted) { return null } + var to = mapping.mapResult(span.to + oldOffset, -1); + if (to.deleted || to.pos <= from.pos) { return null } + return new Decoration(from.pos - offset, to.pos - offset, this) + }; + + NodeType$1.prototype.valid = function valid (node, span) { + var ref = node.content.findIndex(span.from); + var index = ref.index; + var offset = ref.offset; + return offset == span.from && offset + node.child(index).nodeSize == span.to + }; + + NodeType$1.prototype.eq = function eq (other) { + return this == other || + (other instanceof NodeType$1 && compareObjs(this.attrs, other.attrs) && + compareObjs(this.spec, other.spec)) + }; + + // ::- Decoration objects can be provided to the view through the + // [`decorations` prop](#view.EditorProps.decorations). They come in + // several variants—see the static members of this class for details. + var Decoration = function Decoration(from, to, type) { + // :: number + // The start position of the decoration. + this.from = from; + // :: number + // The end position. Will be the same as `from` for [widget + // decorations](#view.Decoration^widget). + this.to = to; + this.type = type; + }; + + var prototypeAccessors$1$6 = { spec: { configurable: true },inline: { configurable: true } }; + + Decoration.prototype.copy = function copy (from, to) { + return new Decoration(from, to, this.type) + }; + + Decoration.prototype.eq = function eq (other, offset) { + if ( offset === void 0 ) offset = 0; + + return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to + }; + + Decoration.prototype.map = function map (mapping, offset, oldOffset) { + return this.type.map(mapping, this, offset, oldOffset) + }; + + // :: (number, union<(view: EditorView, getPos: () → number) → dom.Node, dom.Node>, ?Object) → Decoration + // Creates a widget decoration, which is a DOM node that's shown in + // the document at the given position. It is recommended that you + // delay rendering the widget by passing a function that will be + // called when the widget is actually drawn in a view, but you can + // also directly pass a DOM node. `getPos` can be used to find the + // widget's current document position. + // + // spec::- These options are supported: + // + // side:: ?number + // Controls which side of the document position this widget is + // associated with. When negative, it is drawn before a cursor + // at its position, and content inserted at that position ends + // up after the widget. When zero (the default) or positive, the + // widget is drawn after the cursor and content inserted there + // ends up before the widget. + // + // When there are multiple widgets at a given position, their + // `side` values determine the order in which they appear. Those + // with lower values appear first. The ordering of widgets with + // the same `side` value is unspecified. + // + // When `marks` is null, `side` also determines the marks that + // the widget is wrapped in—those of the node before when + // negative, those of the node after when positive. + // + // marks:: ?[Mark] + // The precise set of marks to draw around the widget. + // + // stopEvent:: ?(event: dom.Event) → bool + // Can be used to control which DOM events, when they bubble out + // of this widget, the editor view should ignore. + // + // ignoreSelection:: ?bool + // When set (defaults to false), selection changes inside the + // widget are ignored, and don't cause ProseMirror to try and + // re-sync the selection with its selection state. + // + // key:: ?string + // When comparing decorations of this type (in order to decide + // whether it needs to be redrawn), ProseMirror will by default + // compare the widget DOM node by identity. If you pass a key, + // that key will be compared instead, which can be useful when + // you generate decorations on the fly and don't want to store + // and reuse DOM nodes. Make sure that any widgets with the same + // key are interchangeable—if widgets differ in, for example, + // the behavior of some event handler, they should get + // different keys. + Decoration.widget = function widget (pos, toDOM, spec) { + return new Decoration(pos, pos, new WidgetType(toDOM, spec)) + }; + + // :: (number, number, DecorationAttrs, ?Object) → Decoration + // Creates an inline decoration, which adds the given attributes to + // each inline node between `from` and `to`. + // + // spec::- These options are recognized: + // + // inclusiveStart:: ?bool + // Determines how the left side of the decoration is + // [mapped](#transform.Position_Mapping) when content is + // inserted directly at that position. By default, the decoration + // won't include the new content, but you can set this to `true` + // to make it inclusive. + // + // inclusiveEnd:: ?bool + // Determines how the right side of the decoration is mapped. + // See + // [`inclusiveStart`](#view.Decoration^inline^spec.inclusiveStart). + Decoration.inline = function inline (from, to, attrs, spec) { + return new Decoration(from, to, new InlineType(attrs, spec)) + }; + + // :: (number, number, DecorationAttrs, ?Object) → Decoration + // Creates a node decoration. `from` and `to` should point precisely + // before and after a node in the document. That node, and only that + // node, will receive the given attributes. + // + // spec::- + // + // Optional information to store with the decoration. It + // is also used when comparing decorators for equality. + Decoration.node = function node (from, to, attrs, spec) { + return new Decoration(from, to, new NodeType$1(attrs, spec)) + }; + + // :: Object + // The spec provided when creating this decoration. Can be useful + // if you've stored extra information in that object. + prototypeAccessors$1$6.spec.get = function () { return this.type.spec }; + + prototypeAccessors$1$6.inline.get = function () { return this.type instanceof InlineType }; + + Object.defineProperties( Decoration.prototype, prototypeAccessors$1$6 ); + + // DecorationAttrs:: interface + // A set of attributes to add to a decorated node. Most properties + // simply directly correspond to DOM attributes of the same name, + // which will be set to the property's value. These are exceptions: + // + // class:: ?string + // A CSS class name or a space-separated set of class names to be + // _added_ to the classes that the node already had. + // + // style:: ?string + // A string of CSS to be _added_ to the node's existing `style` property. + // + // nodeName:: ?string + // When non-null, the target node is wrapped in a DOM element of + // this type (and the other attributes are applied to this element). + + var none = [], noSpec = {}; + + // ::- A collection of [decorations](#view.Decoration), organized in + // such a way that the drawing algorithm can efficiently use and + // compare them. This is a persistent data structure—it is not + // modified, updates create a new value. + var DecorationSet = function DecorationSet(local, children) { + this.local = local && local.length ? local : none; + this.children = children && children.length ? children : none; + }; + + // :: (Node, [Decoration]) → DecorationSet + // Create a set of decorations, using the structure of the given + // document. + DecorationSet.create = function create (doc, decorations) { + return decorations.length ? buildTree(decorations, doc, 0, noSpec) : empty + }; + + // :: (?number, ?number, ?(spec: Object) → bool) → [Decoration] + // Find all decorations in this set which touch the given range + // (including decorations that start or end directly at the + // boundaries) and match the given predicate on their spec. When + // `start` and `end` are omitted, all decorations in the set are + // considered. When `predicate` isn't given, all decorations are + // assumed to match. + DecorationSet.prototype.find = function find (start, end, predicate) { + var result = []; + this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate); + return result + }; + + DecorationSet.prototype.findInner = function findInner (start, end, result, offset, predicate) { + for (var i = 0; i < this.local.length; i++) { + var span = this.local[i]; + if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec))) + { result.push(span.copy(span.from + offset, span.to + offset)); } + } + for (var i$1 = 0; i$1 < this.children.length; i$1 += 3) { + if (this.children[i$1] < end && this.children[i$1 + 1] > start) { + var childOff = this.children[i$1] + 1; + this.children[i$1 + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate); + } + } + }; + + // :: (Mapping, Node, ?Object) → DecorationSet + // Map the set of decorations in response to a change in the + // document. + // + // options::- An optional set of options. + // + // onRemove:: ?(decorationSpec: Object) + // When given, this function will be called for each decoration + // that gets dropped as a result of the mapping, passing the + // spec of that decoration. + DecorationSet.prototype.map = function map (mapping, doc, options) { + if (this == empty || mapping.maps.length == 0) { return this } + return this.mapInner(mapping, doc, 0, 0, options || noSpec) + }; + + DecorationSet.prototype.mapInner = function mapInner (mapping, node, offset, oldOffset, options) { + var newLocal; + for (var i = 0; i < this.local.length; i++) { + var mapped = this.local[i].map(mapping, offset, oldOffset); + if (mapped && mapped.type.valid(node, mapped)) { (newLocal || (newLocal = [])).push(mapped); } + else if (options.onRemove) { options.onRemove(this.local[i].spec); } + } + + if (this.children.length) + { return mapChildren(this.children, newLocal, mapping, node, offset, oldOffset, options) } + else + { return newLocal ? new DecorationSet(newLocal.sort(byPos)) : empty } + }; + + // :: (Node, [Decoration]) → DecorationSet + // Add the given array of decorations to the ones in the set, + // producing a new set. Needs access to the current document to + // create the appropriate tree structure. + DecorationSet.prototype.add = function add (doc, decorations) { + if (!decorations.length) { return this } + if (this == empty) { return DecorationSet.create(doc, decorations) } + return this.addInner(doc, decorations, 0) + }; + + DecorationSet.prototype.addInner = function addInner (doc, decorations, offset) { + var this$1 = this; + + var children, childIndex = 0; + doc.forEach(function (childNode, childOffset) { + var baseOffset = childOffset + offset, found; + if (!(found = takeSpansForNode(decorations, childNode, baseOffset))) { return } + + if (!children) { children = this$1.children.slice(); } + while (childIndex < children.length && children[childIndex] < childOffset) { childIndex += 3; } + if (children[childIndex] == childOffset) + { children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found, baseOffset + 1); } + else + { children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found, childNode, baseOffset + 1, noSpec)); } + childIndex += 3; + }); + + var local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset); + return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, + children || this.children) + }; + + // :: ([Decoration]) → DecorationSet + // Create a new set that contains the decorations in this set, minus + // the ones in the given array. + DecorationSet.prototype.remove = function remove (decorations) { + if (decorations.length == 0 || this == empty) { return this } + return this.removeInner(decorations, 0) + }; + + DecorationSet.prototype.removeInner = function removeInner (decorations, offset) { + var children = this.children, local = this.local; + for (var i = 0; i < children.length; i += 3) { + var found = (void 0), from = children[i] + offset, to = children[i + 1] + offset; + for (var j = 0, span = (void 0); j < decorations.length; j++) { if (span = decorations[j]) { + if (span.from > from && span.to < to) { + decorations[j] = null + ;(found || (found = [])).push(span); + } + } } + if (!found) { continue } + if (children == this.children) { children = this.children.slice(); } + var removed = children[i + 2].removeInner(found, from + 1); + if (removed != empty) { + children[i + 2] = removed; + } else { + children.splice(i, 3); + i -= 3; + } + } + if (local.length) { for (var i$1 = 0, span$1 = (void 0); i$1 < decorations.length; i$1++) { if (span$1 = decorations[i$1]) { + for (var j$1 = 0; j$1 < local.length; j$1++) { if (local[j$1].eq(span$1, offset)) { + if (local == this.local) { local = this.local.slice(); } + local.splice(j$1--, 1); + } } + } } } + if (children == this.children && local == this.local) { return this } + return local.length || children.length ? new DecorationSet(local, children) : empty + }; + + DecorationSet.prototype.forChild = function forChild (offset, node) { + if (this == empty) { return this } + if (node.isLeaf) { return DecorationSet.empty } + + var child, local; + for (var i = 0; i < this.children.length; i += 3) { if (this.children[i] >= offset) { + if (this.children[i] == offset) { child = this.children[i + 2]; } + break + } } + var start = offset + 1, end = start + node.content.size; + for (var i$1 = 0; i$1 < this.local.length; i$1++) { + var dec = this.local[i$1]; + if (dec.from < end && dec.to > start && (dec.type instanceof InlineType)) { + var from = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start; + if (from < to) { (local || (local = [])).push(dec.copy(from, to)); } + } + } + if (local) { + var localSet = new DecorationSet(local.sort(byPos)); + return child ? new DecorationGroup([localSet, child]) : localSet + } + return child || empty + }; + + DecorationSet.prototype.eq = function eq (other) { + if (this == other) { return true } + if (!(other instanceof DecorationSet) || + this.local.length != other.local.length || + this.children.length != other.children.length) { return false } + for (var i = 0; i < this.local.length; i++) + { if (!this.local[i].eq(other.local[i])) { return false } } + for (var i$1 = 0; i$1 < this.children.length; i$1 += 3) + { if (this.children[i$1] != other.children[i$1] || + this.children[i$1 + 1] != other.children[i$1 + 1] || + !this.children[i$1 + 2].eq(other.children[i$1 + 2])) { return false } } + return true + }; + + DecorationSet.prototype.locals = function locals (node) { + return removeOverlap(this.localsInner(node)) + }; + + DecorationSet.prototype.localsInner = function localsInner (node) { + if (this == empty) { return none } + if (node.inlineContent || !this.local.some(InlineType.is)) { return this.local } + var result = []; + for (var i = 0; i < this.local.length; i++) { + if (!(this.local[i].type instanceof InlineType)) + { result.push(this.local[i]); } + } + return result + }; + + var empty = new DecorationSet(); + + // :: DecorationSet + // The empty set of decorations. + DecorationSet.empty = empty; + + DecorationSet.removeOverlap = removeOverlap; + + // :- An abstraction that allows the code dealing with decorations to + // treat multiple DecorationSet objects as if it were a single object + // with (a subset of) the same interface. + var DecorationGroup = function DecorationGroup(members) { + this.members = members; + }; + + DecorationGroup.prototype.forChild = function forChild (offset, child) { + if (child.isLeaf) { return DecorationSet.empty } + var found = []; + for (var i = 0; i < this.members.length; i++) { + var result = this.members[i].forChild(offset, child); + if (result == empty) { continue } + if (result instanceof DecorationGroup) { found = found.concat(result.members); } + else { found.push(result); } + } + return DecorationGroup.from(found) + }; + + DecorationGroup.prototype.eq = function eq (other) { + if (!(other instanceof DecorationGroup) || + other.members.length != this.members.length) { return false } + for (var i = 0; i < this.members.length; i++) + { if (!this.members[i].eq(other.members[i])) { return false } } + return true + }; + + DecorationGroup.prototype.locals = function locals (node) { + var result, sorted = true; + for (var i = 0; i < this.members.length; i++) { + var locals = this.members[i].localsInner(node); + if (!locals.length) { continue } + if (!result) { + result = locals; + } else { + if (sorted) { + result = result.slice(); + sorted = false; + } + for (var j = 0; j < locals.length; j++) { result.push(locals[j]); } + } + } + return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none + }; + + // : ([DecorationSet]) → union + // Create a group for the given array of decoration sets, or return + // a single set when possible. + DecorationGroup.from = function from (members) { + switch (members.length) { + case 0: return empty + case 1: return members[0] + default: return new DecorationGroup(members) + } + }; + + function mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) { + var children = oldChildren.slice(); + + // Mark the children that are directly touched by changes, and + // move those that are after the changes. + var shift = function (oldStart, oldEnd, newStart, newEnd) { + for (var i = 0; i < children.length; i += 3) { + var end = children[i + 1], dSize = (void 0); + if (end == -1 || oldStart > end + oldOffset) { continue } + if (oldEnd >= children[i] + oldOffset) { + children[i + 1] = -1; + } else if (newStart >= offset && (dSize = (newEnd - newStart) - (oldEnd - oldStart))) { + children[i] += dSize; + children[i + 1] += dSize; + } + } + }; + for (var i = 0; i < mapping.maps.length; i++) { mapping.maps[i].forEach(shift); } + + // Find the child nodes that still correspond to a single node, + // recursively call mapInner on them and update their positions. + var mustRebuild = false; + for (var i$1 = 0; i$1 < children.length; i$1 += 3) { if (children[i$1 + 1] == -1) { // Touched nodes + var from = mapping.map(oldChildren[i$1] + oldOffset), fromLocal = from - offset; + if (fromLocal < 0 || fromLocal >= node.content.size) { + mustRebuild = true; + continue + } + // Must read oldChildren because children was tagged with -1 + var to = mapping.map(oldChildren[i$1 + 1] + oldOffset, -1), toLocal = to - offset; + var ref = node.content.findIndex(fromLocal); + var index = ref.index; + var childOffset = ref.offset; + var childNode = node.maybeChild(index); + if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) { + var mapped = children[i$1 + 2].mapInner(mapping, childNode, from + 1, oldChildren[i$1] + oldOffset + 1, options); + if (mapped != empty) { + children[i$1] = fromLocal; + children[i$1 + 1] = toLocal; + children[i$1 + 2] = mapped; + } else { + children[i$1 + 1] = -2; + mustRebuild = true; + } + } else { + mustRebuild = true; + } + } } + + // Remaining children must be collected and rebuilt into the appropriate structure + if (mustRebuild) { + var decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal || [], mapping, + offset, oldOffset, options); + var built = buildTree(decorations, node, 0, options); + newLocal = built.local; + for (var i$2 = 0; i$2 < children.length; i$2 += 3) { if (children[i$2 + 1] < 0) { + children.splice(i$2, 3); + i$2 -= 3; + } } + for (var i$3 = 0, j = 0; i$3 < built.children.length; i$3 += 3) { + var from$1 = built.children[i$3]; + while (j < children.length && children[j] < from$1) { j += 3; } + children.splice(j, 0, built.children[i$3], built.children[i$3 + 1], built.children[i$3 + 2]); + } + } + + return new DecorationSet(newLocal && newLocal.sort(byPos), children) + } + + function moveSpans(spans, offset) { + if (!offset || !spans.length) { return spans } + var result = []; + for (var i = 0; i < spans.length; i++) { + var span = spans[i]; + result.push(new Decoration(span.from + offset, span.to + offset, span.type)); + } + return result + } + + function mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) { + // Gather all decorations from the remaining marked children + function gather(set, oldOffset) { + for (var i = 0; i < set.local.length; i++) { + var mapped = set.local[i].map(mapping, offset, oldOffset); + if (mapped) { decorations.push(mapped); } + else if (options.onRemove) { options.onRemove(set.local[i].spec); } + } + for (var i$1 = 0; i$1 < set.children.length; i$1 += 3) + { gather(set.children[i$1 + 2], set.children[i$1] + oldOffset + 1); } + } + for (var i = 0; i < children.length; i += 3) { if (children[i + 1] == -1) + { gather(children[i + 2], oldChildren[i] + oldOffset + 1); } } + + return decorations + } + + function takeSpansForNode(spans, node, offset) { + if (node.isLeaf) { return null } + var end = offset + node.nodeSize, found = null; + for (var i = 0, span = (void 0); i < spans.length; i++) { + if ((span = spans[i]) && span.from > offset && span.to < end) { + (found || (found = [])).push(span); + spans[i] = null; + } + } + return found + } + + function withoutNulls(array) { + var result = []; + for (var i = 0; i < array.length; i++) + { if (array[i] != null) { result.push(array[i]); } } + return result + } + + // : ([Decoration], Node, number) → DecorationSet + // Build up a tree that corresponds to a set of decorations. `offset` + // is a base offset that should be subtractet from the `from` and `to` + // positions in the spans (so that we don't have to allocate new spans + // for recursive calls). + function buildTree(spans, node, offset, options) { + var children = [], hasNulls = false; + node.forEach(function (childNode, localStart) { + var found = takeSpansForNode(spans, childNode, localStart + offset); + if (found) { + hasNulls = true; + var subtree = buildTree(found, childNode, offset + localStart + 1, options); + if (subtree != empty) + { children.push(localStart, localStart + childNode.nodeSize, subtree); } + } + }); + var locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos); + for (var i = 0; i < locals.length; i++) { if (!locals[i].type.valid(node, locals[i])) { + if (options.onRemove) { options.onRemove(locals[i].spec); } + locals.splice(i--, 1); + } } + return locals.length || children.length ? new DecorationSet(locals, children) : empty + } + + // : (Decoration, Decoration) → number + // Used to sort decorations so that ones with a low start position + // come first, and within a set with the same start position, those + // with an smaller end position come first. + function byPos(a, b) { + return a.from - b.from || a.to - b.to + } + + // : ([Decoration]) → [Decoration] + // Scan a sorted array of decorations for partially overlapping spans, + // and split those so that only fully overlapping spans are left (to + // make subsequent rendering easier). Will return the input array if + // no partially overlapping spans are found (the common case). + function removeOverlap(spans) { + var working = spans; + for (var i = 0; i < working.length - 1; i++) { + var span = working[i]; + if (span.from != span.to) { for (var j = i + 1; j < working.length; j++) { + var next = working[j]; + if (next.from == span.from) { + if (next.to != span.to) { + if (working == spans) { working = spans.slice(); } + // Followed by a partially overlapping larger span. Split that + // span. + working[j] = next.copy(next.from, span.to); + insertAhead(working, j + 1, next.copy(span.to, next.to)); + } + continue + } else { + if (next.from < span.to) { + if (working == spans) { working = spans.slice(); } + // The end of this one overlaps with a subsequent span. Split + // this one. + working[i] = span.copy(span.from, next.from); + insertAhead(working, j, span.copy(next.from, span.to)); + } + break + } + } } + } + return working + } + + function insertAhead(array, i, deco) { + while (i < array.length && byPos(deco, array[i]) > 0) { i++; } + array.splice(i, 0, deco); + } + + // : (EditorView) → union + // Get the decorations associated with the current props of a view. + function viewDecorations(view) { + var found = []; + view.someProp("decorations", function (f) { + var result = f(view.state); + if (result && result != empty) { found.push(result); } + }); + if (view.cursorWrapper) + { found.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco])); } + return DecorationGroup.from(found) + } + + // ::- An editor view manages the DOM structure that represents an + // editable document. Its state and behavior are determined by its + // [props](#view.DirectEditorProps). + var EditorView = function EditorView(place, props) { + this._props = props; + // :: EditorState + // The view's current [state](#state.EditorState). + this.state = props.state; + + this.dispatch = this.dispatch.bind(this); + + this._root = null; + this.focused = false; + // Kludge used to work around a Chrome bug + this.trackWrites = null; + + // :: dom.Element + // An editable DOM node containing the document. (You probably + // should not directly interfere with its content.) + this.dom = (place && place.mount) || document.createElement("div"); + if (place) { + if (place.appendChild) { place.appendChild(this.dom); } + else if (place.apply) { place(this.dom); } + else if (place.mount) { this.mounted = true; } + } + + // :: bool + // Indicates whether the editor is currently [editable](#view.EditorProps.editable). + this.editable = getEditable(this); + this.markCursor = null; + this.cursorWrapper = null; + updateCursorWrapper(this); + this.nodeViews = buildNodeViews(this); + this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this); + + this.lastSelectedViewDesc = null; + // :: ?{slice: Slice, move: bool} + // When editor content is being dragged, this object contains + // information about the dragged slice and whether it is being + // copied or moved. At any other time, it is null. + this.dragging = null; + + initInput(this); + + this.pluginViews = []; + this.updatePluginViews(); + }; + + var prototypeAccessors$2$1 = { props: { configurable: true },root: { configurable: true } }; + + // composing:: boolean + // Holds `true` when a + // [composition](https://developer.mozilla.org/en-US/docs/Mozilla/IME_handling_guide) + // is active. + + // :: DirectEditorProps + // The view's current [props](#view.EditorProps). + prototypeAccessors$2$1.props.get = function () { + if (this._props.state != this.state) { + var prev = this._props; + this._props = {}; + for (var name in prev) { this._props[name] = prev[name]; } + this._props.state = this.state; + } + return this._props + }; + + // :: (DirectEditorProps) + // Update the view's props. Will immediately cause an update to + // the DOM. + EditorView.prototype.update = function update (props) { + if (props.handleDOMEvents != this._props.handleDOMEvents) { ensureListeners(this); } + this._props = props; + this.updateStateInner(props.state, true); + }; + + // :: (DirectEditorProps) + // Update the view by updating existing props object with the object + // given as argument. Equivalent to `view.update(Object.assign({}, + // view.props, props))`. + EditorView.prototype.setProps = function setProps (props) { + var updated = {}; + for (var name in this._props) { updated[name] = this._props[name]; } + updated.state = this.state; + for (var name$1 in props) { updated[name$1] = props[name$1]; } + this.update(updated); + }; + + // :: (EditorState) + // Update the editor's `state` prop, without touching any of the + // other props. + EditorView.prototype.updateState = function updateState (state) { + this.updateStateInner(state, this.state.plugins != state.plugins); + }; + + EditorView.prototype.updateStateInner = function updateStateInner (state, reconfigured) { + var this$1 = this; + + var prev = this.state, redraw = false, updateSel = false; + // When stored marks are added, stop composition, so that they can + // be displayed. + if (state.storedMarks && this.composing) { + clearComposition(this); + updateSel = true; + } + this.state = state; + if (reconfigured) { + var nodeViews = buildNodeViews(this); + if (changedNodeViews(nodeViews, this.nodeViews)) { + this.nodeViews = nodeViews; + redraw = true; + } + ensureListeners(this); + } + + this.editable = getEditable(this); + updateCursorWrapper(this); + var innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this); + + var scroll = reconfigured ? "reset" + : state.scrollToSelection > prev.scrollToSelection ? "to selection" : "preserve"; + var updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco); + if (updateDoc || !state.selection.eq(prev.selection)) { updateSel = true; } + var oldScrollPos = scroll == "preserve" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this); + + if (updateSel) { + this.domObserver.stop(); + // Work around an issue in Chrome, IE, and Edge where changing + // the DOM around an active selection puts it into a broken + // state where the thing the user sees differs from the + // selection reported by the Selection object (#710, #973, + // #1011, #1013, #1035). + var forceSelUpdate = updateDoc && (result.ie || result.chrome) && !this.composing && + !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection); + if (updateDoc) { + // If the node that the selection points into is written to, + // Chrome sometimes starts misreporting the selection, so this + // tracks that and forces a selection reset when our update + // did write to the node. + var chromeKludge = result.chrome ? (this.trackWrites = this.root.getSelection().focusNode) : null; + if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) { + this.docView.updateOuterDeco([]); + this.docView.destroy(); + this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this); + } + if (chromeKludge && !this.trackWrites) { forceSelUpdate = true; } + } + // Work around for an issue where an update arriving right between + // a DOM selection change and the "selectionchange" event for it + // can cause a spurious DOM selection update, disrupting mouse + // drag selection. + if (forceSelUpdate || + !(this.mouseDown && this.domObserver.currentSelection.eq(this.root.getSelection()) && anchorInRightPlace(this))) { + selectionToDOM(this, forceSelUpdate); + } else { + syncNodeSelection(this, state.selection); + this.domObserver.setCurSelection(); + } + this.domObserver.start(); + } + + this.updatePluginViews(prev); + + if (scroll == "reset") { + this.dom.scrollTop = 0; + } else if (scroll == "to selection") { + var startDOM = this.root.getSelection().focusNode; + if (this.someProp("handleScrollToSelection", function (f) { return f(this$1); })) + ; // Handled + else if (state.selection instanceof NodeSelection) + { scrollRectIntoView(this, this.docView.domAfterPos(state.selection.from).getBoundingClientRect(), startDOM); } + else + { scrollRectIntoView(this, this.coordsAtPos(state.selection.head, 1), startDOM); } + } else if (oldScrollPos) { + resetScrollPos(oldScrollPos); + } + }; + + EditorView.prototype.destroyPluginViews = function destroyPluginViews () { + var view; + while (view = this.pluginViews.pop()) { if (view.destroy) { view.destroy(); } } + }; + + EditorView.prototype.updatePluginViews = function updatePluginViews (prevState) { + if (!prevState || prevState.plugins != this.state.plugins) { + this.destroyPluginViews(); + for (var i = 0; i < this.state.plugins.length; i++) { + var plugin = this.state.plugins[i]; + if (plugin.spec.view) { this.pluginViews.push(plugin.spec.view(this)); } + } + } else { + for (var i$1 = 0; i$1 < this.pluginViews.length; i$1++) { + var pluginView = this.pluginViews[i$1]; + if (pluginView.update) { pluginView.update(this, prevState); } + } + } + }; + + // :: (string, ?(prop: *) → *) → * + // Goes over the values of a prop, first those provided directly, + // then those from plugins (in order), and calls `f` every time a + // non-undefined value is found. When `f` returns a truthy value, + // that is immediately returned. When `f` isn't provided, it is + // treated as the identity function (the prop value is returned + // directly). + EditorView.prototype.someProp = function someProp (propName, f) { + var prop = this._props && this._props[propName], value; + if (prop != null && (value = f ? f(prop) : prop)) { return value } + var plugins = this.state.plugins; + if (plugins) { for (var i = 0; i < plugins.length; i++) { + var prop$1 = plugins[i].props[propName]; + if (prop$1 != null && (value = f ? f(prop$1) : prop$1)) { return value } + } } + }; + + // :: () → bool + // Query whether the view has focus. + EditorView.prototype.hasFocus = function hasFocus () { + return this.root.activeElement == this.dom + }; + + // :: () + // Focus the editor. + EditorView.prototype.focus = function focus () { + this.domObserver.stop(); + if (this.editable) { focusPreventScroll(this.dom); } + selectionToDOM(this); + this.domObserver.start(); + }; + + // :: union + // Get the document root in which the editor exists. This will + // usually be the top-level `document`, but might be a [shadow + // DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM) + // root if the editor is inside one. + prototypeAccessors$2$1.root.get = function () { + var cached = this._root; + if (cached == null) { for (var search = this.dom.parentNode; search; search = search.parentNode) { + if (search.nodeType == 9 || (search.nodeType == 11 && search.host)) { + if (!search.getSelection) { Object.getPrototypeOf(search).getSelection = function () { return document.getSelection(); }; } + return this._root = search + } + } } + return cached || document + }; + + // :: ({left: number, top: number}) → ?{pos: number, inside: number} + // Given a pair of viewport coordinates, return the document + // position that corresponds to them. May return null if the given + // coordinates aren't inside of the editor. When an object is + // returned, its `pos` property is the position nearest to the + // coordinates, and its `inside` property holds the position of the + // inner node that the position falls inside of, or -1 if it is at + // the top level, not in any node. + EditorView.prototype.posAtCoords = function posAtCoords$1 (coords) { + return posAtCoords(this, coords) + }; + + // :: (number, number) → {left: number, right: number, top: number, bottom: number} + // Returns the viewport rectangle at a given document position. + // `left` and `right` will be the same number, as this returns a + // flat cursor-ish rectangle. If the position is between two things + // that aren't directly adjacent, `side` determines which element is + // used. When < 0, the element before the position is used, + // otherwise the element after. + EditorView.prototype.coordsAtPos = function coordsAtPos$1 (pos, side) { + if ( side === void 0 ) side = 1; + + return coordsAtPos(this, pos, side) + }; + + // :: (number) → {node: dom.Node, offset: number} + // Find the DOM position that corresponds to the given document + // position. Note that you should **not** mutate the editor's + // internal DOM, only inspect it (and even that is usually not + // necessary). + EditorView.prototype.domAtPos = function domAtPos (pos) { + return this.docView.domFromPos(pos) + }; + + // :: (number) → ?dom.Node + // Find the DOM node that represents the document node after the + // given position. May return `null` when the position doesn't point + // in front of a node or if the node is inside an opaque node view. + // + // This is intended to be able to call things like + // `getBoundingClientRect` on that DOM node. Do **not** mutate the + // editor DOM directly, or add styling this way, since that will be + // immediately overriden by the editor as it redraws the node. + EditorView.prototype.nodeDOM = function nodeDOM (pos) { + var desc = this.docView.descAt(pos); + return desc ? desc.nodeDOM : null + }; + + // :: (dom.Node, number, ?number) → number + // Find the document position that corresponds to a given DOM + // position. (Whenever possible, it is preferable to inspect the + // document structure directly, rather than poking around in the + // DOM, but sometimes—for example when interpreting an event + // target—you don't have a choice.) + // + // The `bias` parameter can be used to influence which side of a DOM + // node to use when the position is inside a leaf node. + EditorView.prototype.posAtDOM = function posAtDOM (node, offset, bias) { + if ( bias === void 0 ) bias = -1; + + var pos = this.docView.posFromDOM(node, offset, bias); + if (pos == null) { throw new RangeError("DOM position not inside the editor") } + return pos + }; + + // :: (union<"up", "down", "left", "right", "forward", "backward">, ?EditorState) → bool + // Find out whether the selection is at the end of a textblock when + // moving in a given direction. When, for example, given `"left"`, + // it will return true if moving left from the current cursor + // position would leave that position's parent textblock. Will apply + // to the view's current state by default, but it is possible to + // pass a different state. + EditorView.prototype.endOfTextblock = function endOfTextblock$1 (dir, state) { + return endOfTextblock(this, state || this.state, dir) + }; + + // :: () + // Removes the editor from the DOM and destroys all [node + // views](#view.NodeView). + EditorView.prototype.destroy = function destroy () { + if (!this.docView) { return } + destroyInput(this); + this.destroyPluginViews(); + if (this.mounted) { + this.docView.update(this.state.doc, [], viewDecorations(this), this); + this.dom.textContent = ""; + } else if (this.dom.parentNode) { + this.dom.parentNode.removeChild(this.dom); + } + this.docView.destroy(); + this.docView = null; + }; + + // Used for testing. + EditorView.prototype.dispatchEvent = function dispatchEvent$1 (event) { + return dispatchEvent(this, event) + }; + + // :: (Transaction) + // Dispatch a transaction. Will call + // [`dispatchTransaction`](#view.DirectEditorProps.dispatchTransaction) + // when given, and otherwise defaults to applying the transaction to + // the current state and calling + // [`updateState`](#view.EditorView.updateState) with the result. + // This method is bound to the view instance, so that it can be + // easily passed around. + EditorView.prototype.dispatch = function dispatch (tr) { + var dispatchTransaction = this._props.dispatchTransaction; + if (dispatchTransaction) { dispatchTransaction.call(this, tr); } + else { this.updateState(this.state.apply(tr)); } + }; + + Object.defineProperties( EditorView.prototype, prototypeAccessors$2$1 ); + + function computeDocDeco(view) { + var attrs = Object.create(null); + attrs.class = "ProseMirror"; + attrs.contenteditable = String(view.editable); + + view.someProp("attributes", function (value) { + if (typeof value == "function") { value = value(view.state); } + if (value) { for (var attr in value) { + if (attr == "class") + { attrs.class += " " + value[attr]; } + else if (!attrs[attr] && attr != "contenteditable" && attr != "nodeName") + { attrs[attr] = String(value[attr]); } + } } + }); + + return [Decoration.node(0, view.state.doc.content.size, attrs)] + } + + function updateCursorWrapper(view) { + if (view.markCursor) { + var dom = document.createElement("img"); + dom.setAttribute("mark-placeholder", "true"); + view.cursorWrapper = {dom: dom, deco: Decoration.widget(view.state.selection.head, dom, {raw: true, marks: view.markCursor})}; + } else { + view.cursorWrapper = null; + } + } + + function getEditable(view) { + return !view.someProp("editable", function (value) { return value(view.state) === false; }) + } + + function selectionContextChanged(sel1, sel2) { + var depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head)); + return sel1.$anchor.start(depth) != sel2.$anchor.start(depth) + } + + function buildNodeViews(view) { + var result = {}; + view.someProp("nodeViews", function (obj) { + for (var prop in obj) { if (!Object.prototype.hasOwnProperty.call(result, prop)) + { result[prop] = obj[prop]; } } + }); + return result + } + + function changedNodeViews(a, b) { + var nA = 0, nB = 0; + for (var prop in a) { + if (a[prop] != b[prop]) { return true } + nA++; + } + for (var _ in b) { nB++; } + return nA != nB + } + + /** + * Mutual exclude for JavaScript. + * + * @module mutex + */ + + /** + * @callback mutex + * @param {function():void} cb Only executed when this mutex is not in the current stack + * @param {function():void} [elseCb] Executed when this mutex is in the current stack + */ + + /** + * Creates a mutual exclude function with the following property: + * + * ```js + * const mutex = createMutex() + * mutex(() => { + * // This function is immediately executed + * mutex(() => { + * // This function is not executed, as the mutex is already active. + * }) + * }) + * ``` + * + * @return {mutex} A mutual exclude function + * @public + */ + const createMutex = () => { + let token = true; + return (f, g) => { + if (token) { + token = false; + try { + f(); + } finally { + token = true; + } + } else if (g !== undefined) { + g(); + } + } + }; + + /** + * The unique prosemirror plugin key for syncPlugin + * + * @public + */ + const ySyncPluginKey = new PluginKey('y-sync'); + + /** + * The unique prosemirror plugin key for undoPlugin + * + * @public + */ + const yUndoPluginKey = new PluginKey('y-undo'); + + /** + * The unique prosemirror plugin key for cursorPlugin + * + * @public + */ + const yCursorPluginKey = new PluginKey('yjs-cursor'); + + /** + * @module bindings/prosemirror + */ + + /** + * @param {Y.Item} item + * @param {Y.Snapshot} [snapshot] + */ + const isVisible$1 = (item, snapshot) => snapshot === undefined ? !item.deleted : (snapshot.sv.has(item.id.client) && /** @type {number} */ (snapshot.sv.get(item.id.client)) > item.id.clock && !isDeleted(snapshot.ds, item.id)); + + /** + * Either a node if type is YXmlElement or an Array of text nodes if YXmlText + * @typedef {Map>} ProsemirrorMapping + */ + + /** + * @typedef {Object} ColorDef + * @property {string} ColorDef.light + * @property {string} ColorDef.dark + */ + + /** + * @typedef {Object} YSyncOpts + * @property {Array} [YSyncOpts.colors] + * @property {Map} [YSyncOpts.colorMapping] + * @property {Y.PermanentUserData|null} [YSyncOpts.permanentUserData] + */ + + /** + * @type {Array} + */ + const defaultColors = [{ light: '#ecd44433', dark: '#ecd444' }]; + + /** + * @param {Map} colorMapping + * @param {Array} colors + * @param {string} user + * @return {ColorDef} + */ + const getUserColor = (colorMapping, colors, user) => { + if (!colorMapping.has(user)) { + colorMapping.set(user, colors[colorMapping.size % colors.length]); + } + return /** @type {ColorDef} */ (colorMapping.get(user)); + }; + + /** + * This plugin listens to changes in prosemirror view and keeps yXmlState and view in sync. + * + * This plugin also keeps references to the type and the shared document so other plugins can access it. + * @param {Y.XmlFragment} yXmlFragment + * @param {YSyncOpts} opts + * @return {any} Returns a prosemirror plugin that binds to this type + */ + const ySyncPlugin = (yXmlFragment, { colors = defaultColors, colorMapping = new Map(), permanentUserData = null } = {}) => { + let changedInitialContent = false; + const plugin = new Plugin({ + props: { + editable: (state) => { + const syncState = ySyncPluginKey.getState(state); + return syncState.snapshot == null && syncState.prevSnapshot == null + } + }, + key: ySyncPluginKey, + state: { + init: (initargs, state) => { + return { + type: yXmlFragment, + doc: yXmlFragment.doc, + binding: null, + snapshot: null, + prevSnapshot: null, + isChangeOrigin: false, + colors, + colorMapping, + permanentUserData + } + }, + apply: (tr, pluginState) => { + const change = tr.getMeta(ySyncPluginKey); + if (change !== undefined) { + pluginState = Object.assign({}, pluginState); + for (const key in change) { + pluginState[key] = change[key]; + } + } + // always set isChangeOrigin. If undefined, this is not change origin. + pluginState.isChangeOrigin = change !== undefined && !!change.isChangeOrigin; + if (pluginState.binding !== null) { + if (change !== undefined && (change.snapshot != null || change.prevSnapshot != null)) { + // snapshot changed, rerender next + setTimeout(() => { + if (change.restore == null) { + pluginState.binding._renderSnapshot(change.snapshot, change.prevSnapshot, pluginState); + } else { + pluginState.binding._renderSnapshot(change.snapshot, change.snapshot, pluginState); + // reset to current prosemirror state + delete pluginState.restore; + delete pluginState.snapshot; + delete pluginState.prevSnapshot; + pluginState.binding._prosemirrorChanged(pluginState.binding.prosemirrorView.state.doc); + } + }, 0); + } + } + return pluginState + } + }, + view: view => { + + const binding = new ProsemirrorBinding(yXmlFragment, view); + binding._forceRerender(); + view.dispatch(view.state.tr.setMeta(ySyncPluginKey, { binding })); + + return { + update: () => { + const pluginState = plugin.getState(view.state); + if (pluginState.snapshot == null && pluginState.prevSnapshot == null) { + if (changedInitialContent || view.state.doc.content.findDiffStart(view.state.doc.type.createAndFill().content) != null) { + changedInitialContent = true; + binding._prosemirrorChanged(view.state.doc); + } + } + }, + destroy: () => { + binding.destroy(); + } + } + } + }); + return plugin + }; + + /** + * @param {any} tr + * @param {any} relSel + * @param {ProsemirrorBinding} binding + */ + const restoreRelativeSelection = (tr, relSel, binding) => { + if (relSel !== null && relSel.anchor !== null && relSel.head !== null) { + const anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping); + const head = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.head, binding.mapping); + if (anchor !== null && head !== null) { + tr = tr.setSelection(TextSelection.create(tr.doc, anchor, head)); + } + } + }; + + const getRelativeSelection = (pmbinding, state) => ({ + anchor: absolutePositionToRelativePosition(state.selection.anchor, pmbinding.type, pmbinding.mapping), + head: absolutePositionToRelativePosition(state.selection.head, pmbinding.type, pmbinding.mapping) + }); + + /** + * Binding for prosemirror. + * + * @protected + */ + class ProsemirrorBinding { + /** + * @param {Y.XmlFragment} yXmlFragment The bind source + * @param {any} prosemirrorView The target binding + */ + constructor (yXmlFragment, prosemirrorView) { + this.type = yXmlFragment; + this.prosemirrorView = prosemirrorView; + this.mux = createMutex(); + /** + * @type {ProsemirrorMapping} + */ + this.mapping = new Map(); + this._observeFunction = this._typeChanged.bind(this); + /** + * @type {Y.Doc} + */ + // @ts-ignore + this.doc = yXmlFragment.doc; + /** + * current selection as relative positions in the Yjs model + */ + this.beforeTransactionSelection = null; + this.beforeAllTransactions = () => { + if (this.beforeTransactionSelection === null) { + this.beforeTransactionSelection = getRelativeSelection(this, prosemirrorView.state); + } + }; + this.afterAllTransactions = () => { + this.beforeTransactionSelection = null; + }; + + this.doc.on('beforeAllTransactions', this.beforeAllTransactions); + this.doc.on('afterAllTransactions', this.afterAllTransactions); + yXmlFragment.observeDeep(this._observeFunction); + + this._domSelectionInView = null; + } + + _isLocalCursorInView () { + if (!this.prosemirrorView.hasFocus()) return false + if (isBrowser && this._domSelectionInView === null) { + // Calculate the domSelectionInView and clear by next tick after all events are finished + setTimeout(() => { + this._domSelectionInView = null; + }, 0); + this._domSelectionInView = this._isDomSelectionInView(); + } + return this._domSelectionInView + } + + _isDomSelectionInView () { + const selection = this.prosemirrorView._root.getSelection(); + + const range = this.prosemirrorView._root.createRange(); + range.setStart(selection.anchorNode, selection.anchorOffset); + range.setEnd(selection.focusNode, selection.focusOffset); + + // This is a workaround for an edgecase where getBoundingClientRect will + // return zero values if the selection is collapsed at the start of a newline + // see reference here: https://stackoverflow.com/a/59780954 + const rects = range.getClientRects(); + if (rects.length === 0) { + // probably buggy newline behavior, explicitly select the node contents + if (range.startContainer && range.collapsed) { + range.selectNodeContents(range.startContainer); + } + } + + const bounding = range.getBoundingClientRect(); + const documentElement = doc.documentElement; + + return bounding.bottom >= 0 && bounding.right >= 0 && + bounding.left <= (window.innerWidth || documentElement.clientWidth || 0) && + bounding.top <= (window.innerHeight || documentElement.clientHeight || 0) + } + + renderSnapshot (snapshot, prevSnapshot) { + if (!prevSnapshot) { + prevSnapshot = createSnapshot(createDeleteSet(), new Map()); + } + this.prosemirrorView.dispatch(this.prosemirrorView.state.tr.setMeta(ySyncPluginKey, { snapshot, prevSnapshot })); + } + + unrenderSnapshot () { + this.mapping = new Map(); + this.mux(() => { + const fragmentContent = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null); + // @ts-ignore + const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new Slice(new Fragment(fragmentContent), 0, 0)); + tr.setMeta(ySyncPluginKey, { snapshot: null, prevSnapshot: null }); + this.prosemirrorView.dispatch(tr); + }); + } + + _forceRerender () { + this.mapping = new Map(); + this.mux(() => { + let content = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null); + if (content.length) { + // @ts-ignore + const tr = this.prosemirrorView.state.tr.replaceWith(0, this.prosemirrorView.state.doc.content.size, new Fragment(content)); + this.prosemirrorView.dispatch(tr); + } + }); + } + + /** + * @param {Y.Snapshot} snapshot + * @param {Y.Snapshot} prevSnapshot + * @param {Object} pluginState + */ + _renderSnapshot (snapshot$1, prevSnapshot, pluginState) { + if (!snapshot$1) { + snapshot$1 = snapshot(this.doc); + } + // clear mapping because we are going to rerender + this.mapping = new Map(); + this.mux(() => { + this.doc.transact(transaction => { + // before rendering, we are going to sanitize ops and split deleted ops + // if they were deleted by seperate users. + const pud = pluginState.permanentUserData; + if (pud) { + pud.dss.forEach(ds => { + iterateDeletedStructs(transaction, ds, item => {}); + }); + } + const computeYChange = (type, id) => { + const user = type === 'added' ? pud.getUserByClientId(id.client) : pud.getUserByDeletedId(id); + return { + user, + type, + color: getUserColor(pluginState.colorMapping, pluginState.colors, user) + } + }; + // Create document fragment and render + const fragmentContent = typeListToArraySnapshot(this.type, new Snapshot(prevSnapshot.ds, snapshot$1.sv)).map(t => { + if (!t._item.deleted || isVisible$1(t._item, snapshot$1) || isVisible$1(t._item, prevSnapshot)) { + return createNodeFromYElement(t, this.prosemirrorView.state.schema, new Map(), snapshot$1, prevSnapshot, computeYChange) + } else { + // No need to render elements that are not visible by either snapshot. + // If a client adds and deletes content in the same snapshot the element is not visible by either snapshot. + return null + } + }).filter(n => n !== null); + // @ts-ignore + const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new Slice(new Fragment(fragmentContent), 0, 0)); + this.prosemirrorView.dispatch(tr); + }, ySyncPluginKey); + }); + } + + /** + * @param {Array} events + * @param {Y.Transaction} transaction + */ + _typeChanged (events, transaction) { + const syncState = ySyncPluginKey.getState(this.prosemirrorView.state); + if (events.length === 0 || syncState.snapshot != null || syncState.prevSnapshot != null) { + // drop out if snapshot is active + this.renderSnapshot(syncState.snapshot, syncState.prevSnapshot); + return + } + this.mux(() => { + /** + * @param {any} _ + * @param {Y.AbstractType} type + */ + const delType = (_, type) => this.mapping.delete(type); + iterateDeletedStructs(transaction, transaction.deleteSet, struct => struct.constructor === Item && this.mapping.delete(/** @type {Y.ContentType} */ (/** @type {Y.Item} */ (struct).content).type)); + transaction.changed.forEach(delType); + transaction.changedParentTypes.forEach(delType); + const fragmentContent = this.type.toArray().map(t => createNodeIfNotExists(/** @type {Y.XmlElement | Y.XmlHook} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null); + // @ts-ignore + let tr = this.prosemirrorView.state.tr.replaceWith(0, this.prosemirrorView.state.doc.content.size, new Fragment(fragmentContent)); + restoreRelativeSelection(tr, this.beforeTransactionSelection, this); + tr = tr.setMeta(ySyncPluginKey, { isChangeOrigin: true }); + if (this.beforeTransactionSelection !== null && this._isLocalCursorInView()) { + tr.scrollIntoView(); + } + this.prosemirrorView.dispatch(tr); + }); + } + + _prosemirrorChanged (doc) { + this.mux(() => { + this.doc.transact(() => { + updateYFragment(this.doc, this.type, doc, this.mapping); + this.beforeTransactionSelection = getRelativeSelection(this, this.prosemirrorView.state); + }, ySyncPluginKey); + }); + } + + destroy () { + this.type.unobserveDeep(this._observeFunction); + this.doc.off('beforeAllTransactions', this.beforeAllTransactions); + this.doc.off('afterAllTransactions', this.afterAllTransactions); + } + } + + /** + * @private + * @param {Y.XmlElement | Y.XmlHook} el + * @param {PMSchema} schema + * @param {ProsemirrorMapping} mapping + * @param {Y.Snapshot} [snapshot] + * @param {Y.Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', Y.ID):any} [computeYChange] + * @return {PMNode | null} + */ + const createNodeIfNotExists = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => { + const node = /** @type {PMNode} */ (mapping.get(el)); + if (node === undefined) { + if (el instanceof YXmlElement) { + return createNodeFromYElement(el, schema, mapping, snapshot, prevSnapshot, computeYChange) + } else { + throw methodUnimplemented() // we are currently not handling hooks + } + } + return node + }; + + /** + * @private + * @param {Y.XmlElement} el + * @param {any} schema + * @param {ProsemirrorMapping} mapping + * @param {Y.Snapshot} [snapshot] + * @param {Y.Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', Y.ID):any} [computeYChange] + * @return {PMNode | null} Returns node if node could be created. Otherwise it deletes the yjs type and returns null + */ + const createNodeFromYElement = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => { + const children = []; + const createChildren = type => { + if (type.constructor === YXmlElement) { + const n = createNodeIfNotExists(type, schema, mapping, snapshot, prevSnapshot, computeYChange); + if (n !== null) { + children.push(n); + } + } else { + const ns = createTextNodesFromYText(type, schema, mapping, snapshot, prevSnapshot, computeYChange); + if (ns !== null) { + ns.forEach(textchild => { + if (textchild !== null) { + children.push(textchild); + } + }); + } + } + }; + if (snapshot === undefined || prevSnapshot === undefined) { + el.toArray().forEach(createChildren); + } else { + typeListToArraySnapshot(el, new Snapshot(prevSnapshot.ds, snapshot.sv)).forEach(createChildren); + } + try { + const attrs = el.getAttributes(snapshot); + if (snapshot !== undefined) { + if (!isVisible$1(/** @type {Y.Item} */ (el._item), snapshot)) { + attrs.ychange = computeYChange ? computeYChange('removed', /** @type {Y.Item} */ (el._item).id) : { type: 'removed' }; + } else if (!isVisible$1(/** @type {Y.Item} */ (el._item), prevSnapshot)) { + attrs.ychange = computeYChange ? computeYChange('added', /** @type {Y.Item} */ (el._item).id) : { type: 'added' }; + } + } + const node = schema.node(el.nodeName, attrs, children); + mapping.set(el, node); + return node + } catch (e) { + // an error occured while creating the node. This is probably a result of a concurrent action. + /** @type {Y.Doc} */ (el.doc).transact(transaction => { + /** @type {Y.Item} */ (el._item).delete(transaction); + }, ySyncPluginKey); + mapping.delete(el); + return null + } + }; + + /** + * @private + * @param {Y.XmlText} text + * @param {any} schema + * @param {ProsemirrorMapping} mapping + * @param {Y.Snapshot} [snapshot] + * @param {Y.Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', Y.ID):any} [computeYChange] + * @return {Array|null} + */ + const createTextNodesFromYText = (text, schema, mapping, snapshot, prevSnapshot, computeYChange) => { + const nodes = []; + const deltas = text.toDelta(snapshot, prevSnapshot, computeYChange); + try { + for (let i = 0; i < deltas.length; i++) { + const delta = deltas[i]; + const marks = []; + for (const markName in delta.attributes) { + marks.push(schema.mark(markName, delta.attributes[markName])); + } + nodes.push(schema.text(delta.insert, marks)); + } + } catch (e) { + // an error occured while creating the node. This is probably a result of a concurrent action. + /** @type {Y.Doc} */ (text.doc).transact(transaction => { + /** @type {Y.Item} */ (text._item).delete(transaction); + }, ySyncPluginKey); + return null + } + // @ts-ignore + return nodes + }; + + /** + * @private + * @param {Array} nodes prosemirror node + * @param {ProsemirrorMapping} mapping + * @return {Y.XmlText} + */ + const createTypeFromTextNodes = (nodes, mapping) => { + const type = new YXmlText(); + const delta = nodes.map(node => ({ + // @ts-ignore + insert: node.text, + attributes: marksToAttributes(node.marks) + })); + type.applyDelta(delta); + mapping.set(type, nodes); + return type + }; + + /** + * @private + * @param {any} node prosemirror node + * @param {ProsemirrorMapping} mapping + * @return {Y.XmlElement} + */ + const createTypeFromElementNode = (node, mapping) => { + const type = new YXmlElement(node.type.name); + for (const key in node.attrs) { + const val = node.attrs[key]; + if (val !== null && key !== 'ychange') { + type.setAttribute(key, val); + } + } + type.insert(0, normalizePNodeContent(node).map(n => createTypeFromTextOrElementNode(n, mapping))); + mapping.set(type, node); + return type + }; + + /** + * @private + * @param {PMNode|Array} node prosemirror text node + * @param {ProsemirrorMapping} mapping + * @return {Y.XmlElement|Y.XmlText} + */ + const createTypeFromTextOrElementNode = (node, mapping) => node instanceof Array ? createTypeFromTextNodes(node, mapping) : createTypeFromElementNode(node, mapping); + + const equalAttrs$1 = (pattrs, yattrs) => { + const keys = Object.keys(pattrs).filter(key => pattrs[key] !== null); + let eq = keys.length === Object.keys(yattrs).filter(key => yattrs[key] !== null).length; + for (let i = 0; i < keys.length && eq; i++) { + const key = keys[i]; + const l = pattrs[key]; + const r = yattrs[key]; + eq = key === 'ychange' || l === r || (typeof l === 'object' && typeof r === 'object' && equalAttrs$1(l, r)); + } + return eq + }; + + /** + * @typedef {Array|PMNode>} NormalizedPNodeContent + */ + + /** + * @param {any} pnode + * @return {NormalizedPNodeContent} + */ + const normalizePNodeContent = pnode => { + const c = pnode.content.content; + const res = []; + for (let i = 0; i < c.length; i++) { + const n = c[i]; + if (n.isText) { + const textNodes = []; + for (let tnode = c[i]; i < c.length && tnode.isText; tnode = c[++i]) { + textNodes.push(tnode); + } + i--; + res.push(textNodes); + } else { + res.push(n); + } + } + return res + }; + + /** + * @param {Y.XmlText} ytext + * @param {Array} ptexts + */ + const equalYTextPText = (ytext, ptexts) => { + const delta = ytext.toDelta(); + return delta.length === ptexts.length && delta.every((d, i) => d.insert === /** @type {any} */ (ptexts[i]).text && keys(d.attributes || {}).length === ptexts[i].marks.length && ptexts[i].marks.every(mark => equalAttrs$1(d.attributes[mark.type.name] || {}, mark.attrs))) + }; + + /** + * @param {Y.XmlElement|Y.XmlText|Y.XmlHook} ytype + * @param {any|Array} pnode + */ + const equalYTypePNode = (ytype, pnode) => { + if (ytype instanceof YXmlElement && !(pnode instanceof Array) && matchNodeName(ytype, pnode)) { + const normalizedContent = normalizePNodeContent(pnode); + return ytype._length === normalizedContent.length && equalAttrs$1(ytype.getAttributes(), pnode.attrs) && ytype.toArray().every((ychild, i) => equalYTypePNode(ychild, normalizedContent[i])) + } + return ytype instanceof YXmlText && pnode instanceof Array && equalYTextPText(ytype, pnode) + }; + + /** + * @param {PMNode | Array | undefined} mapped + * @param {PMNode | Array} pcontent + */ + const mappedIdentity = (mapped, pcontent) => mapped === pcontent || (mapped instanceof Array && pcontent instanceof Array && mapped.length === pcontent.length && mapped.every((a, i) => pcontent[i] === a)); + + /** + * @param {Y.XmlElement} ytype + * @param {PMNode} pnode + * @param {ProsemirrorMapping} mapping + * @return {{ foundMappedChild: boolean, equalityFactor: number }} + */ + const computeChildEqualityFactor = (ytype, pnode, mapping) => { + const yChildren = ytype.toArray(); + const pChildren = normalizePNodeContent(pnode); + const pChildCnt = pChildren.length; + const yChildCnt = yChildren.length; + const minCnt = min(yChildCnt, pChildCnt); + let left = 0; + let right = 0; + let foundMappedChild = false; + for (; left < minCnt; left++) { + const leftY = yChildren[left]; + const leftP = pChildren[left]; + if (mappedIdentity(mapping.get(leftY), leftP)) { + foundMappedChild = true;// definite (good) match! + } else if (!equalYTypePNode(leftY, leftP)) { + break + } + } + for (; left + right < minCnt; right++) { + const rightY = yChildren[yChildCnt - right - 1]; + const rightP = pChildren[pChildCnt - right - 1]; + if (mappedIdentity(mapping.get(rightY), rightP)) { + foundMappedChild = true; + } else if (!equalYTypePNode(rightY, rightP)) { + break + } + } + return { + equalityFactor: left + right, + foundMappedChild + } + }; + + const ytextTrans = ytext => { + let str = ''; + /** + * @type {Y.Item|null} + */ + let n = ytext._start; + const nAttrs = {}; + while (n !== null) { + if (!n.deleted) { + if (n.countable && n.content instanceof ContentString) { + str += n.content.str; + } else if (n.content instanceof ContentFormat) { + nAttrs[n.content.key] = null; + } + } + n = n.right; + } + return { + str, + nAttrs + } + }; + + /** + * @todo test this more + * + * @param {Y.Text} ytext + * @param {Array} ptexts + * @param {ProsemirrorMapping} mapping + */ + const updateYText = (ytext, ptexts, mapping) => { + mapping.set(ytext, ptexts); + const { nAttrs, str } = ytextTrans(ytext); + const content = ptexts.map(p => ({ insert: /** @type {any} */ (p).text, attributes: Object.assign({}, nAttrs, marksToAttributes(p.marks)) })); + const { insert, remove, index } = simpleDiff(str, content.map(c => c.insert).join('')); + ytext.delete(index, remove); + ytext.insert(index, insert); + ytext.applyDelta(content.map(c => ({ retain: c.insert.length, attributes: c.attributes }))); + }; + + const marksToAttributes = marks => { + const pattrs = {}; + marks.forEach(mark => { + if (mark.type.name !== 'ychange') { + pattrs[mark.type.name] = mark.attrs; + } + }); + return pattrs + }; + + /** + * @private + * @param {Y.Doc} y + * @param {Y.XmlFragment} yDomFragment + * @param {any} pNode + * @param {ProsemirrorMapping} mapping + */ + const updateYFragment = (y, yDomFragment, pNode, mapping) => { + if (yDomFragment instanceof YXmlElement && yDomFragment.nodeName !== pNode.type.name) { + throw new Error('node name mismatch!') + } + mapping.set(yDomFragment, pNode); + // update attributes + if (yDomFragment instanceof YXmlElement) { + const yDomAttrs = yDomFragment.getAttributes(); + const pAttrs = pNode.attrs; + for (const key in pAttrs) { + if (pAttrs[key] !== null) { + if (yDomAttrs[key] !== pAttrs[key] && key !== 'ychange') { + yDomFragment.setAttribute(key, pAttrs[key]); + } + } else { + yDomFragment.removeAttribute(key); + } + } + // remove all keys that are no longer in pAttrs + for (const key in yDomAttrs) { + if (pAttrs[key] === undefined) { + yDomFragment.removeAttribute(key); + } + } + } + // update children + const pChildren = normalizePNodeContent(pNode); + const pChildCnt = pChildren.length; + const yChildren = yDomFragment.toArray(); + const yChildCnt = yChildren.length; + const minCnt = min(pChildCnt, yChildCnt); + let left = 0; + let right = 0; + // find number of matching elements from left + for (;left < minCnt; left++) { + const leftY = yChildren[left]; + const leftP = pChildren[left]; + if (!mappedIdentity(mapping.get(leftY), leftP)) { + if (equalYTypePNode(leftY, leftP)) { + // update mapping + mapping.set(leftY, leftP); + } else { + break + } + } + } + // find number of matching elements from right + for (;right + left + 1 < minCnt; right++) { + const rightY = yChildren[yChildCnt - right - 1]; + const rightP = pChildren[pChildCnt - right - 1]; + if (!mappedIdentity(mapping.get(rightY), rightP)) { + if (equalYTypePNode(rightY, rightP)) { + // update mapping + mapping.set(rightY, rightP); + } else { + break + } + } + } + y.transact(() => { + // try to compare and update + while (yChildCnt - left - right > 0 && pChildCnt - left - right > 0) { + const leftY = yChildren[left]; + const leftP = pChildren[left]; + const rightY = yChildren[yChildCnt - right - 1]; + const rightP = pChildren[pChildCnt - right - 1]; + if (leftY instanceof YXmlText && leftP instanceof Array) { + if (!equalYTextPText(leftY, leftP)) { + updateYText(leftY, leftP, mapping); + } + left += 1; + } else { + let updateLeft = leftY instanceof YXmlElement && matchNodeName(leftY, leftP); + let updateRight = rightY instanceof YXmlElement && matchNodeName(rightY, rightP); + if (updateLeft && updateRight) { + // decide which which element to update + const equalityLeft = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (leftY), /** @type {PMNode} */ (leftP), mapping); + const equalityRight = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (rightY), /** @type {PMNode} */ (rightP), mapping); + if (equalityLeft.foundMappedChild && !equalityRight.foundMappedChild) { + updateRight = false; + } else if (!equalityLeft.foundMappedChild && equalityRight.foundMappedChild) { + updateLeft = false; + } else if (equalityLeft.equalityFactor < equalityRight.equalityFactor) { + updateLeft = false; + } else { + updateRight = false; + } + } + if (updateLeft) { + updateYFragment(y, /** @type {Y.XmlFragment} */ (leftY), /** @type {PMNode} */ (leftP), mapping); + left += 1; + } else if (updateRight) { + updateYFragment(y, /** @type {Y.XmlFragment} */ (rightY), /** @type {PMNode} */ (rightP), mapping); + right += 1; + } else { + yDomFragment.delete(left, 1); + yDomFragment.insert(left, [createTypeFromTextOrElementNode(leftP, mapping)]); + left += 1; + } + } + } + const yDelLen = yChildCnt - left - right; + if (yDelLen > 0) { + yDomFragment.delete(left, yDelLen); + } + if (left + right < pChildCnt) { + const ins = []; + for (let i = left; i < pChildCnt - right; i++) { + ins.push(createTypeFromTextOrElementNode(pChildren[i], mapping)); + } + yDomFragment.insert(left, ins); + } + }, ySyncPluginKey); + }; + + /** + * @function + * @param {Y.XmlElement} yElement + * @param {any} pNode Prosemirror Node + */ + const matchNodeName = (yElement, pNode) => !(pNode instanceof Array) && yElement.nodeName === pNode.type.name; + + /** + * Transforms a Prosemirror based absolute position to a Yjs Cursor (relative position in the Yjs model). + * + * @param {number} pos + * @param {Y.XmlFragment} type + * @param {ProsemirrorMapping} mapping + * @return {any} relative position + */ + const absolutePositionToRelativePosition = (pos, type, mapping) => { + if (pos === 0) { + return createRelativePositionFromTypeIndex(type, 0) + } + let n = type._first === null ? null : /** @type {Y.ContentType} */ (type._first.content).type; + while (n !== null && type !== n) { + if (n.constructor === YXmlText) { + if (n._length >= pos) { + return createRelativePositionFromTypeIndex(n, pos) + } else { + pos -= n._length; + } + if (n._item !== null && n._item.next !== null) { + n = /** @type {Y.ContentType} */ (n._item.next.content).type; + } else { + do { + n = n._item === null ? null : n._item.parent; + pos--; + } while (n !== type && n !== null && n._item !== null && n._item.next === null) + if (n !== null && n !== type) { + // @ts-gnore we know that n.next !== null because of above loop conditition + n = n._item === null ? null : /** @type {Y.ContentType} */ (/** @type Y.Item */ (n._item.next).content).type; + } + } + } else { + const pNodeSize = /** @type {any} */ (mapping.get(n) || { nodeSize: 0 }).nodeSize; + if (n._first !== null && pos < pNodeSize) { + n = /** @type {Y.ContentType} */ (n._first.content).type; + pos--; + } else { + if (pos === 1 && n._length === 0 && pNodeSize > 1) { + // edge case, should end in this paragraph + return new RelativePosition(n._item === null ? null : n._item.id, n._item === null ? findRootTypeKey(n) : null, null) + } + pos -= pNodeSize; + if (n._item !== null && n._item.next !== null) { + n = /** @type {Y.ContentType} */ (n._item.next.content).type; + } else { + if (pos === 0) { + // set to end of n.parent + n = n._item === null ? n : n._item.parent; + return new RelativePosition(n._item === null ? null : n._item.id, n._item === null ? findRootTypeKey(n) : null, null) + } + do { + n = /** @type {Y.Item} */ (n._item).parent; + pos--; + } while (n !== type && /** @type {Y.Item} */ (n._item).next === null) + // if n is null at this point, we have an unexpected case + if (n !== type) { + // We know that n._item.next is defined because of above loop condition + n = /** @type {Y.ContentType} */ (/** @type {Y.Item} */ (/** @type {Y.Item} */ (n._item).next).content).type; + } + } + } + } + if (n === null) { + throw unexpectedCase() + } + if (pos === 0 && n.constructor !== YXmlText && n !== type) { // TODO: set to <= 0 + return createRelativePosition$1(n._item.parent, n._item) + } + } + return createRelativePositionFromTypeIndex(type, type._length) + }; + + const createRelativePosition$1 = (type, item) => { + let typeid = null; + let tname = null; + if (type._item === null) { + tname = findRootTypeKey(type); + } else { + typeid = createID(type._item.id.client, type._item.id.clock); + } + return new RelativePosition(typeid, tname, item.id) + }; + + /** + * @param {Y.Doc} y + * @param {Y.XmlFragment} documentType Top level type that is bound to pView + * @param {any} relPos Encoded Yjs based relative position + * @param {ProsemirrorMapping} mapping + * @return {null|number} + */ + const relativePositionToAbsolutePosition = (y, documentType, relPos, mapping) => { + const decodedPos = createAbsolutePositionFromRelativePosition(relPos, y); + if (decodedPos === null || (decodedPos.type !== documentType && !isParentOf(documentType, decodedPos.type._item))) { + return null + } + let type = decodedPos.type; + let pos = 0; + if (type.constructor === YXmlText) { + pos = decodedPos.index; + } else if (type._item === null || !type._item.deleted) { + let n = type._first; + let i = 0; + while (i < type._length && i < decodedPos.index && n !== null) { + if (!n.deleted) { + const t = /** @type {Y.ContentType} */ (n.content).type; + i++; + if (t.constructor === YXmlText) { + pos += t._length; + } else { + pos += /** @type {any} */ (mapping.get(t)).nodeSize; + } + } + n = /** @type {Y.Item} */ (n.right); + } + pos += 1; // increase because we go out of n + } + while (type !== documentType && type._item !== null) { + // @ts-ignore + const parent = type._item.parent; + // @ts-ignore + if (parent._item === null || !parent._item.deleted) { + pos += 1; // the start tag + let n = parent._first; + // now iterate until we found type + while (n !== null) { + const contentType = /** @type {Y.ContentType} */ (n.content).type; + if (contentType === type) { + break + } + if (!n.deleted) { + if (contentType.constructor === YXmlText) { + pos += contentType._length; + } else { + pos += /** @type {any} */ (mapping.get(contentType)).nodeSize; + } + } + n = n.right; + } + } + type = parent; + } + return pos - 1 // we don't count the most outer tag, because it is a fragment + }; + + /** + * Utility method to convert a Prosemirror Doc Node into a Y.Doc. + * + * This can be used when importing existing content to Y.Doc for the first time, + * note that this should not be used to rehydrate a Y.Doc from a database once + * collaboration has begun as all history will be lost + * + * @param {Node} doc + * @param {string} xmlFragment + * @return {Y.Doc} + */ + function prosemirrorToYDoc (doc, xmlFragment = 'prosemirror') { + const ydoc = new Doc(); + const type = ydoc.get(xmlFragment, YXmlFragment); + if (!type.doc) { + return ydoc + } + + updateYFragment(type.doc, type, doc, new Map()); + return type.doc + } + + /** + * Utility method to convert Prosemirror compatible JSON into a Y.Doc. + * + * This can be used when importing existing content to Y.Doc for the first time, + * note that this should not be used to rehydrate a Y.Doc from a database once + * collaboration has begun as all history will be lost + * + * @param {Schema} schema + * @param {any} state + * @param {string} xmlFragment + * @return {Y.Doc} + */ + function prosemirrorJSONToYDoc (schema, state, xmlFragment = 'prosemirror') { + const doc = Node.fromJSON(schema, state); + return prosemirrorToYDoc(doc, xmlFragment) + } + + /** + * Utility method to convert a Y.Doc to Prosemirror compatible JSON. + * + * @param {Y.Doc} ydoc + * @param {string} xmlFragment + * @return {Record} + */ + function yDocToProsemirrorJSON ( + ydoc, + xmlFragment = 'prosemirror' + ) { + const items = ydoc.getXmlFragment(xmlFragment).toArray(); + + function serialize (item) { + /** + * @type {Object} NodeObject + * @property {string} NodeObject.type + * @property {Record=} NodeObject.attrs + * @property {Array=} NodeObject.content + */ + let response; + + // TODO: Must be a better way to detect text nodes than this + if (!item.nodeName) { + const delta = item.toDelta(); + response = delta.map((d) => { + const text = { + type: 'text', + text: d.insert + }; + + if (d.attributes) { + text.marks = Object.keys(d.attributes).map((type) => { + const attrs = d.attributes[type]; + const mark = { + type + }; + + if (Object.keys(attrs)) { + mark.attrs = attrs; + } + + return mark + }); + } + return text + }); + } else { + response = { + type: item.nodeName + }; + + const attrs = item.getAttributes(); + if (Object.keys(attrs).length) { + response.attrs = attrs; + } + + const children = item.toArray(); + if (children.length) { + response.content = children.map(serialize).flat(); + } + } + + return response + } + + return { + type: 'doc', + content: items.map(serialize) + } + } + + var pDOM = ["p", 0], blockquoteDOM = ["blockquote", 0], hrDOM = ["hr"], + preDOM = ["pre", ["code", 0]], brDOM = ["br"]; + + // :: Object + // [Specs](#model.NodeSpec) for the nodes defined in this schema. + var nodes = { + // :: NodeSpec The top level document node. + doc: { + content: "block+" + }, + + // :: NodeSpec A plain paragraph textblock. Represented in the DOM + // as a `

` element. + paragraph: { + content: "inline*", + group: "block", + parseDOM: [{tag: "p"}], + toDOM: function toDOM() { return pDOM } + }, + + // :: NodeSpec A blockquote (`

`) wrapping one or more blocks. + blockquote: { + content: "block+", + group: "block", + defining: true, + parseDOM: [{tag: "blockquote"}], + toDOM: function toDOM() { return blockquoteDOM } + }, + + // :: NodeSpec A horizontal rule (`
`). + horizontal_rule: { + group: "block", + parseDOM: [{tag: "hr"}], + toDOM: function toDOM() { return hrDOM } + }, + + // :: NodeSpec A heading textblock, with a `level` attribute that + // should hold the number 1 to 6. Parsed and serialized as `

` to + // `

` elements. + heading: { + attrs: {level: {default: 1}}, + content: "inline*", + group: "block", + defining: true, + parseDOM: [{tag: "h1", attrs: {level: 1}}, + {tag: "h2", attrs: {level: 2}}, + {tag: "h3", attrs: {level: 3}}, + {tag: "h4", attrs: {level: 4}}, + {tag: "h5", attrs: {level: 5}}, + {tag: "h6", attrs: {level: 6}}], + toDOM: function toDOM(node) { return ["h" + node.attrs.level, 0] } + }, + + // :: NodeSpec A code listing. Disallows marks or non-text inline + // nodes by default. Represented as a `
` element with a
+    // `` element inside of it.
+    code_block: {
+      content: "text*",
+      marks: "",
+      group: "block",
+      code: true,
+      defining: true,
+      parseDOM: [{tag: "pre", preserveWhitespace: "full"}],
+      toDOM: function toDOM() { return preDOM }
+    },
+
+    // :: NodeSpec The text node.
+    text: {
+      group: "inline"
+    },
+
+    // :: NodeSpec An inline image (``) node. Supports `src`,
+    // `alt`, and `href` attributes. The latter two default to the empty
+    // string.
+    image: {
+      inline: true,
+      attrs: {
+        src: {},
+        alt: {default: null},
+        title: {default: null}
+      },
+      group: "inline",
+      draggable: true,
+      parseDOM: [{tag: "img[src]", getAttrs: function getAttrs(dom) {
+        return {
+          src: dom.getAttribute("src"),
+          title: dom.getAttribute("title"),
+          alt: dom.getAttribute("alt")
+        }
+      }}],
+      toDOM: function toDOM(node) { var ref = node.attrs;
+      var src = ref.src;
+      var alt = ref.alt;
+      var title = ref.title; return ["img", {src: src, alt: alt, title: title}] }
+    },
+
+    // :: NodeSpec A hard line break, represented in the DOM as `
`. + hard_break: { + inline: true, + group: "inline", + selectable: false, + parseDOM: [{tag: "br"}], + toDOM: function toDOM() { return brDOM } + } + }; + + var emDOM = ["em", 0], strongDOM = ["strong", 0], codeDOM = ["code", 0]; + + // :: Object [Specs](#model.MarkSpec) for the marks in the schema. + var marks = { + // :: MarkSpec A link. Has `href` and `title` attributes. `title` + // defaults to the empty string. Rendered and parsed as an `
` + // element. + link: { + attrs: { + href: {}, + title: {default: null} + }, + inclusive: false, + parseDOM: [{tag: "a[href]", getAttrs: function getAttrs(dom) { + return {href: dom.getAttribute("href"), title: dom.getAttribute("title")} + }}], + toDOM: function toDOM(node) { var ref = node.attrs; + var href = ref.href; + var title = ref.title; return ["a", {href: href, title: title}, 0] } + }, + + // :: MarkSpec An emphasis mark. Rendered as an `` element. + // Has parse rules that also match `` and `font-style: italic`. + em: { + parseDOM: [{tag: "i"}, {tag: "em"}, {style: "font-style=italic"}], + toDOM: function toDOM() { return emDOM } + }, + + // :: MarkSpec A strong mark. Rendered as ``, parse rules + // also match `` and `font-weight: bold`. + strong: { + parseDOM: [{tag: "strong"}, + // This works around a Google Docs misbehavior where + // pasted content will be inexplicably wrapped in `` + // tags with a font-weight normal. + {tag: "b", getAttrs: function (node) { return node.style.fontWeight != "normal" && null; }}, + {style: "font-weight", getAttrs: function (value) { return /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null; }}], + toDOM: function toDOM() { return strongDOM } + }, + + // :: MarkSpec Code font mark. Represented as a `` element. + code: { + parseDOM: [{tag: "code"}], + toDOM: function toDOM() { return codeDOM } + } + }; + + // :: Schema + // This schema roughly corresponds to the document schema used by + // [CommonMark](http://commonmark.org/), minus the list elements, + // which are defined in the [`prosemirror-schema-list`](#schema-list) + // module. + // + // To reuse elements from this schema, extend or read from its + // `spec.nodes` and `spec.marks` [properties](#model.Schema.spec). + var schema = new Schema({nodes: nodes, marks: marks}); + + const brDOM$1 = ['br']; + + const calcYchangeDomAttrs = (attrs, domAttrs = {}) => { + domAttrs = Object.assign({}, domAttrs); + if (attrs.ychange !== null) { + domAttrs.ychange_user = attrs.ychange.user; + domAttrs.ychange_state = attrs.ychange.state; + } + return domAttrs + }; + + // :: Object + // [Specs](#model.NodeSpec) for the nodes defined in this schema. + const nodes$1 = { + // :: NodeSpec The top level document node. + doc: { + content: 'custom paragraph' + }, + + custom: { + atom: true, + attrs: { checked: { default: false } }, + parseDOM: [{ tag: 'div' }], + toDOM () { + return ['div'] + } + }, + + // :: NodeSpec A plain paragraph textblock. Represented in the DOM + // as a `

` element. + paragraph: { + attrs: { ychange: { default: null } }, + content: 'inline*', + group: 'block', + parseDOM: [{ tag: 'p' }], + toDOM (node) { + return ['p', calcYchangeDomAttrs(node.attrs), 0] + } + }, + + // :: NodeSpec A blockquote (`

`) wrapping one or more blocks. + blockquote: { + attrs: { ychange: { default: null } }, + content: 'block+', + group: 'block', + defining: true, + parseDOM: [{ tag: 'blockquote' }], + toDOM (node) { + return ['blockquote', calcYchangeDomAttrs(node.attrs), 0] + } + }, + + // :: NodeSpec A horizontal rule (`
`). + horizontal_rule: { + attrs: { ychange: { default: null } }, + group: 'block', + parseDOM: [{ tag: 'hr' }], + toDOM (node) { + return ['hr', calcYchangeDomAttrs(node.attrs)] + } + }, + + // :: NodeSpec A heading textblock, with a `level` attribute that + // should hold the number 1 to 6. Parsed and serialized as `

` to + // `

` elements. + heading: { + attrs: { + level: { default: 1 }, + ychange: { default: null } + }, + content: 'inline*', + group: 'block', + defining: true, + parseDOM: [ + { tag: 'h1', attrs: { level: 1 } }, + { tag: 'h2', attrs: { level: 2 } }, + { tag: 'h3', attrs: { level: 3 } }, + { tag: 'h4', attrs: { level: 4 } }, + { tag: 'h5', attrs: { level: 5 } }, + { tag: 'h6', attrs: { level: 6 } } + ], + toDOM (node) { + return ['h' + node.attrs.level, calcYchangeDomAttrs(node.attrs), 0] + } + }, + + // :: NodeSpec A code listing. Disallows marks or non-text inline + // nodes by default. Represented as a `
` element with a
+    // `` element inside of it.
+    code_block: {
+      attrs: { ychange: { default: null } },
+      content: 'text*',
+      marks: '',
+      group: 'block',
+      code: true,
+      defining: true,
+      parseDOM: [{ tag: 'pre', preserveWhitespace: 'full' }],
+      toDOM (node) {
+        return ['pre', calcYchangeDomAttrs(node.attrs), ['code', 0]]
+      }
+    },
+
+    // :: NodeSpec The text node.
+    text: {
+      group: 'inline'
+    },
+
+    // :: NodeSpec An inline image (``) node. Supports `src`,
+    // `alt`, and `href` attributes. The latter two default to the empty
+    // string.
+    image: {
+      inline: true,
+      attrs: {
+        ychange: { default: null },
+        src: {},
+        alt: { default: null },
+        title: { default: null }
+      },
+      group: 'inline',
+      draggable: true,
+      parseDOM: [
+        {
+          tag: 'img[src]',
+          getAttrs (dom) {
+            return {
+              src: dom.getAttribute('src'),
+              title: dom.getAttribute('title'),
+              alt: dom.getAttribute('alt')
+            }
+          }
+        }
+      ],
+      toDOM (node) {
+        const domAttrs = {
+          src: node.attrs.src,
+          title: node.attrs.title,
+          alt: node.attrs.alt
+        };
+        return ['img', calcYchangeDomAttrs(node.attrs, domAttrs)]
+      }
+    },
+
+    // :: NodeSpec A hard line break, represented in the DOM as `
`. + hard_break: { + inline: true, + group: 'inline', + selectable: false, + parseDOM: [{ tag: 'br' }], + toDOM () { + return brDOM$1 + } + } + }; + + const emDOM$1 = ['em', 0]; + const strongDOM$1 = ['strong', 0]; + const codeDOM$1 = ['code', 0]; + + // :: Object [Specs](#model.MarkSpec) for the marks in the schema. + const marks$1 = { + // :: MarkSpec A link. Has `href` and `title` attributes. `title` + // defaults to the empty string. Rendered and parsed as an `
` + // element. + link: { + attrs: { + href: {}, + title: { default: null } + }, + inclusive: false, + parseDOM: [ + { + tag: 'a[href]', + getAttrs (dom) { + return { + href: dom.getAttribute('href'), + title: dom.getAttribute('title') + } + } + } + ], + toDOM (node) { + return ['a', node.attrs, 0] + } + }, + + // :: MarkSpec An emphasis mark. Rendered as an `` element. + // Has parse rules that also match `` and `font-style: italic`. + em: { + parseDOM: [{ tag: 'i' }, { tag: 'em' }, { style: 'font-style=italic' }], + toDOM () { + return emDOM$1 + } + }, + + // :: MarkSpec A strong mark. Rendered as ``, parse rules + // also match `` and `font-weight: bold`. + strong: { + parseDOM: [ + { tag: 'strong' }, + // This works around a Google Docs misbehavior where + // pasted content will be inexplicably wrapped in `` + // tags with a font-weight normal. + { + tag: 'b', + getAttrs: node => node.style.fontWeight !== 'normal' && null + }, + { + style: 'font-weight', + getAttrs: value => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null + } + ], + toDOM () { + return strongDOM$1 + } + }, + + // :: MarkSpec Code font mark. Represented as a `` element. + code: { + parseDOM: [{ tag: 'code' }], + toDOM () { + return codeDOM$1 + } + }, + ychange: { + attrs: { + user: { default: null }, + state: { default: null } + }, + inclusive: false, + parseDOM: [{ tag: 'ychange' }], + toDOM (node) { + return [ + 'ychange', + { ychange_user: node.attrs.user, ychange_state: node.attrs.state }, + 0 + ] + } + } + }; + + // :: Schema + // This schema rougly corresponds to the document schema used by + // [CommonMark](http://commonmark.org/), minus the list elements, + // which are defined in the [`prosemirror-schema-list`](#schema-list) + // module. + // + // To reuse elements from this schema, extend or read from its + // `spec.nodes` and `spec.marks` [properties](#model.Schema.spec). + const schema$1 = new Schema({ nodes: nodes$1, marks: marks$1 }); + + const schema$2 = /** @type {any} */ (schema); + + /** + * @param {t.TestCase} tc + */ + const testDocTransformation = tc => { + const view = createNewProsemirrorView(new Doc()); + view.dispatch(view.state.tr.insert(0, /** @type {any} */ (schema$2.node('paragraph', undefined, schema$2.text('hello world'))))); + const stateJSON = view.state.doc.toJSON(); + // test if transforming back and forth from Yjs doc works + const backandforth = yDocToProsemirrorJSON(prosemirrorJSONToYDoc(/** @type {any} */ (schema$2), stateJSON)); + compare(stateJSON, backandforth); + }; + + /** + * @param {t.TestCase} tc + */ + const testEmptyNotSync = tc => { + const ydoc = new Doc(); + const type = ydoc.getXmlFragment('prosemirror'); + const view = createNewComplexProsemirrorView(ydoc); + assert(type.toString() === '', 'should only sync after first change'); + + view.dispatch( + view.state.tr.setNodeMarkup(0, undefined, { + checked: true + }) + ); + compareStrings(type.toString(), ''); + }; + + const createNewComplexProsemirrorView = y => { + const view = new EditorView(null, { + // @ts-ignore + state: EditorState.create({ + schema: schema$1, + plugins: [ySyncPlugin(y.get('prosemirror', YXmlFragment))] + }) + }); + return view + }; + + const createNewProsemirrorView = y => { + const view = new EditorView(null, { + // @ts-ignore + state: EditorState.create({ + schema: schema$2, + plugins: [ySyncPlugin(y.get('prosemirror', YXmlFragment))] + }) + }); + return view + }; + + let charCounter = 0; + + const marksChoices = [ + [schema$2.mark('strong')], + [schema$2.mark('em')], + [schema$2.mark('em'), schema$2.mark('strong')], + [], + [] + ]; + + const pmChanges = [ + /** + * @param {Y.Doc} y + * @param {prng.PRNG} gen + * @param {EditorView} p + */ + (y, gen, p) => { // insert text + const insertPos = int32(gen, 0, p.state.doc.content.size); + const marks = oneOf(gen, marksChoices); + const tr = p.state.tr; + const text = charCounter++ + word(gen); + p.dispatch(tr.insert(insertPos, schema$2.text(text, marks))); + }, + /** + * @param {Y.Doc} y + * @param {prng.PRNG} gen + * @param {EditorView} p + */ + (y, gen, p) => { // delete text + const insertPos = int32(gen, 0, p.state.doc.content.size); + const overwrite = min(int32(gen, 0, p.state.doc.content.size - insertPos), 2); + p.dispatch(p.state.tr.insertText('', insertPos, insertPos + overwrite)); + }, + /** + * @param {Y.Doc} y + * @param {prng.PRNG} gen + * @param {EditorView} p + */ + (y, gen, p) => { // replace text + const insertPos = int32(gen, 0, p.state.doc.content.size); + const overwrite = min(int32(gen, 0, p.state.doc.content.size - insertPos), 2); + const text = charCounter++ + word(gen); + p.dispatch(p.state.tr.insertText(text, insertPos, insertPos + overwrite)); + }, + /** + * @param {Y.Doc} y + * @param {prng.PRNG} gen + * @param {EditorView} p + */ + (y, gen, p) => { // insert paragraph + const insertPos = int32(gen, 0, p.state.doc.content.size); + const marks = oneOf(gen, marksChoices); + const tr = p.state.tr; + const text = charCounter++ + word(gen); + p.dispatch(tr.insert(insertPos, schema$2.node('paragraph', undefined, schema$2.text(text, marks)))); + }, + /** + * @param {Y.Doc} y + * @param {prng.PRNG} gen + * @param {EditorView} p + */ + (y, gen, p) => { // insert codeblock + const insertPos = int32(gen, 0, p.state.doc.content.size); + const tr = p.state.tr; + const text = charCounter++ + word(gen); + p.dispatch(tr.insert(insertPos, schema$2.node('code_block', undefined, schema$2.text(text)))); + }, + /** + * @param {Y.Doc} y + * @param {prng.PRNG} gen + * @param {EditorView} p + */ + (y, gen, p) => { // wrap in blockquote + const insertPos = int32(gen, 0, p.state.doc.content.size); + const overwrite = int32(gen, 0, p.state.doc.content.size - insertPos); + const tr = p.state.tr; + tr.setSelection(TextSelection.create(tr.doc, insertPos, insertPos + overwrite)); + const $from = tr.selection.$from; + const $to = tr.selection.$to; + const range = $from.blockRange($to); + const wrapping = range && findWrapping(range, schema$2.nodes.blockquote); + if (wrapping) { + p.dispatch(tr.wrap(range, wrapping)); + } + } + ]; + + /** + * @param {any} result + */ + const checkResult = result => { + for (let i = 1; i < result.testObjects.length; i++) { + const p1 = result.testObjects[i - 1].state.doc.toJSON(); + const p2 = result.testObjects[i].state.doc.toJSON(); + compare(p1, p2); + } + }; + + /** + * @param {t.TestCase} tc + */ + const testRepeatGenerateProsemirrorChanges2 = tc => { + checkResult(applyRandomTests(tc, pmChanges, 2, createNewProsemirrorView)); + }; + + /** + * @param {t.TestCase} tc + */ + const testRepeatGenerateProsemirrorChanges3 = tc => { + checkResult(applyRandomTests(tc, pmChanges, 3, createNewProsemirrorView)); + }; + + /** + * @param {t.TestCase} tc + */ + const testRepeatGenerateProsemirrorChanges30 = tc => { + checkResult(applyRandomTests(tc, pmChanges, 30, createNewProsemirrorView)); + }; + + /** + * @param {t.TestCase} tc + */ + const testRepeatGenerateProsemirrorChanges40 = tc => { + checkResult(applyRandomTests(tc, pmChanges, 40, createNewProsemirrorView)); + }; + + /** + * @param {t.TestCase} tc + */ + const testRepeatGenerateProsemirrorChanges70 = tc => { + checkResult(applyRandomTests(tc, pmChanges, 70, createNewProsemirrorView)); + }; + + /** + * @param {t.TestCase} tc + */ + const testRepeatGenerateProsemirrorChanges100 = tc => { + checkResult(applyRandomTests(tc, pmChanges, 100, createNewProsemirrorView)); + }; + + /** + * @param {t.TestCase} tc + */ + const testRepeatGenerateProsemirrorChanges300 = tc => { + checkResult(applyRandomTests(tc, pmChanges, 300, createNewProsemirrorView)); + }; + + var prosemirror = /*#__PURE__*/Object.freeze({ + __proto__: null, + testDocTransformation: testDocTransformation, + testEmptyNotSync: testEmptyNotSync, + testRepeatGenerateProsemirrorChanges2: testRepeatGenerateProsemirrorChanges2, + testRepeatGenerateProsemirrorChanges3: testRepeatGenerateProsemirrorChanges3, + testRepeatGenerateProsemirrorChanges30: testRepeatGenerateProsemirrorChanges30, + testRepeatGenerateProsemirrorChanges40: testRepeatGenerateProsemirrorChanges40, + testRepeatGenerateProsemirrorChanges70: testRepeatGenerateProsemirrorChanges70, + testRepeatGenerateProsemirrorChanges100: testRepeatGenerateProsemirrorChanges100, + testRepeatGenerateProsemirrorChanges300: testRepeatGenerateProsemirrorChanges300 + }); + + if (isBrowser) { + createVConsole(document.body); + } + runTests({ + prosemirror + }).then(success => { + /* istanbul ignore next */ + if (isNode) { + process.exit(success ? 0 : 1); + } + }); + +}()); +//# sourceMappingURL=test.js.map diff --git a/dist/test.js.map b/dist/test.js.map new file mode 100644 index 0000000..df7b108 --- /dev/null +++ b/dist/test.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test.js","sources":["../node_modules/lib0/map.js","../node_modules/lib0/string.js","../node_modules/lib0/conditions.js","../node_modules/lib0/storage.js","../node_modules/lib0/environment.js","../node_modules/lib0/symbol.js","../node_modules/lib0/pair.js","../node_modules/lib0/dom.js","../node_modules/lib0/json.js","../node_modules/lib0/eventloop.js","../node_modules/lib0/math.js","../node_modules/lib0/metric.js","../node_modules/lib0/time.js","../node_modules/lib0/array.js","../node_modules/lib0/object.js","../node_modules/lib0/function.js","../node_modules/lib0/logging.js","../node_modules/lib0/diff.js","../node_modules/isomorphic.js/iso-browser.js","../node_modules/lib0/isomorphic.js","../node_modules/lib0/random.js","../node_modules/lib0/binary.js","../node_modules/lib0/prng/Xorshift32.js","../node_modules/lib0/prng/Xoroshiro128plus.js","../node_modules/lib0/number.js","../node_modules/lib0/encoding.js","../node_modules/lib0/decoding.js","../node_modules/lib0/buffer.js","../node_modules/lib0/prng.js","../node_modules/lib0/statistics.js","../node_modules/lib0/promise.js","../node_modules/lib0/testing.js","../node_modules/lib0/set.js","../node_modules/lib0/observable.js","../node_modules/yjs/src/utils/AbstractConnector.js","../node_modules/yjs/src/utils/DeleteSet.js","../node_modules/yjs/src/utils/Doc.js","../node_modules/lib0/error.js","../node_modules/yjs/src/utils/UpdateDecoder.js","../node_modules/yjs/src/utils/UpdateEncoder.js","../node_modules/yjs/src/utils/encoding.js","../node_modules/yjs/src/utils/EventHandler.js","../node_modules/yjs/src/utils/ID.js","../node_modules/yjs/src/utils/isParentOf.js","../node_modules/yjs/src/utils/logging.js","../node_modules/yjs/src/utils/PermanentUserData.js","../node_modules/yjs/src/utils/RelativePosition.js","../node_modules/yjs/src/utils/Snapshot.js","../node_modules/yjs/src/utils/StructStore.js","../node_modules/yjs/src/utils/Transaction.js","../node_modules/yjs/src/utils/UndoManager.js","../node_modules/yjs/src/utils/YEvent.js","../node_modules/lib0/iterator.js","../node_modules/yjs/src/types/AbstractType.js","../node_modules/yjs/src/types/YArray.js","../node_modules/yjs/src/types/YMap.js","../node_modules/yjs/src/types/YText.js","../node_modules/yjs/src/types/YXmlFragment.js","../node_modules/yjs/src/types/YXmlElement.js","../node_modules/yjs/src/types/YXmlEvent.js","../node_modules/yjs/src/types/YXmlHook.js","../node_modules/yjs/src/types/YXmlText.js","../node_modules/yjs/src/structs/AbstractStruct.js","../node_modules/yjs/src/structs/GC.js","../node_modules/yjs/src/structs/ContentBinary.js","../node_modules/yjs/src/structs/ContentDeleted.js","../node_modules/yjs/src/structs/ContentDoc.js","../node_modules/yjs/src/structs/ContentEmbed.js","../node_modules/yjs/src/structs/ContentFormat.js","../node_modules/yjs/src/structs/ContentJSON.js","../node_modules/yjs/src/structs/ContentAny.js","../node_modules/yjs/src/structs/ContentString.js","../node_modules/yjs/src/structs/ContentType.js","../node_modules/yjs/src/structs/Item.js","../node_modules/y-protocols/sync.js","../node_modules/yjs/tests/testHelper.js","../node_modules/orderedmap/index.es.js","../node_modules/prosemirror-model/dist/index.es.js","../node_modules/prosemirror-transform/dist/index.es.js","../node_modules/prosemirror-state/dist/index.es.js","../node_modules/prosemirror-view/dist/index.es.js","../node_modules/lib0/mutex.js","../src/plugins/keys.js","../src/plugins/sync-plugin.js","../src/lib.js","../node_modules/prosemirror-schema-basic/dist/index.es.js","../test/complexSchema.js","../test/y-prosemirror.test.js","../test/index.js"],"sourcesContent":["/**\n * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template X,Y\n * @param {Map} m\n * @return {Map}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template T,K\n * @param {Map} map\n * @param {K} key\n * @param {function():T} createT\n * @return {T}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map} m\n * @param {function(V,K):R} f\n * @return {Array}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n","/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* istanbul ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* istanbul ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* istanbul ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* istanbul ignore next */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* istanbul ignore next */\n utf8TextDecoder = null\n}\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* istanbul ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n","/**\n * Often used conditions.\n *\n * @module conditions\n */\n\n/**\n * @template T\n * @param {T|null|undefined} v\n * @return {T|null}\n */\n/* istanbul ignore next */\nexport const undefinedToNull = v => v === undefined ? null : v\n","/* global localStorage */\n\n/**\n * Isomorphic variable storage.\n *\n * Uses LocalStorage in the browser and falls back to in-memory storage.\n *\n * @module storage\n */\n\n/* istanbul ignore next */\nclass VarStoragePolyfill {\n constructor () {\n this.map = new Map()\n }\n\n /**\n * @param {string} key\n * @param {any} value\n */\n setItem (key, value) {\n this.map.set(key, value)\n }\n\n /**\n * @param {string} key\n */\n getItem (key) {\n return this.map.get(key)\n }\n}\n\n/* istanbul ignore next */\n/**\n * @type {any}\n */\nlet _localStorage = new VarStoragePolyfill()\n\ntry {\n // if the same-origin rule is violated, accessing localStorage might thrown an error\n /* istanbul ignore next */\n if (typeof localStorage !== 'undefined') {\n _localStorage = localStorage\n }\n} catch (e) { }\n\n/* istanbul ignore next */\n/**\n * This is basically localStorage in browser, or a polyfill in nodejs\n */\nexport const varStorage = _localStorage\n","/**\n * Isomorphic module to work access the environment (query params, env variables).\n *\n * @module map\n */\n\nimport * as map from './map.js'\nimport * as string from './string.js'\nimport * as conditions from './conditions.js'\nimport * as storage from './storage.js'\n\n/* istanbul ignore next */\n// @ts-ignore\nexport const isNode = typeof process !== 'undefined' && process.release && /node|io\\.js/.test(process.release.name)\n/* istanbul ignore next */\nexport const isBrowser = typeof window !== 'undefined' && !isNode\n/* istanbul ignore next */\nexport const isMac = typeof navigator !== 'undefined' ? /Mac/.test(navigator.platform) : false\n\n/**\n * @type {Map}\n */\nlet params\nconst args = []\n\n/* istanbul ignore next */\nconst computeParams = () => {\n if (params === undefined) {\n if (isNode) {\n params = map.create()\n const pargs = process.argv\n let currParamName = null\n /* istanbul ignore next */\n for (let i = 0; i < pargs.length; i++) {\n const parg = pargs[i]\n if (parg[0] === '-') {\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n currParamName = parg\n } else {\n if (currParamName !== null) {\n params.set(currParamName, parg)\n currParamName = null\n } else {\n args.push(parg)\n }\n }\n }\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n // in ReactNative for example this would not be true (unless connected to the Remote Debugger)\n } else if (typeof location === 'object') {\n params = map.create()\n // eslint-disable-next-line no-undef\n ;(location.search || '?').slice(1).split('&').forEach(kv => {\n if (kv.length !== 0) {\n const [key, value] = kv.split('=')\n params.set(`--${string.fromCamelCase(key, '-')}`, value)\n params.set(`-${string.fromCamelCase(key, '-')}`, value)\n }\n })\n } else {\n params = map.create()\n }\n }\n return params\n}\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* istanbul ignore next */\nexport const hasParam = name => computeParams().has(name)\n\n/**\n * @param {string} name\n * @param {string} defaultVal\n * @return {string}\n */\n/* istanbul ignore next */\nexport const getParam = (name, defaultVal) => computeParams().get(name) || defaultVal\n// export const getArgs = name => computeParams() && args\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* istanbul ignore next */\nexport const getVariable = name => isNode ? conditions.undefinedToNull(process.env[name.toUpperCase()]) : conditions.undefinedToNull(storage.varStorage.getItem(name))\n\n/**\n * @param {string} name\n * @return {string|null}\n */\nexport const getConf = name => computeParams().get('--' + name) || getVariable(name)\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* istanbul ignore next */\nexport const hasConf = name => hasParam('--' + name) || getVariable(name) !== null\n\n/* istanbul ignore next */\nexport const production = hasConf('production')\n","/**\n * Utility module to work with EcmaScript Symbols.\n *\n * @module symbol\n */\n\n/**\n * Return fresh symbol.\n *\n * @return {Symbol}\n */\nexport const create = Symbol\n\n/**\n * @param {any} s\n * @return {boolean}\n */\nexport const isSymbol = s => typeof s === 'symbol'\n","/**\n * Working with value pairs.\n *\n * @module pair\n */\n\n/**\n * @template L,R\n */\nexport class Pair {\n /**\n * @param {L} left\n * @param {R} right\n */\n constructor (left, right) {\n this.left = left\n this.right = right\n }\n}\n\n/**\n * @template L,R\n * @param {L} left\n * @param {R} right\n * @return {Pair}\n */\nexport const create = (left, right) => new Pair(left, right)\n\n/**\n * @template L,R\n * @param {R} right\n * @param {L} left\n * @return {Pair}\n */\nexport const createReversed = (right, left) => new Pair(left, right)\n\n/**\n * @template L,R\n * @param {Array>} arr\n * @param {function(L, R):any} f\n */\nexport const forEach = (arr, f) => arr.forEach(p => f(p.left, p.right))\n\n/**\n * @template L,R,X\n * @param {Array>} arr\n * @param {function(L, R):X} f\n * @return {Array}\n */\nexport const map = (arr, f) => arr.map(p => f(p.left, p.right))\n","/* eslint-env browser */\n\n/**\n * Utility module to work with the DOM.\n *\n * @module dom\n */\n\nimport * as pair from './pair.js'\nimport * as map from './map.js'\n\n/* istanbul ignore next */\n/**\n * @type {Document}\n */\nexport const doc = /** @type {Document} */ (typeof document !== 'undefined' ? document : {})\n\n/**\n * @param {string} name\n * @return {HTMLElement}\n */\n/* istanbul ignore next */\nexport const createElement = name => doc.createElement(name)\n\n/**\n * @return {DocumentFragment}\n */\n/* istanbul ignore next */\nexport const createDocumentFragment = () => doc.createDocumentFragment()\n\n/**\n * @param {string} text\n * @return {Text}\n */\n/* istanbul ignore next */\nexport const createTextNode = text => doc.createTextNode(text)\n\n/* istanbul ignore next */\nexport const domParser = /** @type {DOMParser} */ (typeof DOMParser !== 'undefined' ? new DOMParser() : null)\n\n/**\n * @param {HTMLElement} el\n * @param {string} name\n * @param {Object} opts\n */\n/* istanbul ignore next */\nexport const emitCustomEvent = (el, name, opts) => el.dispatchEvent(new CustomEvent(name, opts))\n\n/**\n * @param {Element} el\n * @param {Array>} attrs Array of key-value pairs\n * @return {Element}\n */\n/* istanbul ignore next */\nexport const setAttributes = (el, attrs) => {\n pair.forEach(attrs, (key, value) => {\n if (value === false) {\n el.removeAttribute(key)\n } else if (value === true) {\n el.setAttribute(key, '')\n } else {\n // @ts-ignore\n el.setAttribute(key, value)\n }\n })\n return el\n}\n\n/**\n * @param {Element} el\n * @param {Map} attrs Array of key-value pairs\n * @return {Element}\n */\n/* istanbul ignore next */\nexport const setAttributesMap = (el, attrs) => {\n attrs.forEach((value, key) => { el.setAttribute(key, value) })\n return el\n}\n\n/**\n * @param {Array|HTMLCollection} children\n * @return {DocumentFragment}\n */\n/* istanbul ignore next */\nexport const fragment = children => {\n const fragment = createDocumentFragment()\n for (let i = 0; i < children.length; i++) {\n appendChild(fragment, children[i])\n }\n return fragment\n}\n\n/**\n * @param {Element} parent\n * @param {Array} nodes\n * @return {Element}\n */\n/* istanbul ignore next */\nexport const append = (parent, nodes) => {\n appendChild(parent, fragment(nodes))\n return parent\n}\n\n/**\n * @param {HTMLElement} el\n */\n/* istanbul ignore next */\nexport const remove = el => el.remove()\n\n/**\n * @param {EventTarget} el\n * @param {string} name\n * @param {EventListener} f\n */\n/* istanbul ignore next */\nexport const addEventListener = (el, name, f) => el.addEventListener(name, f)\n\n/**\n * @param {EventTarget} el\n * @param {string} name\n * @param {EventListener} f\n */\n/* istanbul ignore next */\nexport const removeEventListener = (el, name, f) => el.removeEventListener(name, f)\n\n/**\n * @param {Node} node\n * @param {Array>} listeners\n * @return {Node}\n */\n/* istanbul ignore next */\nexport const addEventListeners = (node, listeners) => {\n pair.forEach(listeners, (name, f) => addEventListener(node, name, f))\n return node\n}\n\n/**\n * @param {Node} node\n * @param {Array>} listeners\n * @return {Node}\n */\n/* istanbul ignore next */\nexport const removeEventListeners = (node, listeners) => {\n pair.forEach(listeners, (name, f) => removeEventListener(node, name, f))\n return node\n}\n\n/**\n * @param {string} name\n * @param {Array|pair.Pair>} attrs Array of key-value pairs\n * @param {Array} children\n * @return {Element}\n */\n/* istanbul ignore next */\nexport const element = (name, attrs = [], children = []) =>\n append(setAttributes(createElement(name), attrs), children)\n\n/**\n * @param {number} width\n * @param {number} height\n */\n/* istanbul ignore next */\nexport const canvas = (width, height) => {\n const c = /** @type {HTMLCanvasElement} */ (createElement('canvas'))\n c.height = height\n c.width = width\n return c\n}\n\n/**\n * @param {string} t\n * @return {Text}\n */\n/* istanbul ignore next */\nexport const text = createTextNode\n\n/**\n * @param {pair.Pair} pair\n */\n/* istanbul ignore next */\nexport const pairToStyleString = pair => `${pair.left}:${pair.right};`\n\n/**\n * @param {Array>} pairs\n * @return {string}\n */\n/* istanbul ignore next */\nexport const pairsToStyleString = pairs => pairs.map(pairToStyleString).join('')\n\n/**\n * @param {Map} m\n * @return {string}\n */\n/* istanbul ignore next */\nexport const mapToStyleString = m => map.map(m, (value, key) => `${key}:${value};`).join('')\n\n/**\n * @todo should always query on a dom element\n *\n * @param {HTMLElement|ShadowRoot} el\n * @param {string} query\n * @return {HTMLElement | null}\n */\n/* istanbul ignore next */\nexport const querySelector = (el, query) => el.querySelector(query)\n\n/**\n * @param {HTMLElement|ShadowRoot} el\n * @param {string} query\n * @return {NodeListOf}\n */\n/* istanbul ignore next */\nexport const querySelectorAll = (el, query) => el.querySelectorAll(query)\n\n/**\n * @param {string} id\n * @return {HTMLElement}\n */\n/* istanbul ignore next */\nexport const getElementById = id => /** @type {HTMLElement} */ (doc.getElementById(id))\n\n/**\n * @param {string} html\n * @return {HTMLElement}\n */\n/* istanbul ignore next */\nconst _parse = html => domParser.parseFromString(`${html}`, 'text/html').body\n\n/**\n * @param {string} html\n * @return {DocumentFragment}\n */\n/* istanbul ignore next */\nexport const parseFragment = html => fragment(/** @type {any} */ (_parse(html).childNodes))\n\n/**\n * @param {string} html\n * @return {HTMLElement}\n */\n/* istanbul ignore next */\nexport const parseElement = html => /** @type HTMLElement */ (_parse(html).firstElementChild)\n\n/**\n * @param {HTMLElement} oldEl\n * @param {HTMLElement|DocumentFragment} newEl\n */\n/* istanbul ignore next */\nexport const replaceWith = (oldEl, newEl) => oldEl.replaceWith(newEl)\n\n/**\n * @param {HTMLElement} parent\n * @param {HTMLElement} el\n * @param {Node|null} ref\n * @return {HTMLElement}\n */\n/* istanbul ignore next */\nexport const insertBefore = (parent, el, ref) => parent.insertBefore(el, ref)\n\n/**\n * @param {Node} parent\n * @param {Node} child\n * @return {Node}\n */\n/* istanbul ignore next */\nexport const appendChild = (parent, child) => parent.appendChild(child)\n\nexport const ELEMENT_NODE = doc.ELEMENT_NODE\nexport const TEXT_NODE = doc.TEXT_NODE\nexport const CDATA_SECTION_NODE = doc.CDATA_SECTION_NODE\nexport const COMMENT_NODE = doc.COMMENT_NODE\nexport const DOCUMENT_NODE = doc.DOCUMENT_NODE\nexport const DOCUMENT_TYPE_NODE = doc.DOCUMENT_TYPE_NODE\nexport const DOCUMENT_FRAGMENT_NODE = doc.DOCUMENT_FRAGMENT_NODE\n\n/**\n * @param {any} node\n * @param {number} type\n */\nexport const checkNodeType = (node, type) => node.nodeType === type\n\n/**\n * @param {Node} parent\n * @param {HTMLElement} child\n */\nexport const isParentOf = (parent, child) => {\n let p = child.parentNode\n while (p && p !== parent) {\n p = p.parentNode\n }\n return p === parent\n}\n","/**\n * JSON utility functions.\n *\n * @module json\n */\n\n/**\n * Transform JavaScript object to JSON.\n *\n * @param {any} object\n * @return {string}\n */\nexport const stringify = JSON.stringify\n\n/**\n * Parse JSON object.\n *\n * @param {string} json\n * @return {any}\n */\nexport const parse = JSON.parse\n","/* global requestIdleCallback, requestAnimationFrame, cancelIdleCallback, cancelAnimationFrame */\n\n/**\n * Utility module to work with EcmaScript's event loop.\n *\n * @module eventloop\n */\n\n/**\n * @type {Array}\n */\nlet queue = []\n\nconst _runQueue = () => {\n for (let i = 0; i < queue.length; i++) {\n queue[i]()\n }\n queue = []\n}\n\n/**\n * @param {function():void} f\n */\nexport const enqueue = f => {\n queue.push(f)\n if (queue.length === 1) {\n setTimeout(_runQueue, 0)\n }\n}\n\n/**\n * @typedef {Object} TimeoutObject\n * @property {function} TimeoutObject.destroy\n */\n\n/**\n * @param {function(number):void} clearFunction\n */\nconst createTimeoutClass = clearFunction => class TT {\n /**\n * @param {number} timeoutId\n */\n constructor (timeoutId) {\n this._ = timeoutId\n }\n\n destroy () {\n clearFunction(this._)\n }\n}\n\nconst Timeout = createTimeoutClass(clearTimeout)\n\n/**\n * @param {number} timeout\n * @param {function} callback\n * @return {TimeoutObject}\n */\nexport const timeout = (timeout, callback) => new Timeout(setTimeout(callback, timeout))\n\nconst Interval = createTimeoutClass(clearInterval)\n\n/**\n * @param {number} timeout\n * @param {function} callback\n * @return {TimeoutObject}\n */\nexport const interval = (timeout, callback) => new Interval(setInterval(callback, timeout))\n\n/* istanbul ignore next */\nexport const Animation = createTimeoutClass(arg => typeof requestAnimationFrame !== 'undefined' && cancelAnimationFrame(arg))\n\n/* istanbul ignore next */\n/**\n * @param {function(number):void} cb\n * @return {TimeoutObject}\n */\nexport const animationFrame = cb => typeof requestAnimationFrame === 'undefined' ? timeout(0, cb) : new Animation(requestAnimationFrame(cb))\n\n/* istanbul ignore next */\n// @ts-ignore\nconst Idle = createTimeoutClass(arg => typeof cancelIdleCallback !== 'undefined' && cancelIdleCallback(arg))\n\n/* istanbul ignore next */\n/**\n * Note: this is experimental and is probably only useful in browsers.\n *\n * @param {function} cb\n * @return {TimeoutObject}\n */\n// @ts-ignore\nexport const idleCallback = cb => typeof requestIdleCallback !== 'undefined' ? new Idle(requestIdleCallback(cb)) : timeout(1000, cb)\n\n/**\n * @param {number} timeout Timeout of the debounce action\n * @return {function(function():void):void}\n */\nexport const createDebouncer = timeout => {\n let timer = -1\n return f => {\n clearTimeout(timer)\n if (f) {\n timer = /** @type {any} */ (setTimeout(f, timeout))\n }\n }\n}\n","/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/**\n * Utility module to convert metric values.\n *\n * @module metric\n */\n\nimport * as math from './math.js'\n\nexport const yotta = 1e24\nexport const zetta = 1e21\nexport const exa = 1e18\nexport const peta = 1e15\nexport const tera = 1e12\nexport const giga = 1e9\nexport const mega = 1e6\nexport const kilo = 1e3\nexport const hecto = 1e2\nexport const deca = 10\nexport const deci = 0.1\nexport const centi = 0.01\nexport const milli = 1e-3\nexport const micro = 1e-6\nexport const nano = 1e-9\nexport const pico = 1e-12\nexport const femto = 1e-15\nexport const atto = 1e-18\nexport const zepto = 1e-21\nexport const yocto = 1e-24\n\nconst prefixUp = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']\nconst prefixDown = ['', 'm', 'μ', 'n', 'p', 'f', 'a', 'z', 'y']\n\n/**\n * Calculate the metric prefix for a number. Assumes E.g. `prefix(1000) = { n: 1, prefix: 'k' }`\n *\n * @param {number} n\n * @param {number} [baseMultiplier] Multiplier of the base (10^(3*baseMultiplier)). E.g. `convert(time, -3)` if time is already in milli seconds\n * @return {{n:number,prefix:string}}\n */\nexport const prefix = (n, baseMultiplier = 0) => {\n const nPow = n === 0 ? 0 : math.log10(n)\n let mult = 0\n while (nPow < mult * 3 && baseMultiplier > -8) {\n baseMultiplier--\n mult--\n }\n while (nPow >= 3 + mult * 3 && baseMultiplier < 8) {\n baseMultiplier++\n mult++\n }\n const prefix = baseMultiplier < 0 ? prefixDown[-baseMultiplier] : prefixUp[baseMultiplier]\n return {\n n: math.round((mult > 0 ? n / math.exp10(mult * 3) : n * math.exp10(mult * -3)) * 1e12) / 1e12,\n prefix\n }\n}\n","/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* istanbul ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n","/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {Array} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array}\n */\nexport const create = () => /** @type {Array} */ ([])\n\n/**\n * @template D\n * @param {Array} a\n * @return {Array}\n */\nexport const copy = a => /** @type {Array} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array} dest\n * @param {Array} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike|Iterable} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template ITEM\n *\n * @param {Array} arr\n * @param {function(ITEM, number, Array):boolean} f\n * @return {boolean}\n */\nexport const every = (arr, f) => arr.every(f)\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template S\n * @param {Array} arr\n * @param {function(S, number, Array):boolean} f\n * @return {boolean}\n */\nexport const some = (arr, f) => arr.some(f)\n\n/**\n * @template ELEM\n *\n * @param {Array} a\n * @param {Array} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n","/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object} obj\n */\nexport const keys = Object.keys\n\n/**\n * @param {Object} obj\n * @param {function(any,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @template R\n * @param {Object} obj\n * @param {function(any,string):R} f\n * @return {Array}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @param {Object} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))\n","/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array} fs\n * @param {Array} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array|object} a\n * @param {Array|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((a instanceof Array && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a == null || b == null) {\n return equalityStrict(a, b)\n }\n if (a.constructor !== b.constructor) {\n return false\n }\n if (a === b) {\n return true\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n","/**\n * Isomorphic logging module with support for colors!\n *\n * @module logging\n */\n\nimport * as env from './environment.js'\nimport * as symbol from './symbol.js'\nimport * as pair from './pair.js'\nimport * as dom from './dom.js'\nimport * as json from './json.js'\nimport * as map from './map.js'\nimport * as eventloop from './eventloop.js'\nimport * as math from './math.js'\nimport * as time from './time.js'\nimport * as func from './function.js'\n\nexport const BOLD = symbol.create()\nexport const UNBOLD = symbol.create()\nexport const BLUE = symbol.create()\nexport const GREY = symbol.create()\nexport const GREEN = symbol.create()\nexport const RED = symbol.create()\nexport const PURPLE = symbol.create()\nexport const ORANGE = symbol.create()\nexport const UNCOLOR = symbol.create()\n\n/**\n * @type {Object>}\n */\nconst _browserStyleMap = {\n [BOLD]: pair.create('font-weight', 'bold'),\n [UNBOLD]: pair.create('font-weight', 'normal'),\n [BLUE]: pair.create('color', 'blue'),\n [GREEN]: pair.create('color', 'green'),\n [GREY]: pair.create('color', 'grey'),\n [RED]: pair.create('color', 'red'),\n [PURPLE]: pair.create('color', 'purple'),\n [ORANGE]: pair.create('color', 'orange'), // not well supported in chrome when debugging node with inspector - TODO: deprecate\n [UNCOLOR]: pair.create('color', 'black')\n}\n\nconst _nodeStyleMap = {\n [BOLD]: '\\u001b[1m',\n [UNBOLD]: '\\u001b[2m',\n [BLUE]: '\\x1b[34m',\n [GREEN]: '\\x1b[32m',\n [GREY]: '\\u001b[37m',\n [RED]: '\\x1b[31m',\n [PURPLE]: '\\x1b[35m',\n [ORANGE]: '\\x1b[38;5;208m',\n [UNCOLOR]: '\\x1b[0m'\n}\n\n/* istanbul ignore next */\n/**\n * @param {Array} args\n * @return {Array}\n */\nconst computeBrowserLoggingArgs = args => {\n const strBuilder = []\n const styles = []\n const currentStyle = map.create()\n /**\n * @type {Array}\n */\n let logArgs = []\n // try with formatting until we find something unsupported\n let i = 0\n\n for (; i < args.length; i++) {\n const arg = args[i]\n // @ts-ignore\n const style = _browserStyleMap[arg]\n if (style !== undefined) {\n currentStyle.set(style.left, style.right)\n } else {\n if (arg.constructor === String || arg.constructor === Number) {\n const style = dom.mapToStyleString(currentStyle)\n if (i > 0 || style.length > 0) {\n strBuilder.push('%c' + arg)\n styles.push(style)\n } else {\n strBuilder.push(arg)\n }\n } else {\n break\n }\n }\n }\n\n if (i > 0) {\n // create logArgs with what we have so far\n logArgs = styles\n logArgs.unshift(strBuilder.join(''))\n }\n // append the rest\n for (; i < args.length; i++) {\n const arg = args[i]\n if (!(arg instanceof Symbol)) {\n logArgs.push(arg)\n }\n }\n return logArgs\n}\n\n/**\n * @param {Array} args\n * @return {Array}\n */\nconst computeNodeLoggingArgs = args => {\n const strBuilder = []\n const logArgs = []\n\n // try with formatting until we find something unsupported\n let i = 0\n\n for (; i < args.length; i++) {\n const arg = args[i]\n // @ts-ignore\n const style = _nodeStyleMap[arg]\n if (style !== undefined) {\n strBuilder.push(style)\n } else {\n if (arg.constructor === String || arg.constructor === Number) {\n strBuilder.push(arg)\n } else {\n break\n }\n }\n }\n if (i > 0) {\n // create logArgs with what we have so far\n strBuilder.push('\\x1b[0m')\n logArgs.push(strBuilder.join(''))\n }\n // append the rest\n for (; i < args.length; i++) {\n const arg = args[i]\n /* istanbul ignore else */\n if (!(arg instanceof Symbol)) {\n logArgs.push(arg)\n }\n }\n return logArgs\n}\n\n/* istanbul ignore next */\nconst computeLoggingArgs = env.isNode ? computeNodeLoggingArgs : computeBrowserLoggingArgs\n\n/**\n * @param {Array} args\n */\nexport const print = (...args) => {\n console.log(...computeLoggingArgs(args))\n /* istanbul ignore next */\n vconsoles.forEach(vc => vc.print(args))\n}\n\n/* istanbul ignore next */\n/**\n * @param {Array} args\n */\nexport const warn = (...args) => {\n console.warn(...computeLoggingArgs(args))\n args.unshift(ORANGE)\n vconsoles.forEach(vc => vc.print(args))\n}\n\n/* istanbul ignore next */\n/**\n * @param {Error} err\n */\nexport const printError = err => {\n console.error(err)\n vconsoles.forEach(vc => vc.printError(err))\n}\n\n/* istanbul ignore next */\n/**\n * @param {string} url image location\n * @param {number} height height of the image in pixel\n */\nexport const printImg = (url, height) => {\n if (env.isBrowser) {\n console.log('%c ', `font-size: ${height}px; background-size: contain; background-repeat: no-repeat; background-image: url(${url})`)\n // console.log('%c ', `font-size: ${height}x; background: url(${url}) no-repeat;`)\n }\n vconsoles.forEach(vc => vc.printImg(url, height))\n}\n\n/* istanbul ignore next */\n/**\n * @param {string} base64\n * @param {number} height\n */\nexport const printImgBase64 = (base64, height) => printImg(`data:image/gif;base64,${base64}`, height)\n\n/**\n * @param {Array} args\n */\nexport const group = (...args) => {\n console.group(...computeLoggingArgs(args))\n /* istanbul ignore next */\n vconsoles.forEach(vc => vc.group(args))\n}\n\n/**\n * @param {Array} args\n */\nexport const groupCollapsed = (...args) => {\n console.groupCollapsed(...computeLoggingArgs(args))\n /* istanbul ignore next */\n vconsoles.forEach(vc => vc.groupCollapsed(args))\n}\n\nexport const groupEnd = () => {\n console.groupEnd()\n /* istanbul ignore next */\n vconsoles.forEach(vc => vc.groupEnd())\n}\n\n/* istanbul ignore next */\n/**\n * @param {function():Node} createNode\n */\nexport const printDom = createNode =>\n vconsoles.forEach(vc => vc.printDom(createNode()))\n\n/* istanbul ignore next */\n/**\n * @param {HTMLCanvasElement} canvas\n * @param {number} height\n */\nexport const printCanvas = (canvas, height) => printImg(canvas.toDataURL(), height)\n\nexport const vconsoles = new Set()\n\n/* istanbul ignore next */\n/**\n * @param {Array} args\n * @return {Array}\n */\nconst _computeLineSpans = args => {\n const spans = []\n const currentStyle = new Map()\n // try with formatting until we find something unsupported\n let i = 0\n for (; i < args.length; i++) {\n const arg = args[i]\n // @ts-ignore\n const style = _browserStyleMap[arg]\n if (style !== undefined) {\n currentStyle.set(style.left, style.right)\n } else {\n if (arg.constructor === String || arg.constructor === Number) {\n // @ts-ignore\n const span = dom.element('span', [pair.create('style', dom.mapToStyleString(currentStyle))], [dom.text(arg)])\n if (span.innerHTML === '') {\n span.innerHTML = ' '\n }\n spans.push(span)\n } else {\n break\n }\n }\n }\n // append the rest\n for (; i < args.length; i++) {\n let content = args[i]\n if (!(content instanceof Symbol)) {\n if (content.constructor !== String && content.constructor !== Number) {\n content = ' ' + json.stringify(content) + ' '\n }\n spans.push(dom.element('span', [], [dom.text(/** @type {string} */ (content))]))\n }\n }\n return spans\n}\n\nconst lineStyle = 'font-family:monospace;border-bottom:1px solid #e2e2e2;padding:2px;'\n\n/* istanbul ignore next */\nexport class VConsole {\n /**\n * @param {Element} dom\n */\n constructor (dom) {\n this.dom = dom\n /**\n * @type {Element}\n */\n this.ccontainer = this.dom\n this.depth = 0\n vconsoles.add(this)\n }\n\n /**\n * @param {Array} args\n * @param {boolean} collapsed\n */\n group (args, collapsed = false) {\n eventloop.enqueue(() => {\n const triangleDown = dom.element('span', [pair.create('hidden', collapsed), pair.create('style', 'color:grey;font-size:120%;')], [dom.text('▼')])\n const triangleRight = dom.element('span', [pair.create('hidden', !collapsed), pair.create('style', 'color:grey;font-size:125%;')], [dom.text('▶')])\n const content = dom.element('div', [pair.create('style', `${lineStyle};padding-left:${this.depth * 10}px`)], [triangleDown, triangleRight, dom.text(' ')].concat(_computeLineSpans(args)))\n const nextContainer = dom.element('div', [pair.create('hidden', collapsed)])\n const nextLine = dom.element('div', [], [content, nextContainer])\n dom.append(this.ccontainer, [nextLine])\n this.ccontainer = nextContainer\n this.depth++\n // when header is clicked, collapse/uncollapse container\n dom.addEventListener(content, 'click', event => {\n nextContainer.toggleAttribute('hidden')\n triangleDown.toggleAttribute('hidden')\n triangleRight.toggleAttribute('hidden')\n })\n })\n }\n\n /**\n * @param {Array} args\n */\n groupCollapsed (args) {\n this.group(args, true)\n }\n\n groupEnd () {\n eventloop.enqueue(() => {\n if (this.depth > 0) {\n this.depth--\n // @ts-ignore\n this.ccontainer = this.ccontainer.parentElement.parentElement\n }\n })\n }\n\n /**\n * @param {Array} args\n */\n print (args) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [dom.element('div', [pair.create('style', `${lineStyle};padding-left:${this.depth * 10}px`)], _computeLineSpans(args))])\n })\n }\n\n /**\n * @param {Error} err\n */\n printError (err) {\n this.print([RED, BOLD, err.toString()])\n }\n\n /**\n * @param {string} url\n * @param {number} height\n */\n printImg (url, height) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [dom.element('img', [pair.create('src', url), pair.create('height', `${math.round(height * 1.5)}px`)])])\n })\n }\n\n /**\n * @param {Node} node\n */\n printDom (node) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [node])\n })\n }\n\n destroy () {\n eventloop.enqueue(() => {\n vconsoles.delete(this)\n })\n }\n}\n\n/* istanbul ignore next */\n/**\n * @param {Element} dom\n */\nexport const createVConsole = dom => new VConsole(dom)\n\nconst loggingColors = [GREEN, PURPLE, ORANGE, BLUE]\nlet nextColor = 0\nlet lastLoggingTime = time.getUnixTime()\n\n/**\n * @param {string} moduleName\n * @return {function(...any)}\n */\nexport const createModuleLogger = moduleName => {\n const color = loggingColors[nextColor]\n const debugRegexVar = env.getVariable('log')\n const doLogging = debugRegexVar !== null && (debugRegexVar === '*' || debugRegexVar === 'true' || new RegExp(debugRegexVar, 'gi').test(moduleName))\n nextColor = (nextColor + 1) % loggingColors.length\n moduleName += ': '\n\n return !doLogging ? func.nop : (...args) => {\n const timeNow = time.getUnixTime()\n const timeDiff = timeNow - lastLoggingTime\n lastLoggingTime = timeNow\n print(color, moduleName, UNCOLOR, ...args.map(arg => (typeof arg === 'string' || typeof arg === 'symbol') ? arg : JSON.stringify(arg)), color, ' +' + timeDiff + 'ms')\n }\n}\n","/**\n * Efficient diffs.\n *\n * @module diff\n */\n\nimport { equalityStrict } from './function.js'\n\n/**\n * A SimpleDiff describes a change on a String.\n *\n * ```js\n * console.log(a) // the old value\n * console.log(b) // the updated value\n * // Apply changes of diff (pseudocode)\n * a.remove(diff.index, diff.remove) // Remove `diff.remove` characters\n * a.insert(diff.index, diff.insert) // Insert `diff.insert`\n * a === b // values match\n * ```\n *\n * @typedef {Object} SimpleDiff\n * @property {Number} index The index where changes were applied\n * @property {Number} remove The number of characters to delete starting\n * at `index`.\n * @property {T} insert The new text to insert at `index` after applying\n * `delete`\n *\n * @template T\n */\n\n/**\n * Create a diff between two strings. This diff implementation is highly\n * efficient, but not very sophisticated.\n *\n * @function\n *\n * @param {string} a The old version of the string\n * @param {string} b The updated version of the string\n * @return {SimpleDiff} The diff description.\n */\nexport const simpleDiffString = (a, b) => {\n let left = 0 // number of same characters counting from left\n let right = 0 // number of same characters counting from right\n while (left < a.length && left < b.length && a[left] === b[left]) {\n left++\n }\n if (left !== a.length || left !== b.length) {\n // Only check right if a !== b\n while (right + left < a.length && right + left < b.length && a[a.length - right - 1] === b[b.length - right - 1]) {\n right++\n }\n }\n return {\n index: left,\n remove: a.length - left - right,\n insert: b.slice(left, b.length - right)\n }\n}\n\n/**\n * @todo Remove in favor of simpleDiffString\n * @deprecated\n */\nexport const simpleDiff = simpleDiffString\n\n/**\n * Create a diff between two arrays. This diff implementation is highly\n * efficient, but not very sophisticated.\n *\n * Note: This is basically the same function as above. Another function was created so that the runtime\n * can better optimize these function calls.\n *\n * @function\n * @template T\n *\n * @param {Array} a The old version of the array\n * @param {Array} b The updated version of the array\n * @param {function(T, T):boolean} [compare]\n * @return {SimpleDiff>} The diff description.\n */\nexport const simpleDiffArray = (a, b, compare = equalityStrict) => {\n let left = 0 // number of same characters counting from left\n let right = 0 // number of same characters counting from right\n while (left < a.length && left < b.length && compare(a[left], b[left])) {\n left++\n }\n if (left !== a.length || left !== b.length) {\n // Only check right if a !== b\n while (right + left < a.length && right + left < b.length && compare(a[a.length - right - 1], b[b.length - right - 1])) {\n right++\n }\n }\n return {\n index: left,\n remove: a.length - left - right,\n insert: b.slice(left, b.length - right)\n }\n}\n","/* eslint-env browser */\nconst perf = typeof performance === 'undefined' ? null : performance\n\nconst isoCrypto = typeof crypto === 'undefined' ? null : crypto\n\n/**\n * @type {function(number):ArrayBuffer}\n */\nconst cryptoRandomBuffer = isoCrypto !== null\n ? len => {\n // browser\n const buf = new ArrayBuffer(len)\n const arr = new Uint8Array(buf)\n isoCrypto.getRandomValues(arr)\n return buf\n }\n : len => {\n // polyfill\n const buf = new ArrayBuffer(len)\n const arr = new Uint8Array(buf)\n for (let i = 0; i < len; i++) {\n arr[i] = Math.ceil((Math.random() * 0xFFFFFFFF) >>> 0)\n }\n return buf\n }\n\nexports.performance = perf\nexports.cryptoRandomBuffer = cryptoRandomBuffer\n","/**\n * Isomorphic library exports from isomorphic.js.\n *\n * @module isomorphic\n */\n\n// @ts-ignore\nimport iso from 'isomorphic.js'\n\nexport const performance = /** @type {any} */ (iso.performance)\nexport const cryptoRandomBuffer = /** @type {any} */ (iso.cryptoRandomBuffer)\n","\n/**\n * Isomorphic module for true random numbers / buffers / uuids.\n *\n * Attention: falls back to Math.random if the browser does not support crypto.\n *\n * @module random\n */\n\nimport * as math from './math.js'\nimport { cryptoRandomBuffer } from './isomorphic.js'\n\nexport const rand = Math.random\n\n/* istanbul ignore next */\nexport const uint32 = () => new Uint32Array(cryptoRandomBuffer(4))[0]\n\n/**\n * @template T\n * @param {Array} arr\n * @return {T}\n */\nexport const oneOf = arr => arr[math.floor(rand() * arr.length)]\n\n// @ts-ignore\nconst uuidv4Template = [1e7] + -1e3 + -4e3 + -8e3 + -1e11\nexport const uuidv4 = () => uuidv4Template.replace(/[018]/g, /** @param {number} c */ c =>\n (c ^ uint32() & 15 >> c / 4).toString(16)\n)\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * @module prng\n */\n\nimport * as binary from '../binary.js'\n\n/**\n * Xorshift32 is a very simple but elegang PRNG with a period of `2^32-1`.\n */\nexport class Xorshift32 {\n /**\n * @param {number} seed Unsigned 32 bit number\n */\n constructor (seed) {\n this.seed = seed\n /**\n * @type {number}\n */\n this._state = seed\n }\n\n /**\n * Generate a random signed integer.\n *\n * @return {Number} A 32 bit signed integer.\n */\n next () {\n let x = this._state\n x ^= x << 13\n x ^= x >> 17\n x ^= x << 5\n this._state = x\n return (x >>> 0) / (binary.BITS32 + 1)\n }\n}\n","/**\n * @module prng\n */\n\nimport { Xorshift32 } from './Xorshift32.js'\nimport * as binary from '../binary.js'\n\n/**\n * This is a variant of xoroshiro128plus - the fastest full-period generator passing BigCrush without systematic failures.\n *\n * This implementation follows the idea of the original xoroshiro128plus implementation,\n * but is optimized for the JavaScript runtime. I.e.\n * * The operations are performed on 32bit integers (the original implementation works with 64bit values).\n * * The initial 128bit state is computed based on a 32bit seed and Xorshift32.\n * * This implementation returns two 32bit values based on the 64bit value that is computed by xoroshiro128plus.\n * Caution: The last addition step works slightly different than in the original implementation - the add carry of the\n * first 32bit addition is not carried over to the last 32bit.\n *\n * [Reference implementation](http://vigna.di.unimi.it/xorshift/xoroshiro128plus.c)\n */\nexport class Xoroshiro128plus {\n /**\n * @param {number} seed Unsigned 32 bit number\n */\n constructor (seed) {\n this.seed = seed\n // This is a variant of Xoroshiro128plus to fill the initial state\n const xorshift32 = new Xorshift32(seed)\n this.state = new Uint32Array(4)\n for (let i = 0; i < 4; i++) {\n this.state[i] = xorshift32.next() * binary.BITS32\n }\n this._fresh = true\n }\n\n /**\n * @return {number} Float/Double in [0,1)\n */\n next () {\n const state = this.state\n if (this._fresh) {\n this._fresh = false\n return ((state[0] + state[2]) >>> 0) / (binary.BITS32 + 1)\n } else {\n this._fresh = true\n const s0 = state[0]\n const s1 = state[1]\n const s2 = state[2] ^ s0\n const s3 = state[3] ^ s1\n // function js_rotl (x, k) {\n // k = k - 32\n // const x1 = x[0]\n // const x2 = x[1]\n // x[0] = x2 << k | x1 >>> (32 - k)\n // x[1] = x1 << k | x2 >>> (32 - k)\n // }\n // rotl(s0, 55) // k = 23 = 55 - 32; j = 9 = 32 - 23\n state[0] = (s1 << 23 | s0 >>> 9) ^ s2 ^ (s2 << 14 | s3 >>> 18)\n state[1] = (s0 << 23 | s1 >>> 9) ^ s3 ^ (s3 << 14)\n // rol(s1, 36) // k = 4 = 36 - 32; j = 23 = 32 - 9\n state[2] = s3 << 4 | s2 >>> 28\n state[3] = s2 << 4 | s3 >>> 28\n return (((state[1] + state[3]) >>> 0) / (binary.BITS32 + 1))\n }\n }\n}\n\n/*\n// Reference implementation\n// Source: http://vigna.di.unimi.it/xorshift/xoroshiro128plus.c\n// By David Blackman and Sebastiano Vigna\n// Who published the reference implementation under Public Domain (CC0)\n\n#include \n#include \n\nuint64_t s[2];\n\nstatic inline uint64_t rotl(const uint64_t x, int k) {\n return (x << k) | (x >> (64 - k));\n}\n\nuint64_t next(void) {\n const uint64_t s0 = s[0];\n uint64_t s1 = s[1];\n s1 ^= s0;\n s[0] = rotl(s0, 55) ^ s1 ^ (s1 << 14); // a, b\n s[1] = rotl(s1, 36); // c\n return (s[0] + s[1]) & 0xFFFFFFFF;\n}\n\nint main(void)\n{\n int i;\n s[0] = 1111 | (1337ul << 32);\n s[1] = 1234 | (9999ul << 32);\n\n printf(\"1000 outputs of genrand_int31()\\n\");\n for (i=0; i<100; i++) {\n printf(\"%10lu \", i);\n printf(\"%10lu \", next());\n printf(\"- %10lu \", s[0] >> 32);\n printf(\"%10lu \", (s[0] << 32) >> 32);\n printf(\"%10lu \", s[1] >> 32);\n printf(\"%10lu \", (s[1] << 32) >> 32);\n printf(\"\\n\");\n // if (i%5==4) printf(\"\\n\");\n }\n return 0;\n}\n*/\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\n/**\n * @type {number}\n */\nexport const HIGHEST_INT32 = binary.BITS31\n\n/**\n * @module number\n */\n\n/* istanbul ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = new encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = new decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nconst verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer.\n *\n * Encodes integers in the range from [0, 4294967295] / [0, 0xffffffff]. (max 32 bit unsigned integer)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num >>>= 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * Encodes integers in the range from [-2147483648, -2147483647].\n *\n * We don't use zig-zag encoding because we want to keep the option open\n * to use the same function for BigInt and 53bit integers (doubles).\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num >>>= 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num >>>= 7\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeVarString = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write the content of another Encoder.\n *\n * TODO: can be improved!\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && data <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (data instanceof Array) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = new encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = new decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as binary from './binary.js'\nimport * as math from './math.js'\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n */\nexport class Decoder {\n /**\n * @param {Uint8Array} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @param {Uint8Array} uint8Array\n * @return {Decoder}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = buffer.createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing position.\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing position.\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing position.\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let len = 0\n while (true) {\n const r = decoder.arr[decoder.pos++]\n num = num | ((r & binary.BITS7) << len)\n len += 7\n if (r < binary.BIT8) {\n return num >>> 0 // return unsigned number!\n }\n /* istanbul ignore if */\n if (len > 35) {\n throw new Error('Integer out of range!')\n }\n }\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if unmber is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let len = 6\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n while (true) {\n r = decoder.arr[decoder.pos++]\n num = num | ((r & binary.BITS7) << len)\n len += 7\n if (r < binary.BIT8) {\n return sign * (num >>> 0)\n }\n /* istanbul ignore if */\n if (len > 41) {\n throw new Error('Integer out of range!')\n }\n }\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\nexport const readVarString = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0)\n\n/**\n * @type {Array}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object\n const len = readVarUint(decoder)\n /**\n * @type {Object}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = diff >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","/**\n * Utility functions to work with buffers (Uint8Array).\n *\n * @module buffer\n */\n\nimport * as string from './string.js'\nimport * as env from './environment.js'\nimport * as encoding from './encoding.js'\nimport * as decoding from './decoding.js'\n\n/**\n * @param {number} len\n */\nexport const createUint8ArrayFromLen = len => new Uint8Array(len)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n * @param {number} byteOffset\n * @param {number} length\n */\nexport const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n */\nexport const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)\n\n/* istanbul ignore next */\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Browser = bytes => {\n let s = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n s += string.fromCharCode(bytes[i])\n }\n // eslint-disable-next-line no-undef\n return btoa(s)\n}\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')\n\n/* istanbul ignore next */\n/**\n * @param {string} s\n * @return {Uint8Array}\n */\nconst fromBase64Browser = s => {\n // eslint-disable-next-line no-undef\n const a = atob(s)\n const bytes = createUint8ArrayFromLen(a.length)\n for (let i = 0; i < a.length; i++) {\n bytes[i] = a.charCodeAt(i)\n }\n return bytes\n}\n\n/**\n * @param {string} s\n */\nconst fromBase64Node = s => {\n const buf = Buffer.from(s, 'base64')\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n\n/* istanbul ignore next */\nexport const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node\n\n/* istanbul ignore next */\nexport const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node\n\n/**\n * Copy the content of an Uint8Array view to a new ArrayBuffer.\n *\n * @param {Uint8Array} uint8Array\n * @return {Uint8Array}\n */\nexport const copyUint8Array = uint8Array => {\n const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)\n newBuf.set(uint8Array)\n return newBuf\n}\n\n/**\n * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.\n * See encoding.writeAny for more information.\n *\n * @param {any} data\n * @return {Uint8Array}\n */\nexport const encodeAny = data => {\n const encoder = encoding.createEncoder()\n encoding.writeAny(encoder, data)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Decode an any-encoded value.\n *\n * @param {Uint8Array} buf\n * @return {any}\n */\nexport const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))\n","/**\n * Fast Pseudo Random Number Generators.\n *\n * Given a seed a PRNG generates a sequence of numbers that cannot be reasonably predicted.\n * Two PRNGs must generate the same random sequence of numbers if given the same seed.\n *\n * @module prng\n */\n\nimport * as binary from './binary.js'\nimport { fromCharCode, fromCodePoint } from './string.js'\nimport * as math from './math.js'\nimport { Xoroshiro128plus } from './prng/Xoroshiro128plus.js'\nimport * as buffer from './buffer.js'\n\n/**\n * Description of the function\n * @callback generatorNext\n * @return {number} A 32bit integer\n */\n\n/**\n * A random type generator.\n *\n * @typedef {Object} PRNG\n * @property {generatorNext} next Generate new number\n */\n\nexport const DefaultPRNG = Xoroshiro128plus\n\n/**\n * Create a Xoroshiro128plus Pseudo-Random-Number-Generator.\n * This is the fastest full-period generator passing BigCrush without systematic failures.\n * But there are more PRNGs available in ./PRNG/.\n *\n * @param {number} seed A positive 32bit integer. Do not use negative numbers.\n * @return {PRNG}\n */\nexport const create = seed => new DefaultPRNG(seed)\n\n/**\n * Generates a single random bool.\n *\n * @param {PRNG} gen A random number generator.\n * @return {Boolean} A random boolean\n */\nexport const bool = gen => (gen.next() >= 0.5)\n\n/**\n * Generates a random integer with 53 bit resolution.\n *\n * @param {PRNG} gen A random number generator.\n * @param {Number} min The lower bound of the allowed return values (inclusive).\n * @param {Number} max The upper bound of the allowed return values (inclusive).\n * @return {Number} A random integer on [min, max]\n */\nexport const int53 = (gen, min, max) => math.floor(gen.next() * (max + 1 - min) + min)\n\n/**\n * Generates a random integer with 53 bit resolution.\n *\n * @param {PRNG} gen A random number generator.\n * @param {Number} min The lower bound of the allowed return values (inclusive).\n * @param {Number} max The upper bound of the allowed return values (inclusive).\n * @return {Number} A random integer on [min, max]\n */\nexport const uint53 = (gen, min, max) => math.abs(int53(gen, min, max))\n\n/**\n * Generates a random integer with 32 bit resolution.\n *\n * @param {PRNG} gen A random number generator.\n * @param {Number} min The lower bound of the allowed return values (inclusive).\n * @param {Number} max The upper bound of the allowed return values (inclusive).\n * @return {Number} A random integer on [min, max]\n */\nexport const int32 = (gen, min, max) => math.floor(gen.next() * (max + 1 - min) + min)\n\n/**\n * Generates a random integer with 53 bit resolution.\n *\n * @param {PRNG} gen A random number generator.\n * @param {Number} min The lower bound of the allowed return values (inclusive).\n * @param {Number} max The upper bound of the allowed return values (inclusive).\n * @return {Number} A random integer on [min, max]\n */\nexport const uint32 = (gen, min, max) => int32(gen, min, max) >>> 0\n\n/**\n * @deprecated\n * Optimized version of prng.int32. It has the same precision as prng.int32, but should be preferred when\n * openaring on smaller ranges.\n *\n * @param {PRNG} gen A random number generator.\n * @param {Number} min The lower bound of the allowed return values (inclusive).\n * @param {Number} max The upper bound of the allowed return values (inclusive). The max inclusive number is `binary.BITS31-1`\n * @return {Number} A random integer on [min, max]\n */\nexport const int31 = (gen, min, max) => int32(gen, min, max)\n\n/**\n * Generates a random real on [0, 1) with 53 bit resolution.\n *\n * @param {PRNG} gen A random number generator.\n * @return {Number} A random real number on [0, 1).\n */\nexport const real53 = gen => gen.next() // (((gen.next() >>> 5) * binary.BIT26) + (gen.next() >>> 6)) / MAX_SAFE_INTEGER\n\n/**\n * Generates a random character from char code 32 - 126. I.e. Characters, Numbers, special characters, and Space:\n *\n * @param {PRNG} gen A random number generator.\n * @return {string}\n *\n * (Space)!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[/]^_`abcdefghijklmnopqrstuvwxyz{|}~\n */\nexport const char = gen => fromCharCode(int31(gen, 32, 126))\n\n/**\n * @param {PRNG} gen\n * @return {string} A single letter (a-z)\n */\nexport const letter = gen => fromCharCode(int31(gen, 97, 122))\n\n/**\n * @param {PRNG} gen\n * @param {number} [minLen=0]\n * @param {number} [maxLen=20]\n * @return {string} A random word (0-20 characters) without spaces consisting of letters (a-z)\n */\nexport const word = (gen, minLen = 0, maxLen = 20) => {\n const len = int31(gen, minLen, maxLen)\n let str = ''\n for (let i = 0; i < len; i++) {\n str += letter(gen)\n }\n return str\n}\n\n/**\n * TODO: this function produces invalid runes. Does not cover all of utf16!!\n *\n * @param {PRNG} gen\n * @return {string}\n */\nexport const utf16Rune = gen => {\n const codepoint = int31(gen, 0, 256)\n return fromCodePoint(codepoint)\n}\n\n/**\n * @param {PRNG} gen\n * @param {number} [maxlen = 20]\n */\nexport const utf16String = (gen, maxlen = 20) => {\n const len = int31(gen, 0, maxlen)\n let str = ''\n for (let i = 0; i < len; i++) {\n str += utf16Rune(gen)\n }\n return str\n}\n\n/**\n * Returns one element of a given array.\n *\n * @param {PRNG} gen A random number generator.\n * @param {Array} array Non empty Array of possible values.\n * @return {T} One of the values of the supplied Array.\n * @template T\n */\nexport const oneOf = (gen, array) => array[int31(gen, 0, array.length - 1)]\n\n/**\n * @param {PRNG} gen\n * @param {number} len\n * @return {Uint8Array}\n */\nexport const uint8Array = (gen, len) => {\n const buf = buffer.createUint8ArrayFromLen(len)\n for (let i = 0; i < buf.length; i++) {\n buf[i] = int32(gen, 0, binary.BITS8)\n }\n return buf\n}\n\n/**\n * @param {PRNG} gen\n * @param {number} len\n * @return {Uint16Array}\n */\nexport const uint16Array = (gen, len) => new Uint16Array(uint8Array(gen, len * 2).buffer)\n\n/**\n * @param {PRNG} gen\n * @param {number} len\n * @return {Uint32Array}\n */\nexport const uint32Array = (gen, len) => new Uint32Array(uint8Array(gen, len * 4).buffer)\n","/**\n * Utility helpers for generating statistics.\n *\n * @module statistics\n */\n\nimport * as math from './math.js'\n\n/**\n * @param {Array} arr Array of values\n * @return {number} Returns null if the array is empty\n */\nexport const median = arr => arr.length === 0 ? NaN : (arr.length % 2 === 1 ? arr[(arr.length - 1) / 2] : (arr[math.floor((arr.length - 1) / 2)] + arr[math.ceil((arr.length - 1) / 2)]) / 2)\n\n/**\n * @param {Array} arr\n * @return {number}\n */\nexport const average = arr => arr.reduce(math.add, 0) / arr.length\n","/**\n * Utility helpers to work with promises.\n *\n * @module promise\n */\n\nimport * as time from './time.js'\n\n/**\n * @template T\n * @callback PromiseResolve\n * @param {T|PromiseLike} [result]\n */\n\n/**\n * @template T\n * @param {function(PromiseResolve,function(Error):void):any} f\n * @return {Promise}\n */\nexport const create = f => new Promise(f)\n\n/**\n * @param {function(function():void,function(Error):void):void} f\n * @return {Promise}\n */\nexport const createEmpty = f => new Promise(f)\n\n/**\n * `Promise.all` wait for all promises in the array to resolve and return the result\n * @template T\n * @param {Array>} arrp\n * @return {Promise>}\n */\nexport const all = arrp => Promise.all(arrp)\n\n/**\n * @param {Error} [reason]\n * @return {Promise}\n */\nexport const reject = reason => Promise.reject(reason)\n\n/**\n * @template T\n * @param {T|void} res\n * @return {Promise}\n */\nexport const resolve = res => Promise.resolve(res)\n\n/**\n * @todo Next version, reorder parameters: check, [timeout, [intervalResolution]]\n *\n * @param {number} timeout\n * @param {function():boolean} check\n * @param {number} [intervalResolution]\n * @return {Promise}\n */\nexport const until = (timeout, check, intervalResolution = 10) => create((resolve, reject) => {\n const startTime = time.getUnixTime()\n const hasTimeout = timeout > 0\n const untilInterval = () => {\n if (check()) {\n clearInterval(intervalHandle)\n resolve()\n } else if (hasTimeout) {\n /* istanbul ignore else */\n if (time.getUnixTime() - startTime > timeout) {\n clearInterval(intervalHandle)\n reject(new Error('Timeout'))\n }\n }\n }\n const intervalHandle = setInterval(untilInterval, intervalResolution)\n})\n\n/**\n * @param {number} timeout\n * @return {Promise}\n */\nexport const wait = timeout => create((resolve, reject) => setTimeout(resolve, timeout))\n\n/**\n * Checks if an object is a promise using ducktyping.\n *\n * Promises are often polyfilled, so it makes sense to add some additional guarantees if the user of this\n * library has some insane environment where global Promise objects are overwritten.\n *\n * @param {any} p\n * @return {boolean}\n */\nexport const isPromise = p => p instanceof Promise || (p && p.then && p.catch && p.finally)\n","/**\n * Testing framework with support for generating tests.\n *\n * ```js\n * // test.js template for creating a test executable\n * import { runTests } from 'lib0/testing.js'\n * import * as log from 'lib0/logging.js'\n * import * as mod1 from './mod1.test.js'\n * import * as mod2 from './mod2.test.js'\n\n * import { isBrowser, isNode } from 'lib0/environment.js'\n *\n * if (isBrowser) {\n * // optional: if this is ran in the browser, attach a virtual console to the dom\n * log.createVConsole(document.body)\n * }\n *\n * runTests({\n * mod1,\n * mod2,\n * }).then(success => {\n * if (isNode) {\n * process.exit(success ? 0 : 1)\n * }\n * })\n * ```\n *\n * ```js\n * // mod1.test.js\n * /**\n * * runTests automatically tests all exported functions that start with \"test\".\n * * The name of the function should be in camelCase and is used for the logging output.\n * *\n * * @param {t.TestCase} tc\n * *\\/\n * export const testMyFirstTest = tc => {\n * t.compare({ a: 4 }, { a: 4 }, 'objects are equal')\n * }\n * ```\n *\n * Now you can simply run `node test.js` to run your test or run test.js in the browser.\n *\n * @module testing\n */\n\nimport * as log from './logging.js'\nimport { simpleDiff } from './diff.js'\nimport * as object from './object.js'\nimport * as string from './string.js'\nimport * as math from './math.js'\nimport * as random from './random.js'\nimport * as prng from './prng.js'\nimport * as statistics from './statistics.js'\nimport * as array from './array.js'\nimport * as env from './environment.js'\nimport * as json from './json.js'\nimport * as time from './time.js'\nimport * as promise from './promise.js'\n\nimport { performance } from './isomorphic.js'\n\nexport { production } from './environment.js'\n\nexport const extensive = env.hasConf('extensive')\n\n/* istanbul ignore next */\nexport const envSeed = env.hasParam('--seed') ? Number.parseInt(env.getParam('--seed', '0')) : null\n\nexport class TestCase {\n /**\n * @param {string} moduleName\n * @param {string} testName\n */\n constructor (moduleName, testName) {\n /**\n * @type {string}\n */\n this.moduleName = moduleName\n /**\n * @type {string}\n */\n this.testName = testName\n this._seed = null\n this._prng = null\n }\n\n resetSeed () {\n this._seed = null\n this._prng = null\n }\n\n /**\n * @type {number}\n */\n /* istanbul ignore next */\n get seed () {\n /* istanbul ignore else */\n if (this._seed === null) {\n /* istanbul ignore next */\n this._seed = envSeed === null ? random.uint32() : envSeed\n }\n return this._seed\n }\n\n /**\n * A PRNG for this test case. Use only this PRNG for randomness to make the test case reproducible.\n *\n * @type {prng.PRNG}\n */\n get prng () {\n /* istanbul ignore else */\n if (this._prng === null) {\n this._prng = prng.create(this.seed)\n }\n return this._prng\n }\n}\n\nexport const repititionTime = Number(env.getParam('--repitition-time', '50'))\n/* istanbul ignore next */\nconst testFilter = env.hasParam('--filter') ? env.getParam('--filter', '') : null\n\n/* istanbul ignore next */\nconst testFilterRegExp = testFilter !== null ? new RegExp(testFilter) : new RegExp('.*')\n\nconst repeatTestRegex = /^(repeat|repeating)\\s/\n\n/**\n * @param {string} moduleName\n * @param {string} name\n * @param {function(TestCase):void|Promise} f\n * @param {number} i\n * @param {number} numberOfTests\n */\nexport const run = async (moduleName, name, f, i, numberOfTests) => {\n const uncamelized = string.fromCamelCase(name.slice(4), ' ')\n const filtered = !testFilterRegExp.test(`[${i + 1}/${numberOfTests}] ${moduleName}: ${uncamelized}`)\n /* istanbul ignore if */\n if (filtered) {\n return true\n }\n const tc = new TestCase(moduleName, name)\n const repeat = repeatTestRegex.test(uncamelized)\n const groupArgs = [log.GREY, `[${i + 1}/${numberOfTests}] `, log.PURPLE, `${moduleName}: `, log.BLUE, uncamelized]\n /* istanbul ignore next */\n if (testFilter === null) {\n log.groupCollapsed(...groupArgs)\n } else {\n log.group(...groupArgs)\n }\n const times = []\n const start = performance.now()\n let lastTime = start\n let err = null\n performance.mark(`${name}-start`)\n do {\n try {\n const p = f(tc)\n if (promise.isPromise(p)) {\n await p\n }\n } catch (_err) {\n err = _err\n }\n const currTime = performance.now()\n times.push(currTime - lastTime)\n lastTime = currTime\n if (repeat && err === null && (lastTime - start) < repititionTime) {\n tc.resetSeed()\n } else {\n break\n }\n } while (err === null && (lastTime - start) < repititionTime)\n performance.mark(`${name}-end`)\n /* istanbul ignore if */\n if (err !== null && err.constructor !== SkipError) {\n log.printError(err)\n }\n performance.measure(name, `${name}-start`, `${name}-end`)\n log.groupEnd()\n const duration = lastTime - start\n let success = true\n times.sort((a, b) => a - b)\n /* istanbul ignore next */\n const againMessage = env.isBrowser\n ? ` - ${window.location.href}?filter=\\\\[${i + 1}/${tc._seed === null ? '' : `&seed=${tc._seed}`}`\n : `\\nrepeat: npm run test -- --filter \"\\\\[${i + 1}/\" ${tc._seed === null ? '' : `--seed ${tc._seed}`}`\n const timeInfo = (repeat && err === null)\n ? ` - ${times.length} repititions in ${time.humanizeDuration(duration)} (best: ${time.humanizeDuration(times[0])}, worst: ${time.humanizeDuration(array.last(times))}, median: ${time.humanizeDuration(statistics.median(times))}, average: ${time.humanizeDuration(statistics.average(times))})`\n : ` in ${time.humanizeDuration(duration)}`\n if (err !== null) {\n /* istanbul ignore else */\n if (err.constructor === SkipError) {\n log.print(log.GREY, log.BOLD, 'Skipped: ', log.UNBOLD, uncamelized)\n } else {\n success = false\n log.print(log.RED, log.BOLD, 'Failure: ', log.UNBOLD, log.UNCOLOR, uncamelized, log.GREY, timeInfo, againMessage)\n }\n } else {\n log.print(log.GREEN, log.BOLD, 'Success: ', log.UNBOLD, log.UNCOLOR, uncamelized, log.GREY, timeInfo, againMessage)\n }\n return success\n}\n\n/**\n * Describe what you are currently testing. The message will be logged.\n *\n * ```js\n * export const testMyFirstTest = tc => {\n * t.describe('crunching numbers', 'already crunched 4 numbers!') // the optional second argument can describe the state.\n * }\n * ```\n *\n * @param {string} description\n * @param {string} info\n */\nexport const describe = (description, info = '') => log.print(log.BLUE, description, ' ', log.GREY, info)\n\n/**\n * Describe the state of the current computation.\n * ```js\n * export const testMyFirstTest = tc => {\n * t.info(already crunched 4 numbers!') // the optional second argument can describe the state.\n * }\n * ```\n *\n * @param {string} info\n */\nexport const info = info => describe('', info)\n\nexport const printDom = log.printDom\n\nexport const printCanvas = log.printCanvas\n\n/**\n * Group outputs in a collapsible category.\n *\n * ```js\n * export const testMyFirstTest = tc => {\n * t.group('subtest 1', () => {\n * t.describe('this message is part of a collapsible section')\n * })\n * await t.groupAsync('subtest async 2', async () => {\n * await someaction()\n * t.describe('this message is part of a collapsible section')\n * })\n * }\n * ```\n *\n * @param {string} description\n * @param {function(void):void} f\n */\nexport const group = (description, f) => {\n log.group(log.BLUE, description)\n try {\n f()\n } finally {\n log.groupEnd()\n }\n}\n\n/**\n * Group outputs in a collapsible category.\n *\n * ```js\n * export const testMyFirstTest = async tc => {\n * t.group('subtest 1', () => {\n * t.describe('this message is part of a collapsible section')\n * })\n * await t.groupAsync('subtest async 2', async () => {\n * await someaction()\n * t.describe('this message is part of a collapsible section')\n * })\n * }\n * ```\n *\n * @param {string} description\n * @param {function(void):Promise} f\n */\nexport const groupAsync = async (description, f) => {\n log.group(log.BLUE, description)\n try {\n await f()\n } finally {\n log.groupEnd()\n }\n}\n\n/**\n * Measure the time that it takes to calculate something.\n *\n * ```js\n * export const testMyFirstTest = async tc => {\n * t.measureTime('measurement', () => {\n * heavyCalculation()\n * })\n * await t.groupAsync('async measurement', async () => {\n * await heavyAsyncCalculation()\n * })\n * }\n * ```\n *\n * @param {string} message\n * @param {function():void} f\n * @return {number} Returns a promise that resolves the measured duration to apply f\n */\nexport const measureTime = (message, f) => {\n let duration\n const start = performance.now()\n try {\n f()\n } finally {\n duration = performance.now() - start\n log.print(log.PURPLE, message, log.GREY, ` ${time.humanizeDuration(duration)}`)\n }\n return duration\n}\n\n/**\n * Measure the time that it takes to calculate something.\n *\n * ```js\n * export const testMyFirstTest = async tc => {\n * t.measureTimeAsync('measurement', async () => {\n * await heavyCalculation()\n * })\n * await t.groupAsync('async measurement', async () => {\n * await heavyAsyncCalculation()\n * })\n * }\n * ```\n *\n * @param {string} message\n * @param {function():Promise} f\n * @return {Promise} Returns a promise that resolves the measured duration to apply f\n */\nexport const measureTimeAsync = async (message, f) => {\n let duration\n const start = performance.now()\n try {\n await f()\n } finally {\n duration = performance.now() - start\n log.print(log.PURPLE, message, log.GREY, ` ${time.humanizeDuration(duration)}`)\n }\n return duration\n}\n\n/**\n * @template T\n * @param {Array} as\n * @param {Array} bs\n * @param {string} [m]\n * @return {boolean}\n */\nexport const compareArrays = (as, bs, m = 'Arrays match') => {\n if (as.length !== bs.length) {\n fail(m)\n }\n for (let i = 0; i < as.length; i++) {\n if (as[i] !== bs[i]) {\n fail(m)\n }\n }\n return true\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @param {string} [m]\n * @throws {TestError} Throws if tests fails\n */\nexport const compareStrings = (a, b, m = 'Strings match') => {\n if (a !== b) {\n const diff = simpleDiff(a, b)\n log.print(log.GREY, a.slice(0, diff.index), log.RED, a.slice(diff.index, diff.remove), log.GREEN, diff.insert, log.GREY, a.slice(diff.index + diff.remove))\n fail(m)\n }\n}\n\n/**\n * @template K,V\n * @param {Object} a\n * @param {Object} b\n * @param {string} [m]\n * @throws {TestError} Throws if test fails\n */\nexport const compareObjects = (a, b, m = 'Objects match') => { object.equalFlat(a, b) || fail(m) }\n\n/**\n * @param {any} constructor\n * @param {any} a\n * @param {any} b\n * @param {string} path\n * @throws {TestError}\n */\nconst compareValues = (constructor, a, b, path) => {\n if (a !== b) {\n fail(`Values ${json.stringify(a)} and ${json.stringify(b)} don't match (${path})`)\n }\n return true\n}\n\n/**\n * @param {string?} message\n * @param {string} reason\n * @param {string} path\n * @throws {TestError}\n */\nconst _failMessage = (message, reason, path) => fail(\n message === null\n ? `${reason} ${path}`\n : `${message} (${reason}) ${path}`\n)\n\n/**\n * @param {any} a\n * @param {any} b\n * @param {string} path\n * @param {string?} message\n * @param {function(any,any,any,string,any):boolean} customCompare\n */\nconst _compare = (a, b, path, message, customCompare) => {\n // we don't use assert here because we want to test all branches (istanbul errors if one branch is not tested)\n if (a == null || b == null) {\n return compareValues(null, a, b, path)\n }\n if (a.constructor !== b.constructor) {\n _failMessage(message, 'Constructors don\\'t match', path)\n }\n let success = true\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n _failMessage(message, 'ArrayBuffer lengths match', path)\n }\n for (let i = 0; success && i < a.length; i++) {\n success = success && a[i] === b[i]\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n _failMessage(message, 'Sets have different number of attributes', path)\n }\n // @ts-ignore\n a.forEach(value => {\n if (!b.has(value)) {\n _failMessage(message, `b.${path} does have ${value}`, path)\n }\n })\n break\n }\n case Map: {\n if (a.size !== b.size) {\n _failMessage(message, 'Maps have different number of attributes', path)\n }\n // @ts-ignore\n a.forEach((value, key) => {\n if (!b.has(key)) {\n _failMessage(message, `Property ${path}[\"${key}\"] does not exist on second argument`, path)\n }\n _compare(value, b.get(key), `${path}[\"${key}\"]`, message, customCompare)\n })\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n _failMessage(message, 'Objects have a different number of attributes', path)\n }\n object.forEach(a, (value, key) => {\n if (!object.hasProperty(b, key)) {\n _failMessage(message, `Property ${path} does not exist on second argument`, path)\n }\n _compare(value, b[key], `${path}[\"${key}\"]`, message, customCompare)\n })\n break\n case Array:\n if (a.length !== b.length) {\n _failMessage(message, 'Arrays have a different number of attributes', path)\n }\n // @ts-ignore\n a.forEach((value, i) => _compare(value, b[i], `${path}[${i}]`, message, customCompare))\n break\n /* istanbul ignore next */\n default:\n if (!customCompare(a.constructor, a, b, path, compareValues)) {\n _failMessage(message, `Values ${json.stringify(a)} and ${json.stringify(b)} don't match`, path)\n }\n }\n assert(success, message)\n return true\n}\n\n/**\n * @template T\n * @param {T} a\n * @param {T} b\n * @param {string?} [message]\n * @param {function(any,T,T,string,any):boolean} [customCompare]\n */\nexport const compare = (a, b, message = null, customCompare = compareValues) => _compare(a, b, 'obj', message, customCompare)\n\n/* istanbul ignore next */\n/**\n * @param {boolean} condition\n * @param {string?} [message]\n * @throws {TestError}\n */\nexport const assert = (condition, message = null) => condition || fail(`Assertion failed${message !== null ? `: ${message}` : ''}`)\n\n/**\n * @param {function():void} f\n * @throws {TestError}\n */\nexport const fails = f => {\n let err = null\n try {\n f()\n } catch (_err) {\n err = _err\n log.print(log.GREEN, '⇖ This Error was expected')\n }\n /* istanbul ignore if */\n if (err === null) {\n fail('Expected this to fail')\n }\n}\n\n/**\n * @param {Object>>} tests\n */\nexport const runTests = async tests => {\n const numberOfTests = object.map(tests, mod => object.map(mod, f => /* istanbul ignore next */ f ? 1 : 0).reduce(math.add, 0)).reduce(math.add, 0)\n let successfulTests = 0\n let testnumber = 0\n const start = performance.now()\n for (const modName in tests) {\n const mod = tests[modName]\n for (const fname in mod) {\n const f = mod[fname]\n /* istanbul ignore else */\n if (f) {\n const repeatEachTest = 1\n let success = true\n for (let i = 0; success && i < repeatEachTest; i++) {\n success = await run(modName, fname, f, testnumber, numberOfTests)\n }\n testnumber++\n /* istanbul ignore else */\n if (success) {\n successfulTests++\n }\n }\n }\n }\n const end = performance.now()\n log.print('')\n const success = successfulTests === numberOfTests\n /* istanbul ignore next */\n if (success) {\n /* istanbul ignore next */\n log.print(log.GREEN, log.BOLD, 'All tests successful!', log.GREY, log.UNBOLD, ` in ${time.humanizeDuration(end - start)}`)\n /* istanbul ignore next */\n log.printImgBase64(nyanCatImage, 50)\n } else {\n const failedTests = numberOfTests - successfulTests\n log.print(log.RED, log.BOLD, `> ${failedTests} test${failedTests > 1 ? 's' : ''} failed`)\n }\n return success\n}\n\nclass TestError extends Error {}\n\n/**\n * @param {string} reason\n * @throws {TestError}\n */\nexport const fail = reason => {\n log.print(log.RED, log.BOLD, 'X ', log.UNBOLD, reason)\n throw new TestError('Test Failed')\n}\n\nclass SkipError extends Error {}\n\n/**\n * @param {boolean} cond If true, this tests will be skipped\n * @throws {SkipError}\n */\nexport const skip = (cond = true) => {\n if (cond) {\n throw new SkipError('skipping..')\n }\n}\n\n// eslint-disable-next-line\nconst nyanCatImage = 'R0lGODlhjABMAPcAAMiSE0xMTEzMzUKJzjQ0NFsoKPc7//FM/9mH/z9x0HIiIoKCgmBHN+frGSkZLdDQ0LCwsDk71g0KCUzDdrQQEOFz/8yYdelmBdTiHFxcXDU2erR/mLrTHCgoKK5szBQUFNgSCTk6ymfpCB9VZS2Bl+cGBt2N8kWm0uDcG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VqGG5GtRMPnnll1eiOTjUXK7G5+CInrnmoXf+eeqWf8655adPzroanqN+eeyUm7665TNMsQlnUCgh/PDCu1JFD/6ZqPzyvhJgEOxHRH8EGaITIf0R7oh+/RGiV3I99ZdbL332l2/f/fVEVH/962qYf7k76ItOxhEzuABkBhbkr//++aeQyf0ADKDzDBKGArbhgG3wQwEL6AcEtmGBBnQgBMPgQAUusIEInKADHwjBCkIQgwfUoAQ7iEALMtAPa5iEfbTQIT0YgTxGKJAMvfSFDhDoHgT4AgE6hBA/+GEQ2AgiNvy84EMfekGI2BhEEf1QAyQuEYhCJGIRjyhEJRaxiUJ8IhKlaEQkWtGHWAyiFqO4RC/UIIUl2s4H9PAlw+lrBPHQQ4UCtDU7vJEgbsijHvfIxz768Y+ADKQgB0lIQGJjDdvZjkBstJ3EHCSRRLLRHQnCiEoSJAKVrOQcCCKGTDIiApTMpBgIMgdPbnIgncxkQTw5yoGUMpOnFEgqLRnKSrZSIK/U5Ag+kLjEDaSXCQGmQHzJpWIasyV3OaYyl8nMZi7nLsl0ZkagKc1qWvOa2JxLNLPJzW6+ZZvevAhdwrkStJCTI2gZ5zknos51shOc7oynPOdJz3ra857hDAgAOw=='\n","/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set} set\n * @return {Array}\n */\nexport const toArray = set => Array.from(set)\n","/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n *\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n","\nimport { Observable } from 'lib0/observable.js'\n\nimport {\n Doc // eslint-disable-line\n} from '../internals.js'\n\n/**\n * This is an abstract interface that all Connectors should implement to keep them interchangeable.\n *\n * @note This interface is experimental and it is not advised to actually inherit this class.\n * It just serves as typing information.\n *\n * @extends {Observable}\n */\nexport class AbstractConnector extends Observable {\n /**\n * @param {Doc} ydoc\n * @param {any} awareness\n */\n constructor (ydoc, awareness) {\n super()\n this.doc = ydoc\n this.awareness = awareness\n }\n}\n","\nimport {\n findIndexSS,\n getState,\n splitItem,\n iterateStructs,\n AbstractUpdateDecoder, AbstractDSDecoder, AbstractDSEncoder, DSDecoderV2, DSEncoderV2, Item, GC, StructStore, Transaction, ID // eslint-disable-line\n} from '../internals.js'\n\nimport * as array from 'lib0/array.js'\nimport * as math from 'lib0/math.js'\nimport * as map from 'lib0/map.js'\nimport * as encoding from 'lib0/encoding.js'\nimport * as decoding from 'lib0/decoding.js'\n\nexport class DeleteItem {\n /**\n * @param {number} clock\n * @param {number} len\n */\n constructor (clock, len) {\n /**\n * @type {number}\n */\n this.clock = clock\n /**\n * @type {number}\n */\n this.len = len\n }\n}\n\n/**\n * We no longer maintain a DeleteStore. DeleteSet is a temporary object that is created when needed.\n * - When created in a transaction, it must only be accessed after sorting, and merging\n * - This DeleteSet is send to other clients\n * - We do not create a DeleteSet when we send a sync message. The DeleteSet message is created directly from StructStore\n * - We read a DeleteSet as part of a sync/update message. In this case the DeleteSet is already sorted and merged.\n */\nexport class DeleteSet {\n constructor () {\n /**\n * @type {Map>}\n */\n this.clients = new Map()\n }\n}\n\n/**\n * Iterate over all structs that the DeleteSet gc's.\n *\n * @param {Transaction} transaction\n * @param {DeleteSet} ds\n * @param {function(GC|Item):void} f\n *\n * @function\n */\nexport const iterateDeletedStructs = (transaction, ds, f) =>\n ds.clients.forEach((deletes, clientid) => {\n const structs = /** @type {Array} */ (transaction.doc.store.clients.get(clientid))\n for (let i = 0; i < deletes.length; i++) {\n const del = deletes[i]\n iterateStructs(transaction, structs, del.clock, del.len, f)\n }\n })\n\n/**\n * @param {Array} dis\n * @param {number} clock\n * @return {number|null}\n *\n * @private\n * @function\n */\nexport const findIndexDS = (dis, clock) => {\n let left = 0\n let right = dis.length - 1\n while (left <= right) {\n const midindex = math.floor((left + right) / 2)\n const mid = dis[midindex]\n const midclock = mid.clock\n if (midclock <= clock) {\n if (clock < midclock + mid.len) {\n return midindex\n }\n left = midindex + 1\n } else {\n right = midindex - 1\n }\n }\n return null\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {ID} id\n * @return {boolean}\n *\n * @private\n * @function\n */\nexport const isDeleted = (ds, id) => {\n const dis = ds.clients.get(id.client)\n return dis !== undefined && findIndexDS(dis, id.clock) !== null\n}\n\n/**\n * @param {DeleteSet} ds\n *\n * @private\n * @function\n */\nexport const sortAndMergeDeleteSet = ds => {\n ds.clients.forEach(dels => {\n dels.sort((a, b) => a.clock - b.clock)\n // merge items without filtering or splicing the array\n // i is the current pointer\n // j refers to the current insert position for the pointed item\n // try to merge dels[i] into dels[j-1] or set dels[j]=dels[i]\n let i, j\n for (i = 1, j = 1; i < dels.length; i++) {\n const left = dels[j - 1]\n const right = dels[i]\n if (left.clock + left.len === right.clock) {\n left.len += right.len\n } else {\n if (j < i) {\n dels[j] = right\n }\n j++\n }\n }\n dels.length = j\n })\n}\n\n/**\n * @param {Array} dss\n * @return {DeleteSet} A fresh DeleteSet\n */\nexport const mergeDeleteSets = dss => {\n const merged = new DeleteSet()\n for (let dssI = 0; dssI < dss.length; dssI++) {\n dss[dssI].clients.forEach((delsLeft, client) => {\n if (!merged.clients.has(client)) {\n // Write all missing keys from current ds and all following.\n // If merged already contains `client` current ds has already been added.\n /**\n * @type {Array}\n */\n const dels = delsLeft.slice()\n for (let i = dssI + 1; i < dss.length; i++) {\n array.appendTo(dels, dss[i].clients.get(client) || [])\n }\n merged.clients.set(client, dels)\n }\n })\n }\n sortAndMergeDeleteSet(merged)\n return merged\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {number} client\n * @param {number} clock\n * @param {number} length\n *\n * @private\n * @function\n */\nexport const addToDeleteSet = (ds, client, clock, length) => {\n map.setIfUndefined(ds.clients, client, () => []).push(new DeleteItem(clock, length))\n}\n\nexport const createDeleteSet = () => new DeleteSet()\n\n/**\n * @param {StructStore} ss\n * @return {DeleteSet} Merged and sorted DeleteSet\n *\n * @private\n * @function\n */\nexport const createDeleteSetFromStructStore = ss => {\n const ds = createDeleteSet()\n ss.clients.forEach((structs, client) => {\n /**\n * @type {Array}\n */\n const dsitems = []\n for (let i = 0; i < structs.length; i++) {\n const struct = structs[i]\n if (struct.deleted) {\n const clock = struct.id.clock\n let len = struct.length\n if (i + 1 < structs.length) {\n for (let next = structs[i + 1]; i + 1 < structs.length && next.id.clock === clock + len && next.deleted; next = structs[++i + 1]) {\n len += next.length\n }\n }\n dsitems.push(new DeleteItem(clock, len))\n }\n }\n if (dsitems.length > 0) {\n ds.clients.set(client, dsitems)\n }\n })\n return ds\n}\n\n/**\n * @param {AbstractDSEncoder} encoder\n * @param {DeleteSet} ds\n *\n * @private\n * @function\n */\nexport const writeDeleteSet = (encoder, ds) => {\n encoding.writeVarUint(encoder.restEncoder, ds.clients.size)\n ds.clients.forEach((dsitems, client) => {\n encoder.resetDsCurVal()\n encoding.writeVarUint(encoder.restEncoder, client)\n const len = dsitems.length\n encoding.writeVarUint(encoder.restEncoder, len)\n for (let i = 0; i < len; i++) {\n const item = dsitems[i]\n encoder.writeDsClock(item.clock)\n encoder.writeDsLen(item.len)\n }\n })\n}\n\n/**\n * @param {AbstractDSDecoder} decoder\n * @return {DeleteSet}\n *\n * @private\n * @function\n */\nexport const readDeleteSet = decoder => {\n const ds = new DeleteSet()\n const numClients = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numClients; i++) {\n decoder.resetDsCurVal()\n const client = decoding.readVarUint(decoder.restDecoder)\n const numberOfDeletes = decoding.readVarUint(decoder.restDecoder)\n if (numberOfDeletes > 0) {\n const dsField = map.setIfUndefined(ds.clients, client, () => [])\n for (let i = 0; i < numberOfDeletes; i++) {\n dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen()))\n }\n }\n }\n return ds\n}\n\n/**\n * @todo YDecoder also contains references to String and other Decoders. Would make sense to exchange YDecoder.toUint8Array for YDecoder.DsToUint8Array()..\n */\n\n/**\n * @param {AbstractDSDecoder} decoder\n * @param {Transaction} transaction\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nexport const readAndApplyDeleteSet = (decoder, transaction, store) => {\n const unappliedDS = new DeleteSet()\n const numClients = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numClients; i++) {\n decoder.resetDsCurVal()\n const client = decoding.readVarUint(decoder.restDecoder)\n const numberOfDeletes = decoding.readVarUint(decoder.restDecoder)\n const structs = store.clients.get(client) || []\n const state = getState(store, client)\n for (let i = 0; i < numberOfDeletes; i++) {\n const clock = decoder.readDsClock()\n const clockEnd = clock + decoder.readDsLen()\n if (clock < state) {\n if (state < clockEnd) {\n addToDeleteSet(unappliedDS, client, state, clockEnd - state)\n }\n let index = findIndexSS(structs, clock)\n /**\n * We can ignore the case of GC and Delete structs, because we are going to skip them\n * @type {Item}\n */\n // @ts-ignore\n let struct = structs[index]\n // split the first item if necessary\n if (!struct.deleted && struct.id.clock < clock) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock))\n index++ // increase we now want to use the next struct\n }\n while (index < structs.length) {\n // @ts-ignore\n struct = structs[index++]\n if (struct.id.clock < clockEnd) {\n if (!struct.deleted) {\n if (clockEnd < struct.id.clock + struct.length) {\n structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock))\n }\n struct.delete(transaction)\n }\n } else {\n break\n }\n }\n } else {\n addToDeleteSet(unappliedDS, client, clock, clockEnd - clock)\n }\n }\n }\n if (unappliedDS.clients.size > 0) {\n // TODO: no need for encoding+decoding ds anymore\n const unappliedDSEncoder = new DSEncoderV2()\n writeDeleteSet(unappliedDSEncoder, unappliedDS)\n store.pendingDeleteReaders.push(new DSDecoderV2(decoding.createDecoder((unappliedDSEncoder.toUint8Array()))))\n }\n}\n","/**\n * @module Y\n */\n\nimport {\n StructStore,\n AbstractType,\n YArray,\n YText,\n YMap,\n YXmlFragment,\n transact,\n ContentDoc, Item, Transaction, YEvent // eslint-disable-line\n} from '../internals.js'\n\nimport { Observable } from 'lib0/observable.js'\nimport * as random from 'lib0/random.js'\nimport * as map from 'lib0/map.js'\nimport * as array from 'lib0/array.js'\n\nexport const generateNewClientId = random.uint32\n\n/**\n * @typedef {Object} DocOpts\n * @property {boolean} [DocOpts.gc=true] Disable garbage collection (default: gc=true)\n * @property {function(Item):boolean} [DocOpts.gcFilter] Will be called before an Item is garbage collected. Return false to keep the Item.\n * @property {string} [DocOpts.guid] Define a globally unique identifier for this document\n * @property {any} [DocOpts.meta] Any kind of meta information you want to associate with this document. If this is a subdocument, remote peers will store the meta information as well.\n * @property {boolean} [DocOpts.autoLoad] If a subdocument, automatically load document. If this is a subdocument, remote peers will load the document as well automatically.\n */\n\n/**\n * A Yjs instance handles the state of shared data.\n * @extends Observable\n */\nexport class Doc extends Observable {\n /**\n * @param {DocOpts} [opts] configuration\n */\n constructor ({ guid = random.uuidv4(), gc = true, gcFilter = () => true, meta = null, autoLoad = false } = {}) {\n super()\n this.gc = gc\n this.gcFilter = gcFilter\n this.clientID = generateNewClientId()\n this.guid = guid\n /**\n * @type {Map>}\n */\n this.share = new Map()\n this.store = new StructStore()\n /**\n * @type {Transaction | null}\n */\n this._transaction = null\n /**\n * @type {Array}\n */\n this._transactionCleanups = []\n /**\n * @type {Set}\n */\n this.subdocs = new Set()\n /**\n * If this document is a subdocument - a document integrated into another document - then _item is defined.\n * @type {Item?}\n */\n this._item = null\n this.shouldLoad = autoLoad\n this.autoLoad = autoLoad\n this.meta = meta\n }\n\n /**\n * Notify the parent document that you request to load data into this subdocument (if it is a subdocument).\n *\n * `load()` might be used in the future to request any provider to load the most current data.\n *\n * It is safe to call `load()` multiple times.\n */\n load () {\n const item = this._item\n if (item !== null && !this.shouldLoad) {\n transact(/** @type {any} */ (item.parent).doc, transaction => {\n transaction.subdocsLoaded.add(this)\n }, null, true)\n }\n this.shouldLoad = true\n }\n\n getSubdocs () {\n return this.subdocs\n }\n\n getSubdocGuids () {\n return new Set(Array.from(this.subdocs).map(doc => doc.guid))\n }\n\n /**\n * Changes that happen inside of a transaction are bundled. This means that\n * the observer fires _after_ the transaction is finished and that all changes\n * that happened inside of the transaction are sent as one message to the\n * other peers.\n *\n * @param {function(Transaction):void} f The function that should be executed as a transaction\n * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin\n *\n * @public\n */\n transact (f, origin = null) {\n transact(this, f, origin)\n }\n\n /**\n * Define a shared data type.\n *\n * Multiple calls of `y.get(name, TypeConstructor)` yield the same result\n * and do not overwrite each other. I.e.\n * `y.define(name, Y.Array) === y.define(name, Y.Array)`\n *\n * After this method is called, the type is also available on `y.share.get(name)`.\n *\n * *Best Practices:*\n * Define all types right after the Yjs instance is created and store them in a separate object.\n * Also use the typed methods `getText(name)`, `getArray(name)`, ..\n *\n * @example\n * const y = new Y(..)\n * const appState = {\n * document: y.getText('document')\n * comments: y.getArray('comments')\n * }\n *\n * @param {string} name\n * @param {Function} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ...\n * @return {AbstractType} The created type. Constructed with TypeConstructor\n *\n * @public\n */\n get (name, TypeConstructor = AbstractType) {\n const type = map.setIfUndefined(this.share, name, () => {\n // @ts-ignore\n const t = new TypeConstructor()\n t._integrate(this, null)\n return t\n })\n const Constr = type.constructor\n if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) {\n if (Constr === AbstractType) {\n // @ts-ignore\n const t = new TypeConstructor()\n t._map = type._map\n type._map.forEach(/** @param {Item?} n */ n => {\n for (; n !== null; n = n.left) {\n // @ts-ignore\n n.parent = t\n }\n })\n t._start = type._start\n for (let n = t._start; n !== null; n = n.right) {\n n.parent = t\n }\n t._length = type._length\n this.share.set(name, t)\n t._integrate(this, null)\n return t\n } else {\n throw new Error(`Type with the name ${name} has already been defined with a different constructor`)\n }\n }\n return type\n }\n\n /**\n * @template T\n * @param {string} [name]\n * @return {YArray}\n *\n * @public\n */\n getArray (name = '') {\n // @ts-ignore\n return this.get(name, YArray)\n }\n\n /**\n * @param {string} [name]\n * @return {YText}\n *\n * @public\n */\n getText (name = '') {\n // @ts-ignore\n return this.get(name, YText)\n }\n\n /**\n * @param {string} [name]\n * @return {YMap}\n *\n * @public\n */\n getMap (name = '') {\n // @ts-ignore\n return this.get(name, YMap)\n }\n\n /**\n * @param {string} [name]\n * @return {YXmlFragment}\n *\n * @public\n */\n getXmlFragment (name = '') {\n // @ts-ignore\n return this.get(name, YXmlFragment)\n }\n\n /**\n * Converts the entire document into a js object, recursively traversing each yjs type\n *\n * @return {Object}\n */\n toJSON () {\n /**\n * @type {Object}\n */\n const doc = {}\n\n this.share.forEach((value, key) => {\n doc[key] = value.toJSON()\n })\n\n return doc\n }\n\n /**\n * Emit `destroy` event and unregister all event handlers.\n */\n destroy () {\n array.from(this.subdocs).forEach(subdoc => subdoc.destroy())\n const item = this._item\n if (item !== null) {\n this._item = null\n const content = /** @type {ContentDoc} */ (item.content)\n if (item.deleted) {\n // @ts-ignore\n content.doc = null\n } else {\n content.doc = new Doc({ guid: this.guid, ...content.opts })\n content.doc._item = item\n }\n transact(/** @type {any} */ (item).parent.doc, transaction => {\n if (!item.deleted) {\n transaction.subdocsAdded.add(content.doc)\n }\n transaction.subdocsRemoved.add(this)\n }, null, true)\n }\n this.emit('destroyed', [true])\n super.destroy()\n }\n\n /**\n * @param {string} eventName\n * @param {function(...any):any} f\n */\n on (eventName, f) {\n super.on(eventName, f)\n }\n\n /**\n * @param {string} eventName\n * @param {function} f\n */\n off (eventName, f) {\n super.off(eventName, f)\n }\n}\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* istanbul ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* istanbul ignore next */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* istanbul ignore next */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n","import * as buffer from 'lib0/buffer.js'\nimport * as error from 'lib0/error.js'\nimport * as decoding from 'lib0/decoding.js'\nimport {\n ID, createID\n} from '../internals.js'\n\nexport class AbstractDSDecoder {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n this.restDecoder = decoder\n error.methodUnimplemented()\n }\n\n resetDsCurVal () { }\n\n /**\n * @return {number}\n */\n readDsClock () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {number}\n */\n readDsLen () {\n error.methodUnimplemented()\n }\n}\n\nexport class AbstractUpdateDecoder extends AbstractDSDecoder {\n /**\n * @return {ID}\n */\n readLeftID () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n error.methodUnimplemented()\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n *\n * @return {number}\n */\n readClient () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {string}\n */\n readString () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {boolean} isKey\n */\n readParentInfo () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readTypeRef () {\n error.methodUnimplemented()\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number} len\n */\n readLen () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {any}\n */\n readAny () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n error.methodUnimplemented()\n }\n\n /**\n * Legacy implementation uses JSON parse. We use any-decoding in v2.\n *\n * @return {any}\n */\n readJSON () {\n error.methodUnimplemented()\n }\n\n /**\n * @return {string}\n */\n readKey () {\n error.methodUnimplemented()\n }\n}\n\nexport class DSDecoderV1 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n this.restDecoder = decoder\n }\n\n resetDsCurVal () {\n // nop\n }\n\n /**\n * @return {number}\n */\n readDsClock () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {number}\n */\n readDsLen () {\n return decoding.readVarUint(this.restDecoder)\n }\n}\n\nexport class UpdateDecoderV1 extends DSDecoderV1 {\n /**\n * @return {ID}\n */\n readLeftID () {\n return createID(decoding.readVarUint(this.restDecoder), decoding.readVarUint(this.restDecoder))\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n return createID(decoding.readVarUint(this.restDecoder), decoding.readVarUint(this.restDecoder))\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n */\n readClient () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n return decoding.readUint8(this.restDecoder)\n }\n\n /**\n * @return {string}\n */\n readString () {\n return decoding.readVarString(this.restDecoder)\n }\n\n /**\n * @return {boolean} isKey\n */\n readParentInfo () {\n return decoding.readVarUint(this.restDecoder) === 1\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readTypeRef () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number} len\n */\n readLen () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {any}\n */\n readAny () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n return buffer.copyUint8Array(decoding.readVarUint8Array(this.restDecoder))\n }\n\n /**\n * Legacy implementation uses JSON parse. We use any-decoding in v2.\n *\n * @return {any}\n */\n readJSON () {\n return JSON.parse(decoding.readVarString(this.restDecoder))\n }\n\n /**\n * @return {string}\n */\n readKey () {\n return decoding.readVarString(this.restDecoder)\n }\n}\n\nexport class DSDecoderV2 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n this.dsCurrVal = 0\n this.restDecoder = decoder\n }\n\n resetDsCurVal () {\n this.dsCurrVal = 0\n }\n\n readDsClock () {\n this.dsCurrVal += decoding.readVarUint(this.restDecoder)\n return this.dsCurrVal\n }\n\n readDsLen () {\n const diff = decoding.readVarUint(this.restDecoder) + 1\n this.dsCurrVal += diff\n return diff\n }\n}\n\nexport class UpdateDecoderV2 extends DSDecoderV2 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n super(decoder)\n /**\n * List of cached keys. If the keys[id] does not exist, we read a new key\n * from stringEncoder and push it to keys.\n *\n * @type {Array}\n */\n this.keys = []\n decoding.readUint8(decoder) // read feature flag - currently unused\n this.keyClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.clientDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.leftClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.rightClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.infoDecoder = new decoding.RleDecoder(decoding.readVarUint8Array(decoder), decoding.readUint8)\n this.stringDecoder = new decoding.StringDecoder(decoding.readVarUint8Array(decoder))\n this.parentInfoDecoder = new decoding.RleDecoder(decoding.readVarUint8Array(decoder), decoding.readUint8)\n this.typeRefDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.lenDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder))\n }\n\n /**\n * @return {ID}\n */\n readLeftID () {\n return new ID(this.clientDecoder.read(), this.leftClockDecoder.read())\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n return new ID(this.clientDecoder.read(), this.rightClockDecoder.read())\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n */\n readClient () {\n return this.clientDecoder.read()\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n return /** @type {number} */ (this.infoDecoder.read())\n }\n\n /**\n * @return {string}\n */\n readString () {\n return this.stringDecoder.read()\n }\n\n /**\n * @return {boolean}\n */\n readParentInfo () {\n return this.parentInfoDecoder.read() === 1\n }\n\n /**\n * @return {number} An unsigned 8-bit integer\n */\n readTypeRef () {\n return this.typeRefDecoder.read()\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number}\n */\n readLen () {\n return this.lenDecoder.read()\n }\n\n /**\n * @return {any}\n */\n readAny () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n return decoding.readVarUint8Array(this.restDecoder)\n }\n\n /**\n * This is mainly here for legacy purposes.\n *\n * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.\n *\n * @return {any}\n */\n readJSON () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {string}\n */\n readKey () {\n const keyClock = this.keyClockDecoder.read()\n if (keyClock < this.keys.length) {\n return this.keys[keyClock]\n } else {\n const key = this.stringDecoder.read()\n this.keys.push(key)\n return key\n }\n }\n}\n","\nimport * as error from 'lib0/error.js'\nimport * as encoding from 'lib0/encoding.js'\n\nimport {\n ID // eslint-disable-line\n} from '../internals.js'\n\nexport class AbstractDSEncoder {\n constructor () {\n this.restEncoder = encoding.createEncoder()\n }\n\n /**\n * @return {Uint8Array}\n */\n toUint8Array () {\n error.methodUnimplemented()\n }\n\n /**\n * Resets the ds value to 0.\n * The v2 encoder uses this information to reset the initial diff value.\n */\n resetDsCurVal () { }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) { }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) { }\n}\n\nexport class AbstractUpdateEncoder extends AbstractDSEncoder {\n /**\n * @return {Uint8Array}\n */\n toUint8Array () {\n error.methodUnimplemented()\n }\n\n /**\n * @param {ID} id\n */\n writeLeftID (id) { }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) { }\n\n /**\n * Use writeClient and writeClock instead of writeID if possible.\n * @param {number} client\n */\n writeClient (client) { }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) { }\n\n /**\n * @param {string} s\n */\n writeString (s) { }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) { }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) { }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) { }\n\n /**\n * @param {any} any\n */\n writeAny (any) { }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) { }\n\n /**\n * @param {any} embed\n */\n writeJSON (embed) { }\n\n /**\n * @param {string} key\n */\n writeKey (key) { }\n}\n\nexport class DSEncoderV1 {\n constructor () {\n this.restEncoder = new encoding.Encoder()\n }\n\n toUint8Array () {\n return encoding.toUint8Array(this.restEncoder)\n }\n\n resetDsCurVal () {\n // nop\n }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) {\n encoding.writeVarUint(this.restEncoder, clock)\n }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) {\n encoding.writeVarUint(this.restEncoder, len)\n }\n}\n\nexport class UpdateEncoderV1 extends DSEncoderV1 {\n /**\n * @param {ID} id\n */\n writeLeftID (id) {\n encoding.writeVarUint(this.restEncoder, id.client)\n encoding.writeVarUint(this.restEncoder, id.clock)\n }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) {\n encoding.writeVarUint(this.restEncoder, id.client)\n encoding.writeVarUint(this.restEncoder, id.clock)\n }\n\n /**\n * Use writeClient and writeClock instead of writeID if possible.\n * @param {number} client\n */\n writeClient (client) {\n encoding.writeVarUint(this.restEncoder, client)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) {\n encoding.writeUint8(this.restEncoder, info)\n }\n\n /**\n * @param {string} s\n */\n writeString (s) {\n encoding.writeVarString(this.restEncoder, s)\n }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) {\n encoding.writeVarUint(this.restEncoder, isYKey ? 1 : 0)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) {\n encoding.writeVarUint(this.restEncoder, info)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) {\n encoding.writeVarUint(this.restEncoder, len)\n }\n\n /**\n * @param {any} any\n */\n writeAny (any) {\n encoding.writeAny(this.restEncoder, any)\n }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) {\n encoding.writeVarUint8Array(this.restEncoder, buf)\n }\n\n /**\n * @param {any} embed\n */\n writeJSON (embed) {\n encoding.writeVarString(this.restEncoder, JSON.stringify(embed))\n }\n\n /**\n * @param {string} key\n */\n writeKey (key) {\n encoding.writeVarString(this.restEncoder, key)\n }\n}\n\nexport class DSEncoderV2 {\n constructor () {\n this.restEncoder = new encoding.Encoder() // encodes all the rest / non-optimized\n this.dsCurrVal = 0\n }\n\n toUint8Array () {\n return encoding.toUint8Array(this.restEncoder)\n }\n\n resetDsCurVal () {\n this.dsCurrVal = 0\n }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) {\n const diff = clock - this.dsCurrVal\n this.dsCurrVal = clock\n encoding.writeVarUint(this.restEncoder, diff)\n }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) {\n if (len === 0) {\n error.unexpectedCase()\n }\n encoding.writeVarUint(this.restEncoder, len - 1)\n this.dsCurrVal += len\n }\n}\n\nexport class UpdateEncoderV2 extends DSEncoderV2 {\n constructor () {\n super()\n /**\n * @type {Map}\n */\n this.keyMap = new Map()\n /**\n * Refers to the next uniqe key-identifier to me used.\n * See writeKey method for more information.\n *\n * @type {number}\n */\n this.keyClock = 0\n this.keyClockEncoder = new encoding.IntDiffOptRleEncoder()\n this.clientEncoder = new encoding.UintOptRleEncoder()\n this.leftClockEncoder = new encoding.IntDiffOptRleEncoder()\n this.rightClockEncoder = new encoding.IntDiffOptRleEncoder()\n this.infoEncoder = new encoding.RleEncoder(encoding.writeUint8)\n this.stringEncoder = new encoding.StringEncoder()\n this.parentInfoEncoder = new encoding.RleEncoder(encoding.writeUint8)\n this.typeRefEncoder = new encoding.UintOptRleEncoder()\n this.lenEncoder = new encoding.UintOptRleEncoder()\n }\n\n toUint8Array () {\n const encoder = encoding.createEncoder()\n encoding.writeUint8(encoder, 0) // this is a feature flag that we might use in the future\n encoding.writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.clientEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, encoding.toUint8Array(this.infoEncoder))\n encoding.writeVarUint8Array(encoder, this.stringEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, encoding.toUint8Array(this.parentInfoEncoder))\n encoding.writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.lenEncoder.toUint8Array())\n // @note The rest encoder is appended! (note the missing var)\n encoding.writeUint8Array(encoder, encoding.toUint8Array(this.restEncoder))\n return encoding.toUint8Array(encoder)\n }\n\n /**\n * @param {ID} id\n */\n writeLeftID (id) {\n this.clientEncoder.write(id.client)\n this.leftClockEncoder.write(id.clock)\n }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) {\n this.clientEncoder.write(id.client)\n this.rightClockEncoder.write(id.clock)\n }\n\n /**\n * @param {number} client\n */\n writeClient (client) {\n this.clientEncoder.write(client)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) {\n this.infoEncoder.write(info)\n }\n\n /**\n * @param {string} s\n */\n writeString (s) {\n this.stringEncoder.write(s)\n }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) {\n this.parentInfoEncoder.write(isYKey ? 1 : 0)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) {\n this.typeRefEncoder.write(info)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) {\n this.lenEncoder.write(len)\n }\n\n /**\n * @param {any} any\n */\n writeAny (any) {\n encoding.writeAny(this.restEncoder, any)\n }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) {\n encoding.writeVarUint8Array(this.restEncoder, buf)\n }\n\n /**\n * This is mainly here for legacy purposes.\n *\n * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.\n *\n * @param {any} embed\n */\n writeJSON (embed) {\n encoding.writeAny(this.restEncoder, embed)\n }\n\n /**\n * Property keys are often reused. For example, in y-prosemirror the key `bold` might\n * occur very often. For a 3d application, the key `position` might occur very often.\n *\n * We cache these keys in a Map and refer to them via a unique number.\n *\n * @param {string} key\n */\n writeKey (key) {\n const clock = this.keyMap.get(key)\n if (clock === undefined) {\n this.keyClockEncoder.write(this.keyClock++)\n this.stringEncoder.write(key)\n } else {\n this.keyClockEncoder.write(this.keyClock++)\n }\n }\n}\n","\n/**\n * @module encoding\n */\n/*\n * We use the first five bits in the info flag for determining the type of the struct.\n *\n * 0: GC\n * 1: Item with Deleted content\n * 2: Item with JSON content\n * 3: Item with Binary content\n * 4: Item with String content\n * 5: Item with Embed content (for richtext content)\n * 6: Item with Format content (a formatting marker for richtext content)\n * 7: Item with Type\n */\n\nimport {\n findIndexSS,\n getState,\n createID,\n getStateVector,\n readAndApplyDeleteSet,\n writeDeleteSet,\n createDeleteSetFromStructStore,\n transact,\n readItemContent,\n UpdateDecoderV1,\n UpdateDecoderV2,\n UpdateEncoderV1,\n UpdateEncoderV2,\n DSDecoderV2,\n DSEncoderV2,\n DSDecoderV1,\n DSEncoderV1,\n AbstractDSEncoder, AbstractDSDecoder, AbstractUpdateEncoder, AbstractUpdateDecoder, AbstractContent, Doc, Transaction, GC, Item, StructStore, ID // eslint-disable-line\n} from '../internals.js'\n\nimport * as encoding from 'lib0/encoding.js'\nimport * as decoding from 'lib0/decoding.js'\nimport * as binary from 'lib0/binary.js'\nimport * as map from 'lib0/map.js'\n\nexport let DefaultDSEncoder = DSEncoderV1\nexport let DefaultDSDecoder = DSDecoderV1\nexport let DefaultUpdateEncoder = UpdateEncoderV1\nexport let DefaultUpdateDecoder = UpdateDecoderV1\n\nexport const useV1Encoding = () => {\n DefaultDSEncoder = DSEncoderV1\n DefaultDSDecoder = DSDecoderV1\n DefaultUpdateEncoder = UpdateEncoderV1\n DefaultUpdateDecoder = UpdateDecoderV1\n}\n\nexport const useV2Encoding = () => {\n DefaultDSEncoder = DSEncoderV2\n DefaultDSDecoder = DSDecoderV2\n DefaultUpdateEncoder = UpdateEncoderV2\n DefaultUpdateDecoder = UpdateDecoderV2\n}\n\n/**\n * @param {AbstractUpdateEncoder} encoder\n * @param {Array} structs All structs by `client`\n * @param {number} client\n * @param {number} clock write structs starting with `ID(client,clock)`\n *\n * @function\n */\nconst writeStructs = (encoder, structs, client, clock) => {\n // write first id\n const startNewStructs = findIndexSS(structs, clock)\n // write # encoded structs\n encoding.writeVarUint(encoder.restEncoder, structs.length - startNewStructs)\n encoder.writeClient(client)\n encoding.writeVarUint(encoder.restEncoder, clock)\n const firstStruct = structs[startNewStructs]\n // write first struct with an offset\n firstStruct.write(encoder, clock - firstStruct.id.clock)\n for (let i = startNewStructs + 1; i < structs.length; i++) {\n structs[i].write(encoder, 0)\n }\n}\n\n/**\n * @param {AbstractUpdateEncoder} encoder\n * @param {StructStore} store\n * @param {Map} _sm\n *\n * @private\n * @function\n */\nexport const writeClientsStructs = (encoder, store, _sm) => {\n // we filter all valid _sm entries into sm\n const sm = new Map()\n _sm.forEach((clock, client) => {\n // only write if new structs are available\n if (getState(store, client) > clock) {\n sm.set(client, clock)\n }\n })\n getStateVector(store).forEach((clock, client) => {\n if (!_sm.has(client)) {\n sm.set(client, 0)\n }\n })\n // write # states that were updated\n encoding.writeVarUint(encoder.restEncoder, sm.size)\n // Write items with higher client ids first\n // This heavily improves the conflict algorithm.\n Array.from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {\n // @ts-ignore\n writeStructs(encoder, store.clients.get(client), client, clock)\n })\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder The decoder object to read data from.\n * @param {Map>} clientRefs\n * @param {Doc} doc\n * @return {Map>}\n *\n * @private\n * @function\n */\nexport const readClientsStructRefs = (decoder, clientRefs, doc) => {\n const numOfStateUpdates = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numOfStateUpdates; i++) {\n const numberOfStructs = decoding.readVarUint(decoder.restDecoder)\n /**\n * @type {Array}\n */\n const refs = new Array(numberOfStructs)\n const client = decoder.readClient()\n let clock = decoding.readVarUint(decoder.restDecoder)\n // const start = performance.now()\n clientRefs.set(client, refs)\n for (let i = 0; i < numberOfStructs; i++) {\n const info = decoder.readInfo()\n if ((binary.BITS5 & info) !== 0) {\n /**\n * The optimized implementation doesn't use any variables because inlining variables is faster.\n * Below a non-optimized version is shown that implements the basic algorithm with\n * a few comments\n */\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const struct = new Item(\n createID(client, clock),\n null, // leftd\n (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null, // origin\n null, // right\n (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null, // right origin\n cantCopyParentInfo ? (decoder.readParentInfo() ? doc.get(decoder.readString()) : decoder.readLeftID()) : null, // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n )\n /* A non-optimized implementation of the above algorithm:\n\n // The item that was originally to the left of this item.\n const origin = (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null\n // The item that was originally to the right of this item.\n const rightOrigin = (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0\n const hasParentYKey = cantCopyParentInfo ? decoder.readParentInfo() : false\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const parentYKey = cantCopyParentInfo && hasParentYKey ? decoder.readString() : null\n\n const struct = new Item(\n createID(client, clock),\n null, // leftd\n origin, // origin\n null, // right\n rightOrigin, // right origin\n cantCopyParentInfo && !hasParentYKey ? decoder.readLeftID() : (parentYKey !== null ? doc.get(parentYKey) : null), // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n )\n */\n refs[i] = struct\n clock += struct.length\n } else {\n const len = decoder.readLen()\n refs[i] = new GC(createID(client, clock), len)\n clock += len\n }\n }\n // console.log('time to read: ', performance.now() - start) // @todo remove\n }\n return clientRefs\n}\n\n/**\n * Resume computing structs generated by struct readers.\n *\n * While there is something to do, we integrate structs in this order\n * 1. top element on stack, if stack is not empty\n * 2. next element from current struct reader (if empty, use next struct reader)\n *\n * If struct causally depends on another struct (ref.missing), we put next reader of\n * `ref.id.client` on top of stack.\n *\n * At some point we find a struct that has no causal dependencies,\n * then we start emptying the stack.\n *\n * It is not possible to have circles: i.e. struct1 (from client1) depends on struct2 (from client2)\n * depends on struct3 (from client1). Therefore the max stack size is eqaul to `structReaders.length`.\n *\n * This method is implemented in a way so that we can resume computation if this update\n * causally depends on another update.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nconst resumeStructIntegration = (transaction, store) => {\n const stack = store.pendingStack // @todo don't forget to append stackhead at the end\n const clientsStructRefs = store.pendingClientsStructRefs\n // sort them so that we take the higher id first, in case of conflicts the lower id will probably not conflict with the id from the higher user.\n const clientsStructRefsIds = Array.from(clientsStructRefs.keys()).sort((a, b) => a - b)\n if (clientsStructRefsIds.length === 0) {\n return\n }\n const getNextStructTarget = () => {\n let nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]))\n while (nextStructsTarget.refs.length === nextStructsTarget.i) {\n clientsStructRefsIds.pop()\n if (clientsStructRefsIds.length > 0) {\n nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]))\n } else {\n store.pendingClientsStructRefs.clear()\n return null\n }\n }\n return nextStructsTarget\n }\n let curStructsTarget = getNextStructTarget()\n if (curStructsTarget === null && stack.length === 0) {\n return\n }\n /**\n * @type {GC|Item}\n */\n let stackHead = stack.length > 0\n ? /** @type {GC|Item} */ (stack.pop())\n : /** @type {any} */ (curStructsTarget).refs[/** @type {any} */ (curStructsTarget).i++]\n // caching the state because it is used very often\n const state = new Map()\n // iterate over all struct readers until we are done\n while (true) {\n const localClock = map.setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client))\n const offset = stackHead.id.clock < localClock ? localClock - stackHead.id.clock : 0\n if (stackHead.id.clock + offset !== localClock) {\n // A previous message from this client is missing\n // check if there is a pending structRef with a smaller clock and switch them\n /**\n * @type {{ refs: Array, i: number }}\n */\n const structRefs = clientsStructRefs.get(stackHead.id.client) || { refs: [], i: 0 }\n if (structRefs.refs.length !== structRefs.i) {\n const r = structRefs.refs[structRefs.i]\n if (r.id.clock < stackHead.id.clock) {\n // put ref with smaller clock on stack instead and continue\n structRefs.refs[structRefs.i] = stackHead\n stackHead = r\n // sort the set because this approach might bring the list out of order\n structRefs.refs = structRefs.refs.slice(structRefs.i).sort((r1, r2) => r1.id.clock - r2.id.clock)\n structRefs.i = 0\n continue\n }\n }\n // wait until missing struct is available\n stack.push(stackHead)\n return\n }\n const missing = stackHead.getMissing(transaction, store)\n if (missing === null) {\n if (offset === 0 || offset < stackHead.length) {\n stackHead.integrate(transaction, offset)\n state.set(stackHead.id.client, stackHead.id.clock + stackHead.length)\n }\n // iterate to next stackHead\n if (stack.length > 0) {\n stackHead = /** @type {GC|Item} */ (stack.pop())\n } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) {\n stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++])\n } else {\n curStructsTarget = getNextStructTarget()\n if (curStructsTarget === null) {\n // we are done!\n break\n } else {\n stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++])\n }\n }\n } else {\n // get the struct reader that has the missing struct\n /**\n * @type {{ refs: Array, i: number }}\n */\n const structRefs = clientsStructRefs.get(missing) || { refs: [], i: 0 }\n if (structRefs.refs.length === structRefs.i) {\n // This update message causally depends on another update message.\n stack.push(stackHead)\n return\n }\n stack.push(stackHead)\n stackHead = structRefs.refs[structRefs.i++]\n }\n }\n store.pendingClientsStructRefs.clear()\n}\n\n/**\n * @param {Transaction} transaction\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nexport const tryResumePendingDeleteReaders = (transaction, store) => {\n const pendingReaders = store.pendingDeleteReaders\n store.pendingDeleteReaders = []\n for (let i = 0; i < pendingReaders.length; i++) {\n readAndApplyDeleteSet(pendingReaders[i], transaction, store)\n }\n}\n\n/**\n * @param {AbstractUpdateEncoder} encoder\n * @param {Transaction} transaction\n *\n * @private\n * @function\n */\nexport const writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState)\n\n/**\n * @param {StructStore} store\n * @param {Map>} clientsStructsRefs\n *\n * @private\n * @function\n */\nconst mergeReadStructsIntoPendingReads = (store, clientsStructsRefs) => {\n const pendingClientsStructRefs = store.pendingClientsStructRefs\n clientsStructsRefs.forEach((structRefs, client) => {\n const pendingStructRefs = pendingClientsStructRefs.get(client)\n if (pendingStructRefs === undefined) {\n pendingClientsStructRefs.set(client, { refs: structRefs, i: 0 })\n } else {\n // merge into existing structRefs\n const merged = pendingStructRefs.i > 0 ? pendingStructRefs.refs.slice(pendingStructRefs.i) : pendingStructRefs.refs\n for (let i = 0; i < structRefs.length; i++) {\n merged.push(structRefs[i])\n }\n pendingStructRefs.i = 0\n pendingStructRefs.refs = merged.sort((r1, r2) => r1.id.clock - r2.id.clock)\n }\n })\n}\n\n/**\n * @param {Map,i:number}>} pendingClientsStructRefs\n */\nconst cleanupPendingStructs = pendingClientsStructRefs => {\n // cleanup pendingClientsStructs if not fully finished\n pendingClientsStructRefs.forEach((refs, client) => {\n if (refs.i === refs.refs.length) {\n pendingClientsStructRefs.delete(client)\n } else {\n refs.refs.splice(0, refs.i)\n refs.i = 0\n }\n })\n}\n\n/**\n * Read the next Item in a Decoder and fill this Item with the read data.\n *\n * This is called when data is received from a remote peer.\n *\n * @param {AbstractUpdateDecoder} decoder The decoder object to read data from.\n * @param {Transaction} transaction\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nexport const readStructs = (decoder, transaction, store) => {\n const clientsStructRefs = new Map()\n // let start = performance.now()\n readClientsStructRefs(decoder, clientsStructRefs, transaction.doc)\n // console.log('time to read structs: ', performance.now() - start) // @todo remove\n // start = performance.now()\n mergeReadStructsIntoPendingReads(store, clientsStructRefs)\n // console.log('time to merge: ', performance.now() - start) // @todo remove\n // start = performance.now()\n resumeStructIntegration(transaction, store)\n // console.log('time to integrate: ', performance.now() - start) // @todo remove\n // start = performance.now()\n cleanupPendingStructs(store.pendingClientsStructRefs)\n // console.log('time to cleanup: ', performance.now() - start) // @todo remove\n // start = performance.now()\n tryResumePendingDeleteReaders(transaction, store)\n // console.log('time to resume delete readers: ', performance.now() - start) // @todo remove\n // start = performance.now()\n}\n\n/**\n * Read and apply a document update.\n *\n * This function has the same effect as `applyUpdate` but accepts an decoder.\n *\n * @param {decoding.Decoder} decoder\n * @param {Doc} ydoc\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n * @param {AbstractUpdateDecoder} [structDecoder]\n *\n * @function\n */\nexport const readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) =>\n transact(ydoc, transaction => {\n readStructs(structDecoder, transaction, ydoc.store)\n readAndApplyDeleteSet(structDecoder, transaction, ydoc.store)\n }, transactionOrigin, false)\n\n/**\n * Read and apply a document update.\n *\n * This function has the same effect as `applyUpdate` but accepts an decoder.\n *\n * @param {decoding.Decoder} decoder\n * @param {Doc} ydoc\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n *\n * @function\n */\nexport const readUpdate = (decoder, ydoc, transactionOrigin) => readUpdateV2(decoder, ydoc, transactionOrigin, new DefaultUpdateDecoder(decoder))\n\n/**\n * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.\n *\n * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.\n *\n * @param {Doc} ydoc\n * @param {Uint8Array} update\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder]\n *\n * @function\n */\nexport const applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => {\n const decoder = decoding.createDecoder(update)\n readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder))\n}\n\n/**\n * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.\n *\n * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.\n *\n * @param {Doc} ydoc\n * @param {Uint8Array} update\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n *\n * @function\n */\nexport const applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, DefaultUpdateDecoder)\n\n/**\n * Write all the document as a single update message. If you specify the state of the remote client (`targetStateVector`) it will\n * only write the operations that are missing.\n *\n * @param {AbstractUpdateEncoder} encoder\n * @param {Doc} doc\n * @param {Map} [targetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n *\n * @function\n */\nexport const writeStateAsUpdate = (encoder, doc, targetStateVector = new Map()) => {\n writeClientsStructs(encoder, doc.store, targetStateVector)\n writeDeleteSet(encoder, createDeleteSetFromStructStore(doc.store))\n}\n\n/**\n * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will\n * only write the operations that are missing.\n *\n * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder\n *\n * @param {Doc} doc\n * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n * @param {AbstractUpdateEncoder} [encoder]\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateAsUpdateV2 = (doc, encodedTargetStateVector, encoder = new UpdateEncoderV2()) => {\n const targetStateVector = encodedTargetStateVector == null ? new Map() : decodeStateVector(encodedTargetStateVector)\n writeStateAsUpdate(encoder, doc, targetStateVector)\n return encoder.toUint8Array()\n}\n\n/**\n * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will\n * only write the operations that are missing.\n *\n * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder\n *\n * @param {Doc} doc\n * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateAsUpdate = (doc, encodedTargetStateVector) => encodeStateAsUpdateV2(doc, encodedTargetStateVector, new DefaultUpdateEncoder())\n\n/**\n * Read state vector from Decoder and return as Map\n *\n * @param {AbstractDSDecoder} decoder\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nexport const readStateVector = decoder => {\n const ss = new Map()\n const ssLength = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < ssLength; i++) {\n const client = decoding.readVarUint(decoder.restDecoder)\n const clock = decoding.readVarUint(decoder.restDecoder)\n ss.set(client, clock)\n }\n return ss\n}\n\n/**\n * Read decodedState and return State as Map.\n *\n * @param {Uint8Array} decodedState\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nexport const decodeStateVectorV2 = decodedState => readStateVector(new DSDecoderV2(decoding.createDecoder(decodedState)))\n\n/**\n * Read decodedState and return State as Map.\n *\n * @param {Uint8Array} decodedState\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nexport const decodeStateVector = decodedState => readStateVector(new DefaultDSDecoder(decoding.createDecoder(decodedState)))\n\n/**\n * @param {AbstractDSEncoder} encoder\n * @param {Map} sv\n * @function\n */\nexport const writeStateVector = (encoder, sv) => {\n encoding.writeVarUint(encoder.restEncoder, sv.size)\n sv.forEach((clock, client) => {\n encoding.writeVarUint(encoder.restEncoder, client) // @todo use a special client decoder that is based on mapping\n encoding.writeVarUint(encoder.restEncoder, clock)\n })\n return encoder\n}\n\n/**\n * @param {AbstractDSEncoder} encoder\n * @param {Doc} doc\n *\n * @function\n */\nexport const writeDocumentStateVector = (encoder, doc) => writeStateVector(encoder, getStateVector(doc.store))\n\n/**\n * Encode State as Uint8Array.\n *\n * @param {Doc} doc\n * @param {AbstractDSEncoder} [encoder]\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateVectorV2 = (doc, encoder = new DSEncoderV2()) => {\n writeDocumentStateVector(encoder, doc)\n return encoder.toUint8Array()\n}\n\n/**\n * Encode State as Uint8Array.\n *\n * @param {Doc} doc\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateVector = doc => encodeStateVectorV2(doc, new DefaultDSEncoder())\n","import * as f from 'lib0/function.js'\n\n/**\n * General event handler implementation.\n *\n * @template ARG0, ARG1\n *\n * @private\n */\nexport class EventHandler {\n constructor () {\n /**\n * @type {Array}\n */\n this.l = []\n }\n}\n\n/**\n * @template ARG0,ARG1\n * @returns {EventHandler}\n *\n * @private\n * @function\n */\nexport const createEventHandler = () => new EventHandler()\n\n/**\n * Adds an event listener that is called when\n * {@link EventHandler#callEventListeners} is called.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {function(ARG0,ARG1):void} f The event handler.\n *\n * @private\n * @function\n */\nexport const addEventHandlerListener = (eventHandler, f) =>\n eventHandler.l.push(f)\n\n/**\n * Removes an event listener.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {function(ARG0,ARG1):void} f The event handler that was added with\n * {@link EventHandler#addEventListener}\n *\n * @private\n * @function\n */\nexport const removeEventHandlerListener = (eventHandler, f) => {\n const l = eventHandler.l\n const len = l.length\n eventHandler.l = l.filter(g => f !== g)\n if (len === eventHandler.l.length) {\n console.error('[yjs] Tried to remove event handler that doesn\\'t exist.')\n }\n}\n\n/**\n * Removes all event listeners.\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n *\n * @private\n * @function\n */\nexport const removeAllEventHandlerListeners = eventHandler => {\n eventHandler.l.length = 0\n}\n\n/**\n * Call all event listeners that were added via\n * {@link EventHandler#addEventListener}.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {ARG0} arg0\n * @param {ARG1} arg1\n *\n * @private\n * @function\n */\nexport const callEventHandlerListeners = (eventHandler, arg0, arg1) =>\n f.callAll(eventHandler.l, [arg0, arg1])\n","\nimport { AbstractType } from '../internals.js' // eslint-disable-line\n\nimport * as decoding from 'lib0/decoding.js'\nimport * as encoding from 'lib0/encoding.js'\nimport * as error from 'lib0/error.js'\n\nexport class ID {\n /**\n * @param {number} client client id\n * @param {number} clock unique per client id, continuous number\n */\n constructor (client, clock) {\n /**\n * Client id\n * @type {number}\n */\n this.client = client\n /**\n * unique per client id, continuous number\n * @type {number}\n */\n this.clock = clock\n }\n}\n\n/**\n * @param {ID | null} a\n * @param {ID | null} b\n * @return {boolean}\n *\n * @function\n */\nexport const compareIDs = (a, b) => a === b || (a !== null && b !== null && a.client === b.client && a.clock === b.clock)\n\n/**\n * @param {number} client\n * @param {number} clock\n *\n * @private\n * @function\n */\nexport const createID = (client, clock) => new ID(client, clock)\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {ID} id\n *\n * @private\n * @function\n */\nexport const writeID = (encoder, id) => {\n encoding.writeVarUint(encoder, id.client)\n encoding.writeVarUint(encoder, id.clock)\n}\n\n/**\n * Read ID.\n * * If first varUint read is 0xFFFFFF a RootID is returned.\n * * Otherwise an ID is returned\n *\n * @param {decoding.Decoder} decoder\n * @return {ID}\n *\n * @private\n * @function\n */\nexport const readID = decoder =>\n createID(decoding.readVarUint(decoder), decoding.readVarUint(decoder))\n\n/**\n * The top types are mapped from y.share.get(keyname) => type.\n * `type` does not store any information about the `keyname`.\n * This function finds the correct `keyname` for `type` and throws otherwise.\n *\n * @param {AbstractType} type\n * @return {string}\n *\n * @private\n * @function\n */\nexport const findRootTypeKey = type => {\n // @ts-ignore _y must be defined, otherwise unexpected case\n for (const [key, value] of type.doc.share.entries()) {\n if (value === type) {\n return key\n }\n }\n throw error.unexpectedCase()\n}\n","\nimport { AbstractType, Item } from '../internals.js' // eslint-disable-line\n\n/**\n * Check if `parent` is a parent of `child`.\n *\n * @param {AbstractType} parent\n * @param {Item|null} child\n * @return {Boolean} Whether `parent` is a parent of `child`.\n *\n * @private\n * @function\n */\nexport const isParentOf = (parent, child) => {\n while (child !== null) {\n if (child.parent === parent) {\n return true\n }\n child = /** @type {AbstractType} */ (child.parent)._item\n }\n return false\n}\n","\nimport {\n AbstractType // eslint-disable-line\n} from '../internals.js'\n\n/**\n * Convenient helper to log type information.\n *\n * Do not use in productive systems as the output can be immense!\n *\n * @param {AbstractType} type\n */\nexport const logType = type => {\n const res = []\n let n = type._start\n while (n) {\n res.push(n)\n n = n.right\n }\n console.log('Children: ', res)\n console.log('Children content: ', res.filter(m => !m.deleted).map(m => m.content))\n}\n","\nimport {\n YArray,\n YMap,\n readDeleteSet,\n writeDeleteSet,\n createDeleteSet,\n DSEncoderV1, DSDecoderV1, ID, DeleteSet, YArrayEvent, Transaction, Doc // eslint-disable-line\n} from '../internals.js'\n\nimport * as decoding from 'lib0/decoding.js'\n\nimport { mergeDeleteSets, isDeleted } from './DeleteSet.js'\n\nexport class PermanentUserData {\n /**\n * @param {Doc} doc\n * @param {YMap} [storeType]\n */\n constructor (doc, storeType = doc.getMap('users')) {\n /**\n * @type {Map}\n */\n const dss = new Map()\n this.yusers = storeType\n this.doc = doc\n /**\n * Maps from clientid to userDescription\n *\n * @type {Map}\n */\n this.clients = new Map()\n this.dss = dss\n /**\n * @param {YMap} user\n * @param {string} userDescription\n */\n const initUser = (user, userDescription) => {\n /**\n * @type {YArray}\n */\n const ds = user.get('ds')\n const ids = user.get('ids')\n const addClientId = /** @param {number} clientid */ clientid => this.clients.set(clientid, userDescription)\n ds.observe(/** @param {YArrayEvent} event */ event => {\n event.changes.added.forEach(item => {\n item.content.getContent().forEach(encodedDs => {\n if (encodedDs instanceof Uint8Array) {\n this.dss.set(userDescription, mergeDeleteSets([this.dss.get(userDescription) || createDeleteSet(), readDeleteSet(new DSDecoderV1(decoding.createDecoder(encodedDs)))]))\n }\n })\n })\n })\n this.dss.set(userDescription, mergeDeleteSets(ds.map(encodedDs => readDeleteSet(new DSDecoderV1(decoding.createDecoder(encodedDs))))))\n ids.observe(/** @param {YArrayEvent} event */ event =>\n event.changes.added.forEach(item => item.content.getContent().forEach(addClientId))\n )\n ids.forEach(addClientId)\n }\n // observe users\n storeType.observe(event => {\n event.keysChanged.forEach(userDescription =>\n initUser(storeType.get(userDescription), userDescription)\n )\n })\n // add intial data\n storeType.forEach(initUser)\n }\n\n /**\n * @param {Doc} doc\n * @param {number} clientid\n * @param {string} userDescription\n * @param {Object} [conf]\n * @param {function(Transaction, DeleteSet):boolean} [conf.filter]\n */\n setUserMapping (doc, clientid, userDescription, { filter = () => true } = {}) {\n const users = this.yusers\n let user = users.get(userDescription)\n if (!user) {\n user = new YMap()\n user.set('ids', new YArray())\n user.set('ds', new YArray())\n users.set(userDescription, user)\n }\n user.get('ids').push([clientid])\n users.observe(event => {\n setTimeout(() => {\n const userOverwrite = users.get(userDescription)\n if (userOverwrite !== user) {\n // user was overwritten, port all data over to the next user object\n // @todo Experiment with Y.Sets here\n user = userOverwrite\n // @todo iterate over old type\n this.clients.forEach((_userDescription, clientid) => {\n if (userDescription === _userDescription) {\n user.get('ids').push([clientid])\n }\n })\n const encoder = new DSEncoderV1()\n const ds = this.dss.get(userDescription)\n if (ds) {\n writeDeleteSet(encoder, ds)\n user.get('ds').push([encoder.toUint8Array()])\n }\n }\n }, 0)\n })\n doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => {\n setTimeout(() => {\n const yds = user.get('ds')\n const ds = transaction.deleteSet\n if (transaction.local && ds.clients.size > 0 && filter(transaction, ds)) {\n const encoder = new DSEncoderV1()\n writeDeleteSet(encoder, ds)\n yds.push([encoder.toUint8Array()])\n }\n })\n })\n }\n\n /**\n * @param {number} clientid\n * @return {any}\n */\n getUserByClientId (clientid) {\n return this.clients.get(clientid) || null\n }\n\n /**\n * @param {ID} id\n * @return {string | null}\n */\n getUserByDeletedId (id) {\n for (const [userDescription, ds] of this.dss.entries()) {\n if (isDeleted(ds, id)) {\n return userDescription\n }\n }\n return null\n }\n}\n","\nimport {\n writeID,\n readID,\n compareIDs,\n getState,\n findRootTypeKey,\n Item,\n createID,\n ContentType,\n followRedone,\n ID, Doc, AbstractType // eslint-disable-line\n} from '../internals.js'\n\nimport * as encoding from 'lib0/encoding.js'\nimport * as decoding from 'lib0/decoding.js'\nimport * as error from 'lib0/error.js'\n\n/**\n * A relative position is based on the Yjs model and is not affected by document changes.\n * E.g. If you place a relative position before a certain character, it will always point to this character.\n * If you place a relative position at the end of a type, it will always point to the end of the type.\n *\n * A numeric position is often unsuited for user selections, because it does not change when content is inserted\n * before or after.\n *\n * ```Insert(0, 'x')('a|bc') = 'xa|bc'``` Where | is the relative position.\n *\n * One of the properties must be defined.\n *\n * @example\n * // Current cursor position is at position 10\n * const relativePosition = createRelativePositionFromIndex(yText, 10)\n * // modify yText\n * yText.insert(0, 'abc')\n * yText.delete(3, 10)\n * // Compute the cursor position\n * const absolutePosition = createAbsolutePositionFromRelativePosition(y, relativePosition)\n * absolutePosition.type === yText // => true\n * console.log('cursor location is ' + absolutePosition.index) // => cursor location is 3\n *\n */\nexport class RelativePosition {\n /**\n * @param {ID|null} type\n * @param {string|null} tname\n * @param {ID|null} item\n */\n constructor (type, tname, item) {\n /**\n * @type {ID|null}\n */\n this.type = type\n /**\n * @type {string|null}\n */\n this.tname = tname\n /**\n * @type {ID | null}\n */\n this.item = item\n }\n}\n\n/**\n * @param {any} json\n * @return {RelativePosition}\n *\n * @function\n */\nexport const createRelativePositionFromJSON = json => new RelativePosition(json.type == null ? null : createID(json.type.client, json.type.clock), json.tname || null, json.item == null ? null : createID(json.item.client, json.item.clock))\n\nexport class AbsolutePosition {\n /**\n * @param {AbstractType} type\n * @param {number} index\n */\n constructor (type, index) {\n /**\n * @type {AbstractType}\n */\n this.type = type\n /**\n * @type {number}\n */\n this.index = index\n }\n}\n\n/**\n * @param {AbstractType} type\n * @param {number} index\n *\n * @function\n */\nexport const createAbsolutePosition = (type, index) => new AbsolutePosition(type, index)\n\n/**\n * @param {AbstractType} type\n * @param {ID|null} item\n *\n * @function\n */\nexport const createRelativePosition = (type, item) => {\n let typeid = null\n let tname = null\n if (type._item === null) {\n tname = findRootTypeKey(type)\n } else {\n typeid = createID(type._item.id.client, type._item.id.clock)\n }\n return new RelativePosition(typeid, tname, item)\n}\n\n/**\n * Create a relativePosition based on a absolute position.\n *\n * @param {AbstractType} type The base type (e.g. YText or YArray).\n * @param {number} index The absolute position.\n * @return {RelativePosition}\n *\n * @function\n */\nexport const createRelativePositionFromTypeIndex = (type, index) => {\n let t = type._start\n while (t !== null) {\n if (!t.deleted && t.countable) {\n if (t.length > index) {\n // case 1: found position somewhere in the linked list\n return createRelativePosition(type, createID(t.id.client, t.id.clock + index))\n }\n index -= t.length\n }\n t = t.right\n }\n return createRelativePosition(type, null)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {RelativePosition} rpos\n *\n * @function\n */\nexport const writeRelativePosition = (encoder, rpos) => {\n const { type, tname, item } = rpos\n if (item !== null) {\n encoding.writeVarUint(encoder, 0)\n writeID(encoder, item)\n } else if (tname !== null) {\n // case 2: found position at the end of the list and type is stored in y.share\n encoding.writeUint8(encoder, 1)\n encoding.writeVarString(encoder, tname)\n } else if (type !== null) {\n // case 3: found position at the end of the list and type is attached to an item\n encoding.writeUint8(encoder, 2)\n writeID(encoder, type)\n } else {\n throw error.unexpectedCase()\n }\n return encoder\n}\n\n/**\n * @param {RelativePosition} rpos\n * @return {Uint8Array}\n */\nexport const encodeRelativePosition = rpos => {\n const encoder = encoding.createEncoder()\n writeRelativePosition(encoder, rpos)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {decoding.Decoder} decoder\n * @return {RelativePosition|null}\n *\n * @function\n */\nexport const readRelativePosition = decoder => {\n let type = null\n let tname = null\n let itemID = null\n switch (decoding.readVarUint(decoder)) {\n case 0:\n // case 1: found position somewhere in the linked list\n itemID = readID(decoder)\n break\n case 1:\n // case 2: found position at the end of the list and type is stored in y.share\n tname = decoding.readVarString(decoder)\n break\n case 2: {\n // case 3: found position at the end of the list and type is attached to an item\n type = readID(decoder)\n }\n }\n return new RelativePosition(type, tname, itemID)\n}\n\n/**\n * @param {Uint8Array} uint8Array\n * @return {RelativePosition|null}\n */\nexport const decodeRelativePosition = uint8Array => readRelativePosition(decoding.createDecoder(uint8Array))\n\n/**\n * @param {RelativePosition} rpos\n * @param {Doc} doc\n * @return {AbsolutePosition|null}\n *\n * @function\n */\nexport const createAbsolutePositionFromRelativePosition = (rpos, doc) => {\n const store = doc.store\n const rightID = rpos.item\n const typeID = rpos.type\n const tname = rpos.tname\n let type = null\n let index = 0\n if (rightID !== null) {\n if (getState(store, rightID.client) <= rightID.clock) {\n return null\n }\n const res = followRedone(store, rightID)\n const right = res.item\n if (!(right instanceof Item)) {\n return null\n }\n type = /** @type {AbstractType} */ (right.parent)\n if (type._item === null || !type._item.deleted) {\n index = right.deleted || !right.countable ? 0 : res.diff\n let n = right.left\n while (n !== null) {\n if (!n.deleted && n.countable) {\n index += n.length\n }\n n = n.left\n }\n }\n } else {\n if (tname !== null) {\n type = doc.get(tname)\n } else if (typeID !== null) {\n if (getState(store, typeID.client) <= typeID.clock) {\n // type does not exist yet\n return null\n }\n const { item } = followRedone(store, typeID)\n if (item instanceof Item && item.content instanceof ContentType) {\n type = item.content.type\n } else {\n // struct is garbage collected\n return null\n }\n } else {\n throw error.unexpectedCase()\n }\n index = type._length\n }\n return createAbsolutePosition(type, index)\n}\n\n/**\n * @param {RelativePosition|null} a\n * @param {RelativePosition|null} b\n *\n * @function\n */\nexport const compareRelativePositions = (a, b) => a === b || (\n a !== null && b !== null && a.tname === b.tname && compareIDs(a.item, b.item) && compareIDs(a.type, b.type)\n)\n","\nimport {\n isDeleted,\n createDeleteSetFromStructStore,\n getStateVector,\n getItemCleanStart,\n iterateDeletedStructs,\n writeDeleteSet,\n writeStateVector,\n readDeleteSet,\n readStateVector,\n createDeleteSet,\n createID,\n getState,\n findIndexSS,\n UpdateEncoderV2,\n DefaultDSEncoder,\n applyUpdateV2,\n AbstractDSDecoder, AbstractDSEncoder, DSEncoderV2, DSDecoderV1, DSDecoderV2, Transaction, Doc, DeleteSet, Item // eslint-disable-line\n} from '../internals.js'\n\nimport * as map from 'lib0/map.js'\nimport * as set from 'lib0/set.js'\nimport * as decoding from 'lib0/decoding.js'\nimport * as encoding from 'lib0/encoding.js'\n\nexport class Snapshot {\n /**\n * @param {DeleteSet} ds\n * @param {Map} sv state map\n */\n constructor (ds, sv) {\n /**\n * @type {DeleteSet}\n */\n this.ds = ds\n /**\n * State Map\n * @type {Map}\n */\n this.sv = sv\n }\n}\n\n/**\n * @param {Snapshot} snap1\n * @param {Snapshot} snap2\n * @return {boolean}\n */\nexport const equalSnapshots = (snap1, snap2) => {\n const ds1 = snap1.ds.clients\n const ds2 = snap2.ds.clients\n const sv1 = snap1.sv\n const sv2 = snap2.sv\n if (sv1.size !== sv2.size || ds1.size !== ds2.size) {\n return false\n }\n for (const [key, value] of sv1.entries()) {\n if (sv2.get(key) !== value) {\n return false\n }\n }\n for (const [client, dsitems1] of ds1.entries()) {\n const dsitems2 = ds2.get(client) || []\n if (dsitems1.length !== dsitems2.length) {\n return false\n }\n for (let i = 0; i < dsitems1.length; i++) {\n const dsitem1 = dsitems1[i]\n const dsitem2 = dsitems2[i]\n if (dsitem1.clock !== dsitem2.clock || dsitem1.len !== dsitem2.len) {\n return false\n }\n }\n }\n return true\n}\n\n/**\n * @param {Snapshot} snapshot\n * @param {AbstractDSEncoder} [encoder]\n * @return {Uint8Array}\n */\nexport const encodeSnapshotV2 = (snapshot, encoder = new DSEncoderV2()) => {\n writeDeleteSet(encoder, snapshot.ds)\n writeStateVector(encoder, snapshot.sv)\n return encoder.toUint8Array()\n}\n\n/**\n * @param {Snapshot} snapshot\n * @return {Uint8Array}\n */\nexport const encodeSnapshot = snapshot => encodeSnapshotV2(snapshot, new DefaultDSEncoder())\n\n/**\n * @param {Uint8Array} buf\n * @param {AbstractDSDecoder} [decoder]\n * @return {Snapshot}\n */\nexport const decodeSnapshotV2 = (buf, decoder = new DSDecoderV2(decoding.createDecoder(buf))) => {\n return new Snapshot(readDeleteSet(decoder), readStateVector(decoder))\n}\n\n/**\n * @param {Uint8Array} buf\n * @return {Snapshot}\n */\nexport const decodeSnapshot = buf => decodeSnapshotV2(buf, new DSDecoderV1(decoding.createDecoder(buf)))\n\n/**\n * @param {DeleteSet} ds\n * @param {Map} sm\n * @return {Snapshot}\n */\nexport const createSnapshot = (ds, sm) => new Snapshot(ds, sm)\n\nexport const emptySnapshot = createSnapshot(createDeleteSet(), new Map())\n\n/**\n * @param {Doc} doc\n * @return {Snapshot}\n */\nexport const snapshot = doc => createSnapshot(createDeleteSetFromStructStore(doc.store), getStateVector(doc.store))\n\n/**\n * @param {Item} item\n * @param {Snapshot|undefined} snapshot\n *\n * @protected\n * @function\n */\nexport const isVisible = (item, snapshot) => snapshot === undefined ? !item.deleted : (\n snapshot.sv.has(item.id.client) && (snapshot.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot.ds, item.id)\n)\n\n/**\n * @param {Transaction} transaction\n * @param {Snapshot} snapshot\n */\nexport const splitSnapshotAffectedStructs = (transaction, snapshot) => {\n const meta = map.setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, set.create)\n const store = transaction.doc.store\n // check if we already split for this snapshot\n if (!meta.has(snapshot)) {\n snapshot.sv.forEach((clock, client) => {\n if (clock < getState(store, client)) {\n getItemCleanStart(transaction, createID(client, clock))\n }\n })\n iterateDeletedStructs(transaction, snapshot.ds, item => {})\n meta.add(snapshot)\n }\n}\n\n/**\n * @param {Doc} originDoc\n * @param {Snapshot} snapshot\n * @param {Doc} [newDoc] Optionally, you may define the Yjs document that receives the data from originDoc\n * @return {Doc}\n */\nexport const createDocFromSnapshot = (originDoc, snapshot, newDoc = new Doc()) => {\n if (originDoc.gc) {\n // we should not try to restore a GC-ed document, because some of the restored items might have their content deleted\n throw new Error('originDoc must not be garbage collected')\n }\n const { sv, ds } = snapshot\n\n const encoder = new UpdateEncoderV2()\n originDoc.transact(transaction => {\n let size = 0\n sv.forEach(clock => {\n if (clock > 0) {\n size++\n }\n })\n encoding.writeVarUint(encoder.restEncoder, size)\n // splitting the structs before writing them to the encoder\n for (const [client, clock] of sv) {\n if (clock === 0) {\n continue\n }\n if (clock < getState(originDoc.store, client)) {\n getItemCleanStart(transaction, createID(client, clock))\n }\n const structs = originDoc.store.clients.get(client) || []\n const lastStructIndex = findIndexSS(structs, clock - 1)\n // write # encoded structs\n encoding.writeVarUint(encoder.restEncoder, lastStructIndex + 1)\n encoder.writeClient(client)\n // first clock written is 0\n encoding.writeVarUint(encoder.restEncoder, 0)\n for (let i = 0; i <= lastStructIndex; i++) {\n structs[i].write(encoder, 0)\n }\n }\n writeDeleteSet(encoder, ds)\n })\n\n applyUpdateV2(newDoc, encoder.toUint8Array(), 'snapshot')\n return newDoc\n}\n","\nimport {\n GC,\n splitItem,\n Transaction, ID, Item, DSDecoderV2 // eslint-disable-line\n} from '../internals.js'\n\nimport * as math from 'lib0/math.js'\nimport * as error from 'lib0/error.js'\n\nexport class StructStore {\n constructor () {\n /**\n * @type {Map>}\n */\n this.clients = new Map()\n /**\n * Store incompleted struct reads here\n * `i` denotes to the next read operation\n * We could shift the array of refs instead, but shift is incredible\n * slow in Chrome for arrays with more than 100k elements\n * @see tryResumePendingStructRefs\n * @type {Map}>}\n */\n this.pendingClientsStructRefs = new Map()\n /**\n * Stack of pending structs waiting for struct dependencies\n * Maximum length of stack is structReaders.size\n * @type {Array}\n */\n this.pendingStack = []\n /**\n * @type {Array}\n */\n this.pendingDeleteReaders = []\n }\n}\n\n/**\n * Return the states as a Map.\n * Note that clock refers to the next expected clock id.\n *\n * @param {StructStore} store\n * @return {Map}\n *\n * @public\n * @function\n */\nexport const getStateVector = store => {\n const sm = new Map()\n store.clients.forEach((structs, client) => {\n const struct = structs[structs.length - 1]\n sm.set(client, struct.id.clock + struct.length)\n })\n return sm\n}\n\n/**\n * @param {StructStore} store\n * @param {number} client\n * @return {number}\n *\n * @public\n * @function\n */\nexport const getState = (store, client) => {\n const structs = store.clients.get(client)\n if (structs === undefined) {\n return 0\n }\n const lastStruct = structs[structs.length - 1]\n return lastStruct.id.clock + lastStruct.length\n}\n\n/**\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nexport const integretyCheck = store => {\n store.clients.forEach(structs => {\n for (let i = 1; i < structs.length; i++) {\n const l = structs[i - 1]\n const r = structs[i]\n if (l.id.clock + l.length !== r.id.clock) {\n throw new Error('StructStore failed integrety check')\n }\n }\n })\n}\n\n/**\n * @param {StructStore} store\n * @param {GC|Item} struct\n *\n * @private\n * @function\n */\nexport const addStruct = (store, struct) => {\n let structs = store.clients.get(struct.id.client)\n if (structs === undefined) {\n structs = []\n store.clients.set(struct.id.client, structs)\n } else {\n const lastStruct = structs[structs.length - 1]\n if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) {\n throw error.unexpectedCase()\n }\n }\n structs.push(struct)\n}\n\n/**\n * Perform a binary search on a sorted array\n * @param {Array} structs\n * @param {number} clock\n * @return {number}\n *\n * @private\n * @function\n */\nexport const findIndexSS = (structs, clock) => {\n let left = 0\n let right = structs.length - 1\n let mid = structs[right]\n let midclock = mid.id.clock\n if (midclock === clock) {\n return right\n }\n // @todo does it even make sense to pivot the search?\n // If a good split misses, it might actually increase the time to find the correct item.\n // Currently, the only advantage is that search with pivoting might find the item on the first try.\n let midindex = math.floor((clock / (midclock + mid.length - 1)) * right) // pivoting the search\n while (left <= right) {\n mid = structs[midindex]\n midclock = mid.id.clock\n if (midclock <= clock) {\n if (clock < midclock + mid.length) {\n return midindex\n }\n left = midindex + 1\n } else {\n right = midindex - 1\n }\n midindex = math.floor((left + right) / 2)\n }\n // Always check state before looking for a struct in StructStore\n // Therefore the case of not finding a struct is unexpected\n throw error.unexpectedCase()\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {StructStore} store\n * @param {ID} id\n * @return {GC|Item}\n *\n * @private\n * @function\n */\nexport const find = (store, id) => {\n /**\n * @type {Array}\n */\n // @ts-ignore\n const structs = store.clients.get(id.client)\n return structs[findIndexSS(structs, id.clock)]\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n * @private\n * @function\n */\nexport const getItem = /** @type {function(StructStore,ID):Item} */ (find)\n\n/**\n * @param {Transaction} transaction\n * @param {Array} structs\n * @param {number} clock\n */\nexport const findIndexCleanStart = (transaction, structs, clock) => {\n const index = findIndexSS(structs, clock)\n const struct = structs[index]\n if (struct.id.clock < clock && struct instanceof Item) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock))\n return index + 1\n }\n return index\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {Transaction} transaction\n * @param {ID} id\n * @return {Item}\n *\n * @private\n * @function\n */\nexport const getItemCleanStart = (transaction, id) => {\n const structs = /** @type {Array} */ (transaction.doc.store.clients.get(id.client))\n return structs[findIndexCleanStart(transaction, structs, id.clock)]\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @param {ID} id\n * @return {Item}\n *\n * @private\n * @function\n */\nexport const getItemCleanEnd = (transaction, store, id) => {\n /**\n * @type {Array}\n */\n // @ts-ignore\n const structs = store.clients.get(id.client)\n const index = findIndexSS(structs, id.clock)\n const struct = structs[index]\n if (id.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, id.clock - struct.id.clock + 1))\n }\n return struct\n}\n\n/**\n * Replace `item` with `newitem` in store\n * @param {StructStore} store\n * @param {GC|Item} struct\n * @param {GC|Item} newStruct\n *\n * @private\n * @function\n */\nexport const replaceStruct = (store, struct, newStruct) => {\n const structs = /** @type {Array} */ (store.clients.get(struct.id.client))\n structs[findIndexSS(structs, struct.id.clock)] = newStruct\n}\n\n/**\n * Iterate over a range of structs\n *\n * @param {Transaction} transaction\n * @param {Array} structs\n * @param {number} clockStart Inclusive start\n * @param {number} len\n * @param {function(GC|Item):void} f\n *\n * @function\n */\nexport const iterateStructs = (transaction, structs, clockStart, len, f) => {\n if (len === 0) {\n return\n }\n const clockEnd = clockStart + len\n let index = findIndexCleanStart(transaction, structs, clockStart)\n let struct\n do {\n struct = structs[index++]\n if (clockEnd < struct.id.clock + struct.length) {\n findIndexCleanStart(transaction, structs, clockEnd)\n }\n f(struct)\n } while (index < structs.length && structs[index].id.clock < clockEnd)\n}\n","\nimport {\n getState,\n writeStructsFromTransaction,\n writeDeleteSet,\n DeleteSet,\n sortAndMergeDeleteSet,\n getStateVector,\n findIndexSS,\n callEventHandlerListeners,\n Item,\n generateNewClientId,\n createID,\n AbstractUpdateEncoder, GC, StructStore, UpdateEncoderV2, DefaultUpdateEncoder, AbstractType, AbstractStruct, YEvent, Doc // eslint-disable-line\n} from '../internals.js'\n\nimport * as map from 'lib0/map.js'\nimport * as math from 'lib0/math.js'\nimport * as set from 'lib0/set.js'\nimport * as logging from 'lib0/logging.js'\nimport { callAll } from 'lib0/function.js'\n\n/**\n * A transaction is created for every change on the Yjs model. It is possible\n * to bundle changes on the Yjs model in a single transaction to\n * minimize the number on messages sent and the number of observer calls.\n * If possible the user of this library should bundle as many changes as\n * possible. Here is an example to illustrate the advantages of bundling:\n *\n * @example\n * const map = y.define('map', YMap)\n * // Log content when change is triggered\n * map.observe(() => {\n * console.log('change triggered')\n * })\n * // Each change on the map type triggers a log message:\n * map.set('a', 0) // => \"change triggered\"\n * map.set('b', 0) // => \"change triggered\"\n * // When put in a transaction, it will trigger the log after the transaction:\n * y.transact(() => {\n * map.set('a', 1)\n * map.set('b', 1)\n * }) // => \"change triggered\"\n *\n * @public\n */\nexport class Transaction {\n /**\n * @param {Doc} doc\n * @param {any} origin\n * @param {boolean} local\n */\n constructor (doc, origin, local) {\n /**\n * The Yjs instance.\n * @type {Doc}\n */\n this.doc = doc\n /**\n * Describes the set of deleted items by ids\n * @type {DeleteSet}\n */\n this.deleteSet = new DeleteSet()\n /**\n * Holds the state before the transaction started.\n * @type {Map}\n */\n this.beforeState = getStateVector(doc.store)\n /**\n * Holds the state after the transaction.\n * @type {Map}\n */\n this.afterState = new Map()\n /**\n * All types that were directly modified (property added or child\n * inserted/deleted). New types are not included in this Set.\n * Maps from type to parentSubs (`item.parentSub = null` for YArray)\n * @type {Map,Set>}\n */\n this.changed = new Map()\n /**\n * Stores the events for the types that observe also child elements.\n * It is mainly used by `observeDeep`.\n * @type {Map,Array>}\n */\n this.changedParentTypes = new Map()\n /**\n * @type {Array}\n */\n this._mergeStructs = []\n /**\n * @type {any}\n */\n this.origin = origin\n /**\n * Stores meta information on the transaction\n * @type {Map}\n */\n this.meta = new Map()\n /**\n * Whether this change originates from this doc.\n * @type {boolean}\n */\n this.local = local\n /**\n * @type {Set}\n */\n this.subdocsAdded = new Set()\n /**\n * @type {Set}\n */\n this.subdocsRemoved = new Set()\n /**\n * @type {Set}\n */\n this.subdocsLoaded = new Set()\n }\n}\n\n/**\n * @param {AbstractUpdateEncoder} encoder\n * @param {Transaction} transaction\n * @return {boolean} Whether data was written.\n */\nexport const writeUpdateMessageFromTransaction = (encoder, transaction) => {\n if (transaction.deleteSet.clients.size === 0 && !map.any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) {\n return false\n }\n sortAndMergeDeleteSet(transaction.deleteSet)\n writeStructsFromTransaction(encoder, transaction)\n writeDeleteSet(encoder, transaction.deleteSet)\n return true\n}\n\n/**\n * @param {Transaction} transaction\n *\n * @private\n * @function\n */\nexport const nextID = transaction => {\n const y = transaction.doc\n return createID(y.clientID, getState(y.store, y.clientID))\n}\n\n/**\n * If `type.parent` was added in current transaction, `type` technically\n * did not change, it was just added and we should not fire events for `type`.\n *\n * @param {Transaction} transaction\n * @param {AbstractType} type\n * @param {string|null} parentSub\n */\nexport const addChangedTypeToTransaction = (transaction, type, parentSub) => {\n const item = type._item\n if (item === null || (item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted)) {\n map.setIfUndefined(transaction.changed, type, set.create).add(parentSub)\n }\n}\n\n/**\n * @param {Array} structs\n * @param {number} pos\n */\nconst tryToMergeWithLeft = (structs, pos) => {\n const left = structs[pos - 1]\n const right = structs[pos]\n if (left.deleted === right.deleted && left.constructor === right.constructor) {\n if (left.mergeWith(right)) {\n structs.splice(pos, 1)\n if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType} */ (right.parent)._map.get(right.parentSub) === right) {\n /** @type {AbstractType} */ (right.parent)._map.set(right.parentSub, /** @type {Item} */ (left))\n }\n }\n }\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n * @param {function(Item):boolean} gcFilter\n */\nconst tryGcDeleteSet = (ds, store, gcFilter) => {\n for (const [client, deleteItems] of ds.clients.entries()) {\n const structs = /** @type {Array} */ (store.clients.get(client))\n for (let di = deleteItems.length - 1; di >= 0; di--) {\n const deleteItem = deleteItems[di]\n const endDeleteItemClock = deleteItem.clock + deleteItem.len\n for (\n let si = findIndexSS(structs, deleteItem.clock), struct = structs[si];\n si < structs.length && struct.id.clock < endDeleteItemClock;\n struct = structs[++si]\n ) {\n const struct = structs[si]\n if (deleteItem.clock + deleteItem.len <= struct.id.clock) {\n break\n }\n if (struct instanceof Item && struct.deleted && !struct.keep && gcFilter(struct)) {\n struct.gc(store, false)\n }\n }\n }\n }\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n */\nconst tryMergeDeleteSet = (ds, store) => {\n // try to merge deleted / gc'd items\n // merge from right to left for better efficiecy and so we don't miss any merge targets\n ds.clients.forEach((deleteItems, client) => {\n const structs = /** @type {Array} */ (store.clients.get(client))\n for (let di = deleteItems.length - 1; di >= 0; di--) {\n const deleteItem = deleteItems[di]\n // start with merging the item next to the last deleted item\n const mostRightIndexToCheck = math.min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1))\n for (\n let si = mostRightIndexToCheck, struct = structs[si];\n si > 0 && struct.id.clock >= deleteItem.clock;\n struct = structs[--si]\n ) {\n tryToMergeWithLeft(structs, si)\n }\n }\n })\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n * @param {function(Item):boolean} gcFilter\n */\nexport const tryGc = (ds, store, gcFilter) => {\n tryGcDeleteSet(ds, store, gcFilter)\n tryMergeDeleteSet(ds, store)\n}\n\n/**\n * @param {Array} transactionCleanups\n * @param {number} i\n */\nconst cleanupTransactions = (transactionCleanups, i) => {\n if (i < transactionCleanups.length) {\n const transaction = transactionCleanups[i]\n const doc = transaction.doc\n const store = doc.store\n const ds = transaction.deleteSet\n const mergeStructs = transaction._mergeStructs\n try {\n sortAndMergeDeleteSet(ds)\n transaction.afterState = getStateVector(transaction.doc.store)\n doc._transaction = null\n doc.emit('beforeObserverCalls', [transaction, doc])\n /**\n * An array of event callbacks.\n *\n * Each callback is called even if the other ones throw errors.\n *\n * @type {Array}\n */\n const fs = []\n // observe events on changed types\n transaction.changed.forEach((subs, itemtype) =>\n fs.push(() => {\n if (itemtype._item === null || !itemtype._item.deleted) {\n itemtype._callObserver(transaction, subs)\n }\n })\n )\n fs.push(() => {\n // deep observe events\n transaction.changedParentTypes.forEach((events, type) =>\n fs.push(() => {\n // We need to think about the possibility that the user transforms the\n // Y.Doc in the event.\n if (type._item === null || !type._item.deleted) {\n events = events\n .filter(event =>\n event.target._item === null || !event.target._item.deleted\n )\n events\n .forEach(event => {\n event.currentTarget = type\n })\n // sort events by path length so that top-level events are fired first.\n events\n .sort((event1, event2) => event1.path.length - event2.path.length)\n // We don't need to check for events.length\n // because we know it has at least one element\n callEventHandlerListeners(type._dEH, events, transaction)\n }\n })\n )\n fs.push(() => doc.emit('afterTransaction', [transaction, doc]))\n })\n callAll(fs, [])\n } finally {\n // Replace deleted items with ItemDeleted / GC.\n // This is where content is actually remove from the Yjs Doc.\n if (doc.gc) {\n tryGcDeleteSet(ds, store, doc.gcFilter)\n }\n tryMergeDeleteSet(ds, store)\n\n // on all affected store.clients props, try to merge\n transaction.afterState.forEach((clock, client) => {\n const beforeClock = transaction.beforeState.get(client) || 0\n if (beforeClock !== clock) {\n const structs = /** @type {Array} */ (store.clients.get(client))\n // we iterate from right to left so we can safely remove entries\n const firstChangePos = math.max(findIndexSS(structs, beforeClock), 1)\n for (let i = structs.length - 1; i >= firstChangePos; i--) {\n tryToMergeWithLeft(structs, i)\n }\n }\n })\n // try to merge mergeStructs\n // @todo: it makes more sense to transform mergeStructs to a DS, sort it, and merge from right to left\n // but at the moment DS does not handle duplicates\n for (let i = 0; i < mergeStructs.length; i++) {\n const { client, clock } = mergeStructs[i].id\n const structs = /** @type {Array} */ (store.clients.get(client))\n const replacedStructPos = findIndexSS(structs, clock)\n if (replacedStructPos + 1 < structs.length) {\n tryToMergeWithLeft(structs, replacedStructPos + 1)\n }\n if (replacedStructPos > 0) {\n tryToMergeWithLeft(structs, replacedStructPos)\n }\n }\n if (!transaction.local && transaction.afterState.get(doc.clientID) !== transaction.beforeState.get(doc.clientID)) {\n doc.clientID = generateNewClientId()\n logging.print(logging.ORANGE, logging.BOLD, '[yjs] ', logging.UNBOLD, logging.RED, 'Changed the client-id because another client seems to be using it.')\n }\n // @todo Merge all the transactions into one and provide send the data as a single update message\n doc.emit('afterTransactionCleanup', [transaction, doc])\n if (doc._observers.has('update')) {\n const encoder = new DefaultUpdateEncoder()\n const hasContent = writeUpdateMessageFromTransaction(encoder, transaction)\n if (hasContent) {\n doc.emit('update', [encoder.toUint8Array(), transaction.origin, doc])\n }\n }\n if (doc._observers.has('updateV2')) {\n const encoder = new UpdateEncoderV2()\n const hasContent = writeUpdateMessageFromTransaction(encoder, transaction)\n if (hasContent) {\n doc.emit('updateV2', [encoder.toUint8Array(), transaction.origin, doc])\n }\n }\n transaction.subdocsAdded.forEach(subdoc => doc.subdocs.add(subdoc))\n transaction.subdocsRemoved.forEach(subdoc => doc.subdocs.delete(subdoc))\n\n doc.emit('subdocs', [{ loaded: transaction.subdocsLoaded, added: transaction.subdocsAdded, removed: transaction.subdocsRemoved }])\n transaction.subdocsRemoved.forEach(subdoc => subdoc.destroy())\n\n if (transactionCleanups.length <= i + 1) {\n doc._transactionCleanups = []\n doc.emit('afterAllTransactions', [doc, transactionCleanups])\n } else {\n cleanupTransactions(transactionCleanups, i + 1)\n }\n }\n }\n}\n\n/**\n * Implements the functionality of `y.transact(()=>{..})`\n *\n * @param {Doc} doc\n * @param {function(Transaction):void} f\n * @param {any} [origin=true]\n *\n * @function\n */\nexport const transact = (doc, f, origin = null, local = true) => {\n const transactionCleanups = doc._transactionCleanups\n let initialCall = false\n if (doc._transaction === null) {\n initialCall = true\n doc._transaction = new Transaction(doc, origin, local)\n transactionCleanups.push(doc._transaction)\n if (transactionCleanups.length === 1) {\n doc.emit('beforeAllTransactions', [doc])\n }\n doc.emit('beforeTransaction', [doc._transaction, doc])\n }\n try {\n f(doc._transaction)\n } finally {\n if (initialCall && transactionCleanups[0] === doc._transaction) {\n // The first transaction ended, now process observer calls.\n // Observer call may create new transactions for which we need to call the observers and do cleanup.\n // We don't want to nest these calls, so we execute these calls one after\n // another.\n // Also we need to ensure that all cleanups are called, even if the\n // observes throw errors.\n // This file is full of hacky try {} finally {} blocks to ensure that an\n // event can throw errors and also that the cleanup is called.\n cleanupTransactions(transactionCleanups, 0)\n }\n }\n}\n","import {\n mergeDeleteSets,\n iterateDeletedStructs,\n keepItem,\n transact,\n createID,\n redoItem,\n iterateStructs,\n isParentOf,\n followRedone,\n getItemCleanStart,\n getState,\n ID, Transaction, Doc, Item, GC, DeleteSet, AbstractType // eslint-disable-line\n} from '../internals.js'\n\nimport * as time from 'lib0/time.js'\nimport { Observable } from 'lib0/observable.js'\n\nclass StackItem {\n /**\n * @param {DeleteSet} ds\n * @param {Map} beforeState\n * @param {Map} afterState\n */\n constructor (ds, beforeState, afterState) {\n this.ds = ds\n this.beforeState = beforeState\n this.afterState = afterState\n /**\n * Use this to save and restore metadata like selection range\n */\n this.meta = new Map()\n }\n}\n\n/**\n * @param {UndoManager} undoManager\n * @param {Array} stack\n * @param {string} eventType\n * @return {StackItem?}\n */\nconst popStackItem = (undoManager, stack, eventType) => {\n /**\n * Whether a change happened\n * @type {StackItem?}\n */\n let result = null\n const doc = undoManager.doc\n const scope = undoManager.scope\n transact(doc, transaction => {\n while (stack.length > 0 && result === null) {\n const store = doc.store\n const stackItem = /** @type {StackItem} */ (stack.pop())\n /**\n * @type {Set}\n */\n const itemsToRedo = new Set()\n /**\n * @type {Array}\n */\n const itemsToDelete = []\n let performedChange = false\n stackItem.afterState.forEach((endClock, client) => {\n const startClock = stackItem.beforeState.get(client) || 0\n const len = endClock - startClock\n // @todo iterateStructs should not need the structs parameter\n const structs = /** @type {Array} */ (store.clients.get(client))\n if (startClock !== endClock) {\n // make sure structs don't overlap with the range of created operations [stackItem.start, stackItem.start + stackItem.end)\n // this must be executed before deleted structs are iterated.\n getItemCleanStart(transaction, createID(client, startClock))\n if (endClock < getState(doc.store, client)) {\n getItemCleanStart(transaction, createID(client, endClock))\n }\n iterateStructs(transaction, structs, startClock, len, struct => {\n if (struct instanceof Item) {\n if (struct.redone !== null) {\n let { item, diff } = followRedone(store, struct.id)\n if (diff > 0) {\n item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff))\n }\n if (item.length > len) {\n getItemCleanStart(transaction, createID(item.id.client, endClock))\n }\n struct = item\n }\n if (!struct.deleted && scope.some(type => isParentOf(type, /** @type {Item} */ (struct)))) {\n itemsToDelete.push(struct)\n }\n }\n })\n }\n })\n iterateDeletedStructs(transaction, stackItem.ds, struct => {\n const id = struct.id\n const clock = id.clock\n const client = id.client\n const startClock = stackItem.beforeState.get(client) || 0\n const endClock = stackItem.afterState.get(client) || 0\n if (\n struct instanceof Item &&\n scope.some(type => isParentOf(type, struct)) &&\n // Never redo structs in [stackItem.start, stackItem.start + stackItem.end) because they were created and deleted in the same capture interval.\n !(clock >= startClock && clock < endClock)\n ) {\n itemsToRedo.add(struct)\n }\n })\n itemsToRedo.forEach(struct => {\n performedChange = redoItem(transaction, struct, itemsToRedo) !== null || performedChange\n })\n // We want to delete in reverse order so that children are deleted before\n // parents, so we have more information available when items are filtered.\n for (let i = itemsToDelete.length - 1; i >= 0; i--) {\n const item = itemsToDelete[i]\n if (undoManager.deleteFilter(item)) {\n item.delete(transaction)\n performedChange = true\n }\n }\n result = stackItem\n if (result != null) {\n undoManager.emit('stack-item-popped', [{ stackItem: result, type: eventType }, undoManager])\n }\n }\n transaction.changed.forEach((subProps, type) => {\n // destroy search marker if necessary\n if (subProps.has(null) && type._searchMarker) {\n type._searchMarker.length = 0\n }\n })\n }, undoManager)\n return result\n}\n\n/**\n * @typedef {Object} UndoManagerOptions\n * @property {number} [UndoManagerOptions.captureTimeout=500]\n * @property {function(Item):boolean} [UndoManagerOptions.deleteFilter=()=>true] Sometimes\n * it is necessary to filter whan an Undo/Redo operation can delete. If this\n * filter returns false, the type/item won't be deleted even it is in the\n * undo/redo scope.\n * @property {Set} [UndoManagerOptions.trackedOrigins=new Set([null])]\n */\n\n/**\n * Fires 'stack-item-added' event when a stack item was added to either the undo- or\n * the redo-stack. You may store additional stack information via the\n * metadata property on `event.stackItem.meta` (it is a `Map` of metadata properties).\n * Fires 'stack-item-popped' event when a stack item was popped from either the\n * undo- or the redo-stack. You may restore the saved stack information from `event.stackItem.meta`.\n *\n * @extends {Observable<'stack-item-added'|'stack-item-popped'>}\n */\nexport class UndoManager extends Observable {\n /**\n * @param {AbstractType|Array>} typeScope Accepts either a single type, or an array of types\n * @param {UndoManagerOptions} options\n */\n constructor (typeScope, { captureTimeout = 500, deleteFilter = () => true, trackedOrigins = new Set([null]) } = {}) {\n super()\n this.scope = typeScope instanceof Array ? typeScope : [typeScope]\n this.deleteFilter = deleteFilter\n trackedOrigins.add(this)\n this.trackedOrigins = trackedOrigins\n /**\n * @type {Array}\n */\n this.undoStack = []\n /**\n * @type {Array}\n */\n this.redoStack = []\n /**\n * Whether the client is currently undoing (calling UndoManager.undo)\n *\n * @type {boolean}\n */\n this.undoing = false\n this.redoing = false\n this.doc = /** @type {Doc} */ (this.scope[0].doc)\n this.lastChange = 0\n this.doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => {\n // Only track certain transactions\n if (!this.scope.some(type => transaction.changedParentTypes.has(type)) || (!this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor)))) {\n return\n }\n const undoing = this.undoing\n const redoing = this.redoing\n const stack = undoing ? this.redoStack : this.undoStack\n if (undoing) {\n this.stopCapturing() // next undo should not be appended to last stack item\n } else if (!redoing) {\n // neither undoing nor redoing: delete redoStack\n this.redoStack = []\n }\n const beforeState = transaction.beforeState\n const afterState = transaction.afterState\n const now = time.getUnixTime()\n if (now - this.lastChange < captureTimeout && stack.length > 0 && !undoing && !redoing) {\n // append change to last stack op\n const lastOp = stack[stack.length - 1]\n lastOp.ds = mergeDeleteSets([lastOp.ds, transaction.deleteSet])\n lastOp.afterState = afterState\n } else {\n // create a new stack op\n stack.push(new StackItem(transaction.deleteSet, beforeState, afterState))\n }\n if (!undoing && !redoing) {\n this.lastChange = now\n }\n // make sure that deleted structs are not gc'd\n iterateDeletedStructs(transaction, transaction.deleteSet, /** @param {Item|GC} item */ item => {\n if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) {\n keepItem(item, true)\n }\n })\n this.emit('stack-item-added', [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? 'redo' : 'undo' }, this])\n })\n }\n\n clear () {\n this.doc.transact(transaction => {\n /**\n * @param {StackItem} stackItem\n */\n const clearItem = stackItem => {\n iterateDeletedStructs(transaction, stackItem.ds, item => {\n if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) {\n keepItem(item, false)\n }\n })\n }\n this.undoStack.forEach(clearItem)\n this.redoStack.forEach(clearItem)\n })\n this.undoStack = []\n this.redoStack = []\n }\n\n /**\n * UndoManager merges Undo-StackItem if they are created within time-gap\n * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next\n * StackItem won't be merged.\n *\n *\n * @example\n * // without stopCapturing\n * ytext.insert(0, 'a')\n * ytext.insert(1, 'b')\n * um.undo()\n * ytext.toString() // => '' (note that 'ab' was removed)\n * // with stopCapturing\n * ytext.insert(0, 'a')\n * um.stopCapturing()\n * ytext.insert(0, 'b')\n * um.undo()\n * ytext.toString() // => 'a' (note that only 'b' was removed)\n *\n */\n stopCapturing () {\n this.lastChange = 0\n }\n\n /**\n * Undo last changes on type.\n *\n * @return {StackItem?} Returns StackItem if a change was applied\n */\n undo () {\n this.undoing = true\n let res\n try {\n res = popStackItem(this, this.undoStack, 'undo')\n } finally {\n this.undoing = false\n }\n return res\n }\n\n /**\n * Redo last undo operation.\n *\n * @return {StackItem?} Returns StackItem if a change was applied\n */\n redo () {\n this.redoing = true\n let res\n try {\n res = popStackItem(this, this.redoStack, 'redo')\n } finally {\n this.redoing = false\n }\n return res\n }\n}\n","\nimport {\n isDeleted,\n Item, AbstractType, Transaction, AbstractStruct // eslint-disable-line\n} from '../internals.js'\n\nimport * as set from 'lib0/set.js'\nimport * as array from 'lib0/array.js'\n\n/**\n * YEvent describes the changes on a YType.\n */\nexport class YEvent {\n /**\n * @param {AbstractType} target The changed type.\n * @param {Transaction} transaction\n */\n constructor (target, transaction) {\n /**\n * The type on which this event was created on.\n * @type {AbstractType}\n */\n this.target = target\n /**\n * The current target on which the observe callback is called.\n * @type {AbstractType}\n */\n this.currentTarget = target\n /**\n * The transaction that triggered this event.\n * @type {Transaction}\n */\n this.transaction = transaction\n /**\n * @type {Object|null}\n */\n this._changes = null\n }\n\n /**\n * Computes the path from `y` to the changed type.\n *\n * The following property holds:\n * @example\n * let type = y\n * event.path.forEach(dir => {\n * type = type.get(dir)\n * })\n * type === event.target // => true\n */\n get path () {\n // @ts-ignore _item is defined because target is integrated\n return getPathTo(this.currentTarget, this.target)\n }\n\n /**\n * Check if a struct is deleted by this event.\n *\n * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.\n *\n * @param {AbstractStruct} struct\n * @return {boolean}\n */\n deletes (struct) {\n return isDeleted(this.transaction.deleteSet, struct.id)\n }\n\n /**\n * Check if a struct is added by this event.\n *\n * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.\n *\n * @param {AbstractStruct} struct\n * @return {boolean}\n */\n adds (struct) {\n return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0)\n }\n\n /**\n * @return {{added:Set,deleted:Set,keys:Map,delta:Array<{insert:Array}|{delete:number}|{retain:number}>}}\n */\n get changes () {\n let changes = this._changes\n if (changes === null) {\n const target = this.target\n const added = set.create()\n const deleted = set.create()\n /**\n * @type {Array<{insert:Array}|{delete:number}|{retain:number}>}\n */\n const delta = []\n /**\n * @type {Map}\n */\n const keys = new Map()\n changes = {\n added, deleted, delta, keys\n }\n const changed = /** @type Set */ (this.transaction.changed.get(target))\n if (changed.has(null)) {\n /**\n * @type {any}\n */\n let lastOp = null\n const packOp = () => {\n if (lastOp) {\n delta.push(lastOp)\n }\n }\n for (let item = target._start; item !== null; item = item.right) {\n if (item.deleted) {\n if (this.deletes(item) && !this.adds(item)) {\n if (lastOp === null || lastOp.delete === undefined) {\n packOp()\n lastOp = { delete: 0 }\n }\n lastOp.delete += item.length\n deleted.add(item)\n } // else nop\n } else {\n if (this.adds(item)) {\n if (lastOp === null || lastOp.insert === undefined) {\n packOp()\n lastOp = { insert: [] }\n }\n lastOp.insert = lastOp.insert.concat(item.content.getContent())\n added.add(item)\n } else {\n if (lastOp === null || lastOp.retain === undefined) {\n packOp()\n lastOp = { retain: 0 }\n }\n lastOp.retain += item.length\n }\n }\n }\n if (lastOp !== null && lastOp.retain === undefined) {\n packOp()\n }\n }\n changed.forEach(key => {\n if (key !== null) {\n const item = /** @type {Item} */ (target._map.get(key))\n /**\n * @type {'delete' | 'add' | 'update'}\n */\n let action\n let oldValue\n if (this.adds(item)) {\n let prev = item.left\n while (prev !== null && this.adds(prev)) {\n prev = prev.left\n }\n if (this.deletes(item)) {\n if (prev !== null && this.deletes(prev)) {\n action = 'delete'\n oldValue = array.last(prev.content.getContent())\n } else {\n return\n }\n } else {\n if (prev !== null && this.deletes(prev)) {\n action = 'update'\n oldValue = array.last(prev.content.getContent())\n } else {\n action = 'add'\n oldValue = undefined\n }\n }\n } else {\n if (this.deletes(item)) {\n action = 'delete'\n oldValue = array.last(/** @type {Item} */ item.content.getContent())\n } else {\n return // nop\n }\n }\n keys.set(key, { action, oldValue })\n }\n })\n this._changes = changes\n }\n return /** @type {any} */ (changes)\n }\n}\n\n/**\n * Compute the path from this type to the specified target.\n *\n * @example\n * // `child` should be accessible via `type.get(path[0]).get(path[1])..`\n * const path = type.getPathTo(child)\n * // assuming `type instanceof YArray`\n * console.log(path) // might look like => [2, 'key1']\n * child === type.get(path[0]).get(path[1])\n *\n * @param {AbstractType} parent\n * @param {AbstractType} child target\n * @return {Array} Path to the target\n *\n * @private\n * @function\n */\nconst getPathTo = (parent, child) => {\n const path = []\n while (child._item !== null && child !== parent) {\n if (child._item.parentSub !== null) {\n // parent is map-ish\n path.unshift(child._item.parentSub)\n } else {\n // parent is array-ish\n let i = 0\n let c = /** @type {AbstractType} */ (child._item.parent)._start\n while (c !== child._item && c !== null) {\n if (!c.deleted) {\n i++\n }\n c = c.right\n }\n path.unshift(i)\n }\n child = /** @type {AbstractType} */ (child._item.parent)\n }\n return path\n}\n","/**\n * Utility module to create and manipulate Iterators.\n *\n * @module iterator\n */\n\n/**\n * @template T,R\n * @param {Iterator} iterator\n * @param {function(T):R} f\n * @return {IterableIterator}\n */\nexport const mapIterator = (iterator, f) => ({\n /**\n * @param {function(T):R} f\n */\n [Symbol.iterator] () {\n return this\n },\n // @ts-ignore\n next () {\n const r = iterator.next()\n return { value: r.done ? undefined : f(r.value), done: r.done }\n }\n})\n\n/**\n * @template T\n * @param {function():IteratorResult} next\n * @return {IterableIterator}\n */\nexport const createIterator = next => ({\n /**\n * @return {IterableIterator}\n */\n [Symbol.iterator] () {\n return this\n },\n // @ts-ignore\n next\n})\n\n/**\n * @template T\n * @param {Iterator} iterator\n * @param {function(T):boolean} filter\n */\nexport const iteratorFilter = (iterator, filter) => createIterator(() => {\n let res\n do {\n res = iterator.next()\n } while (!res.done && !filter(res.value))\n return res\n})\n\n/**\n * @template T,M\n * @param {Iterator} iterator\n * @param {function(T):M} fmap\n */\nexport const iteratorMap = (iterator, fmap) => createIterator(() => {\n const { done, value } = iterator.next()\n return { done, value: done ? undefined : fmap(value) }\n})\n","\nimport {\n removeEventHandlerListener,\n callEventHandlerListeners,\n addEventHandlerListener,\n createEventHandler,\n getState,\n isVisible,\n ContentType,\n createID,\n ContentAny,\n ContentBinary,\n getItemCleanStart,\n ContentDoc, YText, YArray, AbstractUpdateEncoder, Doc, Snapshot, Transaction, EventHandler, YEvent, Item, // eslint-disable-line\n} from '../internals.js'\n\nimport * as map from 'lib0/map.js'\nimport * as iterator from 'lib0/iterator.js'\nimport * as error from 'lib0/error.js'\nimport * as math from 'lib0/math.js'\n\nconst maxSearchMarker = 80\n\n/**\n * A unique timestamp that identifies each marker.\n *\n * Time is relative,.. this is more like an ever-increasing clock.\n *\n * @type {number}\n */\nlet globalSearchMarkerTimestamp = 0\n\nexport class ArraySearchMarker {\n /**\n * @param {Item} p\n * @param {number} index\n */\n constructor (p, index) {\n p.marker = true\n this.p = p\n this.index = index\n this.timestamp = globalSearchMarkerTimestamp++\n }\n}\n\n/**\n * @param {ArraySearchMarker} marker\n */\nconst refreshMarkerTimestamp = marker => { marker.timestamp = globalSearchMarkerTimestamp++ }\n\n/**\n * This is rather complex so this function is the only thing that should overwrite a marker\n *\n * @param {ArraySearchMarker} marker\n * @param {Item} p\n * @param {number} index\n */\nconst overwriteMarker = (marker, p, index) => {\n marker.p.marker = false\n marker.p = p\n p.marker = true\n marker.index = index\n marker.timestamp = globalSearchMarkerTimestamp++\n}\n\n/**\n * @param {Array} searchMarker\n * @param {Item} p\n * @param {number} index\n */\nconst markPosition = (searchMarker, p, index) => {\n if (searchMarker.length >= maxSearchMarker) {\n // override oldest marker (we don't want to create more objects)\n const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b)\n overwriteMarker(marker, p, index)\n return marker\n } else {\n // create new marker\n const pm = new ArraySearchMarker(p, index)\n searchMarker.push(pm)\n return pm\n }\n}\n\n/**\n * Search marker help us to find positions in the associative array faster.\n *\n * They speed up the process of finding a position without much bookkeeping.\n *\n * A maximum of `maxSearchMarker` objects are created.\n *\n * This function always returns a refreshed marker (updated timestamp)\n *\n * @param {AbstractType} yarray\n * @param {number} index\n */\nexport const findMarker = (yarray, index) => {\n if (yarray._start === null || index === 0 || yarray._searchMarker === null) {\n return null\n }\n const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => math.abs(index - a.index) < math.abs(index - b.index) ? a : b)\n let p = yarray._start\n let pindex = 0\n if (marker !== null) {\n p = marker.p\n pindex = marker.index\n refreshMarkerTimestamp(marker) // we used it, we might need to use it again\n }\n // iterate to right if possible\n while (p.right !== null && pindex < index) {\n if (!p.deleted && p.countable) {\n if (index < pindex + p.length) {\n break\n }\n pindex += p.length\n }\n p = p.right\n }\n // iterate to left if necessary (might be that pindex > index)\n while (p.left !== null && pindex > index) {\n p = p.left\n if (!p.deleted && p.countable) {\n pindex -= p.length\n }\n }\n // we want to make sure that p can't be merged with left, because that would screw up everything\n // in that cas just return what we have (it is most likely the best marker anyway)\n // iterate to left until p can't be merged with left\n while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) {\n p = p.left\n if (!p.deleted && p.countable) {\n pindex -= p.length\n }\n }\n\n // @todo remove!\n // assure position\n // {\n // let start = yarray._start\n // let pos = 0\n // while (start !== p) {\n // if (!start.deleted && start.countable) {\n // pos += start.length\n // }\n // start = /** @type {Item} */ (start.right)\n // }\n // if (pos !== pindex) {\n // debugger\n // throw new Error('Gotcha position fail!')\n // }\n // }\n // if (marker) {\n // if (window.lengthes == null) {\n // window.lengthes = []\n // window.getLengthes = () => window.lengthes.sort((a, b) => a - b)\n // }\n // window.lengthes.push(marker.index - pindex)\n // console.log('distance', marker.index - pindex, 'len', p && p.parent.length)\n // }\n if (marker !== null && math.abs(marker.index - pindex) < /** @type {YText|YArray} */ (p.parent).length / maxSearchMarker) {\n // adjust existing marker\n overwriteMarker(marker, p, pindex)\n return marker\n } else {\n // create new marker\n return markPosition(yarray._searchMarker, p, pindex)\n }\n}\n\n/**\n * Update markers when a change happened.\n *\n * This should be called before doing a deletion!\n *\n * @param {Array} searchMarker\n * @param {number} index\n * @param {number} len If insertion, len is positive. If deletion, len is negative.\n */\nexport const updateMarkerChanges = (searchMarker, index, len) => {\n for (let i = searchMarker.length - 1; i >= 0; i--) {\n const m = searchMarker[i]\n if (len > 0) {\n /**\n * @type {Item|null}\n */\n let p = m.p\n p.marker = false\n // Ideally we just want to do a simple position comparison, but this will only work if\n // search markers don't point to deleted items for formats.\n // Iterate marker to prev undeleted countable position so we know what to do when updating a position\n while (p && (p.deleted || !p.countable)) {\n p = p.left\n if (p && !p.deleted && p.countable) {\n // adjust position. the loop should break now\n m.index -= p.length\n }\n }\n if (p === null || p.marker === true) {\n // remove search marker if updated position is null or if position is already marked\n searchMarker.splice(i, 1)\n continue\n }\n m.p = p\n p.marker = true\n }\n if (index < m.index || (len > 0 && index === m.index)) { // a simple index <= m.index check would actually suffice\n m.index = math.max(index, m.index + len)\n }\n }\n}\n\n/**\n * Accumulate all (list) children of a type and return them as an Array.\n *\n * @param {AbstractType} t\n * @return {Array}\n */\nexport const getTypeChildren = t => {\n let s = t._start\n const arr = []\n while (s) {\n arr.push(s)\n s = s.right\n }\n return arr\n}\n\n/**\n * Call event listeners with an event. This will also add an event to all\n * parents (for `.observeDeep` handlers).\n *\n * @template EventType\n * @param {AbstractType} type\n * @param {Transaction} transaction\n * @param {EventType} event\n */\nexport const callTypeObservers = (type, transaction, event) => {\n const changedType = type\n const changedParentTypes = transaction.changedParentTypes\n while (true) {\n // @ts-ignore\n map.setIfUndefined(changedParentTypes, type, () => []).push(event)\n if (type._item === null) {\n break\n }\n type = /** @type {AbstractType} */ (type._item.parent)\n }\n callEventHandlerListeners(changedType._eH, event, transaction)\n}\n\n/**\n * @template EventType\n * Abstract Yjs Type class\n */\nexport class AbstractType {\n constructor () {\n /**\n * @type {Item|null}\n */\n this._item = null\n /**\n * @type {Map}\n */\n this._map = new Map()\n /**\n * @type {Item|null}\n */\n this._start = null\n /**\n * @type {Doc|null}\n */\n this.doc = null\n this._length = 0\n /**\n * Event handlers\n * @type {EventHandler}\n */\n this._eH = createEventHandler()\n /**\n * Deep event handlers\n * @type {EventHandler,Transaction>}\n */\n this._dEH = createEventHandler()\n /**\n * @type {null | Array}\n */\n this._searchMarker = null\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item|null} item\n */\n _integrate (y, item) {\n this.doc = y\n this._item = item\n }\n\n /**\n * @return {AbstractType}\n */\n _copy () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n */\n _write (encoder) { }\n\n /**\n * The first non-deleted item\n */\n get _first () {\n let n = this._start\n while (n !== null && n.deleted) {\n n = n.right\n }\n return n\n }\n\n /**\n * Creates YEvent and calls all type observers.\n * Must be implemented by each type.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n if (!transaction.local && this._searchMarker) {\n this._searchMarker.length = 0\n }\n }\n\n /**\n * Observe all events that are created on this type.\n *\n * @param {function(EventType, Transaction):void} f Observer function\n */\n observe (f) {\n addEventHandlerListener(this._eH, f)\n }\n\n /**\n * Observe all events that are created by this type and its children.\n *\n * @param {function(Array,Transaction):void} f Observer function\n */\n observeDeep (f) {\n addEventHandlerListener(this._dEH, f)\n }\n\n /**\n * Unregister an observer function.\n *\n * @param {function(EventType,Transaction):void} f Observer function\n */\n unobserve (f) {\n removeEventHandlerListener(this._eH, f)\n }\n\n /**\n * Unregister an observer function.\n *\n * @param {function(Array,Transaction):void} f Observer function\n */\n unobserveDeep (f) {\n removeEventHandlerListener(this._dEH, f)\n }\n\n /**\n * @abstract\n * @return {any}\n */\n toJSON () {}\n}\n\n/**\n * @param {AbstractType} type\n * @return {Array}\n *\n * @private\n * @function\n */\nexport const typeListToArray = type => {\n const cs = []\n let n = type._start\n while (n !== null) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n cs.push(c[i])\n }\n }\n n = n.right\n }\n return cs\n}\n\n/**\n * @param {AbstractType} type\n * @param {Snapshot} snapshot\n * @return {Array}\n *\n * @private\n * @function\n */\nexport const typeListToArraySnapshot = (type, snapshot) => {\n const cs = []\n let n = type._start\n while (n !== null) {\n if (n.countable && isVisible(n, snapshot)) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n cs.push(c[i])\n }\n }\n n = n.right\n }\n return cs\n}\n\n/**\n * Executes a provided function on once on overy element of this YArray.\n *\n * @param {AbstractType} type\n * @param {function(any,number,any):void} f A function to execute on every element of this YArray.\n *\n * @private\n * @function\n */\nexport const typeListForEach = (type, f) => {\n let index = 0\n let n = type._start\n while (n !== null) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n f(c[i], index++, type)\n }\n }\n n = n.right\n }\n}\n\n/**\n * @template C,R\n * @param {AbstractType} type\n * @param {function(C,number,AbstractType):R} f\n * @return {Array}\n *\n * @private\n * @function\n */\nexport const typeListMap = (type, f) => {\n /**\n * @type {Array}\n */\n const result = []\n typeListForEach(type, (c, i) => {\n result.push(f(c, i, type))\n })\n return result\n}\n\n/**\n * @param {AbstractType} type\n * @return {IterableIterator}\n *\n * @private\n * @function\n */\nexport const typeListCreateIterator = type => {\n let n = type._start\n /**\n * @type {Array|null}\n */\n let currentContent = null\n let currentContentIndex = 0\n return {\n [Symbol.iterator] () {\n return this\n },\n next: () => {\n // find some content\n if (currentContent === null) {\n while (n !== null && n.deleted) {\n n = n.right\n }\n // check if we reached the end, no need to check currentContent, because it does not exist\n if (n === null) {\n return {\n done: true,\n value: undefined\n }\n }\n // we found n, so we can set currentContent\n currentContent = n.content.getContent()\n currentContentIndex = 0\n n = n.right // we used the content of n, now iterate to next\n }\n const value = currentContent[currentContentIndex++]\n // check if we need to empty currentContent\n if (currentContent.length <= currentContentIndex) {\n currentContent = null\n }\n return {\n done: false,\n value\n }\n }\n }\n}\n\n/**\n * Executes a provided function on once on overy element of this YArray.\n * Operates on a snapshotted state of the document.\n *\n * @param {AbstractType} type\n * @param {function(any,number,AbstractType):void} f A function to execute on every element of this YArray.\n * @param {Snapshot} snapshot\n *\n * @private\n * @function\n */\nexport const typeListForEachSnapshot = (type, f, snapshot) => {\n let index = 0\n let n = type._start\n while (n !== null) {\n if (n.countable && isVisible(n, snapshot)) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n f(c[i], index++, type)\n }\n }\n n = n.right\n }\n}\n\n/**\n * @param {AbstractType} type\n * @param {number} index\n * @return {any}\n *\n * @private\n * @function\n */\nexport const typeListGet = (type, index) => {\n const marker = findMarker(type, index)\n let n = type._start\n if (marker !== null) {\n n = marker.p\n index -= marker.index\n }\n for (; n !== null; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index < n.length) {\n return n.content.getContent()[index]\n }\n index -= n.length\n }\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {Item?} referenceItem\n * @param {Array|Array|boolean|number|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nexport const typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => {\n let left = referenceItem\n const doc = transaction.doc\n const ownClientId = doc.clientID\n const store = doc.store\n const right = referenceItem === null ? parent._start : referenceItem.right\n /**\n * @type {Array|number>}\n */\n let jsonContent = []\n const packJsonContent = () => {\n if (jsonContent.length > 0) {\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent))\n left.integrate(transaction, 0)\n jsonContent = []\n }\n }\n content.forEach(c => {\n switch (c.constructor) {\n case Number:\n case Object:\n case Boolean:\n case Array:\n case String:\n jsonContent.push(c)\n break\n default:\n packJsonContent()\n switch (c.constructor) {\n case Uint8Array:\n case ArrayBuffer:\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array(/** @type {Uint8Array} */ (c))))\n left.integrate(transaction, 0)\n break\n case Doc:\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc(/** @type {Doc} */ (c)))\n left.integrate(transaction, 0)\n break\n default:\n if (c instanceof AbstractType) {\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c))\n left.integrate(transaction, 0)\n } else {\n throw new Error('Unexpected content type in insert operation')\n }\n }\n }\n })\n packJsonContent()\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @param {Array|Array|number|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nexport const typeListInsertGenerics = (transaction, parent, index, content) => {\n if (index === 0) {\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, index, content.length)\n }\n return typeListInsertGenericsAfter(transaction, parent, null, content)\n }\n const startIndex = index\n const marker = findMarker(parent, index)\n let n = parent._start\n if (marker !== null) {\n n = marker.p\n index -= marker.index\n // we need to iterate one to the left so that the algorithm works\n if (index === 0) {\n // @todo refactor this as it actually doesn't consider formats\n n = n.prev // important! get the left undeleted item so that we can actually decrease index\n index += (n && n.countable && !n.deleted) ? n.length : 0\n }\n }\n for (; n !== null; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index <= n.length) {\n if (index < n.length) {\n // insert in-between\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index))\n }\n break\n }\n index -= n.length\n }\n }\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, startIndex, content.length)\n }\n return typeListInsertGenericsAfter(transaction, parent, n, content)\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @param {number} length\n *\n * @private\n * @function\n */\nexport const typeListDelete = (transaction, parent, index, length) => {\n if (length === 0) { return }\n const startIndex = index\n const startLength = length\n const marker = findMarker(parent, index)\n let n = parent._start\n if (marker !== null) {\n n = marker.p\n index -= marker.index\n }\n // compute the first item to be deleted\n for (; n !== null && index > 0; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index < n.length) {\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index))\n }\n index -= n.length\n }\n }\n // delete all items until done\n while (length > 0 && n !== null) {\n if (!n.deleted) {\n if (length < n.length) {\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length))\n }\n n.delete(transaction)\n length -= n.length\n }\n n = n.right\n }\n if (length > 0) {\n throw error.create('array length exceeded')\n }\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, startIndex, -startLength + length /* in case we remove the above exception */)\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {string} key\n *\n * @private\n * @function\n */\nexport const typeMapDelete = (transaction, parent, key) => {\n const c = parent._map.get(key)\n if (c !== undefined) {\n c.delete(transaction)\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {string} key\n * @param {Object|number|Array|string|Uint8Array|AbstractType} value\n *\n * @private\n * @function\n */\nexport const typeMapSet = (transaction, parent, key, value) => {\n const left = parent._map.get(key) || null\n const doc = transaction.doc\n const ownClientId = doc.clientID\n let content\n if (value == null) {\n content = new ContentAny([value])\n } else {\n switch (value.constructor) {\n case Number:\n case Object:\n case Boolean:\n case Array:\n case String:\n content = new ContentAny([value])\n break\n case Uint8Array:\n content = new ContentBinary(/** @type {Uint8Array} */ (value))\n break\n case Doc:\n content = new ContentDoc(/** @type {Doc} */ (value))\n break\n default:\n if (value instanceof AbstractType) {\n content = new ContentType(value)\n } else {\n throw new Error('Unexpected content type')\n }\n }\n }\n new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0)\n}\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined}\n *\n * @private\n * @function\n */\nexport const typeMapGet = (parent, key) => {\n const val = parent._map.get(key)\n return val !== undefined && !val.deleted ? val.content.getContent()[val.length - 1] : undefined\n}\n\n/**\n * @param {AbstractType} parent\n * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined>}\n *\n * @private\n * @function\n */\nexport const typeMapGetAll = (parent) => {\n /**\n * @type {Object}\n */\n const res = {}\n parent._map.forEach((value, key) => {\n if (!value.deleted) {\n res[key] = value.content.getContent()[value.length - 1]\n }\n })\n return res\n}\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @return {boolean}\n *\n * @private\n * @function\n */\nexport const typeMapHas = (parent, key) => {\n const val = parent._map.get(key)\n return val !== undefined && !val.deleted\n}\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @param {Snapshot} snapshot\n * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined}\n *\n * @private\n * @function\n */\nexport const typeMapGetSnapshot = (parent, key, snapshot) => {\n let v = parent._map.get(key) || null\n while (v !== null && (!snapshot.sv.has(v.id.client) || v.id.clock >= (snapshot.sv.get(v.id.client) || 0))) {\n v = v.left\n }\n return v !== null && isVisible(v, snapshot) ? v.content.getContent()[v.length - 1] : undefined\n}\n\n/**\n * @param {Map} map\n * @return {IterableIterator>}\n *\n * @private\n * @function\n */\nexport const createMapIterator = map => iterator.iteratorFilter(map.entries(), /** @param {any} entry */ entry => !entry[1].deleted)\n","/**\n * @module YArray\n */\n\nimport {\n YEvent,\n AbstractType,\n typeListGet,\n typeListToArray,\n typeListForEach,\n typeListCreateIterator,\n typeListInsertGenerics,\n typeListDelete,\n typeListMap,\n YArrayRefID,\n callTypeObservers,\n transact,\n ArraySearchMarker, AbstractUpdateDecoder, AbstractUpdateEncoder, Doc, Transaction, Item // eslint-disable-line\n} from '../internals.js'\n\n/**\n * Event that describes the changes on a YArray\n * @template T\n */\nexport class YArrayEvent extends YEvent {\n /**\n * @param {YArray} yarray The changed type\n * @param {Transaction} transaction The transaction object\n */\n constructor (yarray, transaction) {\n super(yarray, transaction)\n this._transaction = transaction\n }\n}\n\n/**\n * A shared Array implementation.\n * @template T\n * @extends AbstractType>\n * @implements {Iterable}\n */\nexport class YArray extends AbstractType {\n constructor () {\n super()\n /**\n * @type {Array?}\n * @private\n */\n this._prelimContent = []\n /**\n * @type {Array}\n */\n this._searchMarker = []\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n this.insert(0, /** @type {Array} */ (this._prelimContent))\n this._prelimContent = null\n }\n\n _copy () {\n return new YArray()\n }\n\n get length () {\n return this._prelimContent === null ? this._length : this._prelimContent.length\n }\n\n /**\n * Creates YArrayEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n super._callObserver(transaction, parentSubs)\n callTypeObservers(this, transaction, new YArrayEvent(this, transaction))\n }\n\n /**\n * Inserts new content at an index.\n *\n * Important: This function expects an array of content. Not just a content\n * object. The reason for this \"weirdness\" is that inserting several elements\n * is very efficient when it is done as a single operation.\n *\n * @example\n * // Insert character 'a' at position 0\n * yarray.insert(0, ['a'])\n * // Insert numbers 1, 2 at position 1\n * yarray.insert(1, [1, 2])\n *\n * @param {number} index The index to insert content at.\n * @param {Array} content The array of content\n */\n insert (index, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListInsertGenerics(transaction, this, index, content)\n })\n } else {\n /** @type {Array} */ (this._prelimContent).splice(index, 0, ...content)\n }\n }\n\n /**\n * Appends content to this YArray.\n *\n * @param {Array} content Array of content to append.\n */\n push (content) {\n this.insert(this.length, content)\n }\n\n /**\n * Preppends content to this YArray.\n *\n * @param {Array} content Array of content to preppend.\n */\n unshift (content) {\n this.insert(0, content)\n }\n\n /**\n * Deletes elements starting from an index.\n *\n * @param {number} index Index at which to start deleting elements\n * @param {number} length The number of elements to remove. Defaults to 1.\n */\n delete (index, length = 1) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListDelete(transaction, this, index, length)\n })\n } else {\n /** @type {Array} */ (this._prelimContent).splice(index, length)\n }\n }\n\n /**\n * Returns the i-th element from a YArray.\n *\n * @param {number} index The index of the element to return from the YArray\n * @return {T}\n */\n get (index) {\n return typeListGet(this, index)\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @return {Array}\n */\n toArray () {\n return typeListToArray(this)\n }\n\n /**\n * Transforms this Shared Type to a JSON object.\n *\n * @return {Array}\n */\n toJSON () {\n return this.map(c => c instanceof AbstractType ? c.toJSON() : c)\n }\n\n /**\n * Returns an Array with the result of calling a provided function on every\n * element of this YArray.\n *\n * @template T,M\n * @param {function(T,number,YArray):M} f Function that produces an element of the new Array\n * @return {Array} A new array with each element being the result of the\n * callback function\n */\n map (f) {\n return typeListMap(this, /** @type {any} */ (f))\n }\n\n /**\n * Executes a provided function on once on overy element of this YArray.\n *\n * @param {function(T,number,YArray):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n typeListForEach(this, f)\n }\n\n /**\n * @return {IterableIterator}\n */\n [Symbol.iterator] () {\n return typeListCreateIterator(this)\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YArrayRefID)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n *\n * @private\n * @function\n */\nexport const readYArray = decoder => new YArray()\n","\n/**\n * @module YMap\n */\n\nimport {\n YEvent,\n AbstractType,\n typeMapDelete,\n typeMapSet,\n typeMapGet,\n typeMapHas,\n createMapIterator,\n YMapRefID,\n callTypeObservers,\n transact,\n AbstractUpdateDecoder, AbstractUpdateEncoder, Doc, Transaction, Item // eslint-disable-line\n} from '../internals.js'\n\nimport * as iterator from 'lib0/iterator.js'\n\n/**\n * @template T\n * Event that describes the changes on a YMap.\n */\nexport class YMapEvent extends YEvent {\n /**\n * @param {YMap} ymap The YArray that changed.\n * @param {Transaction} transaction\n * @param {Set} subs The keys that changed.\n */\n constructor (ymap, transaction, subs) {\n super(ymap, transaction)\n this.keysChanged = subs\n }\n}\n\n/**\n * @template T number|string|Object|Array|Uint8Array\n * A shared Map implementation.\n *\n * @extends AbstractType>\n * @implements {Iterable}\n */\nexport class YMap extends AbstractType {\n /**\n *\n * @param {Iterable=} entries - an optional iterable to initialize the YMap\n */\n constructor (entries) {\n super()\n /**\n * @type {Map?}\n * @private\n */\n this._prelimContent = null\n\n if (entries === undefined) {\n this._prelimContent = new Map()\n } else {\n this._prelimContent = new Map(entries)\n }\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n ;/** @type {Map} */ (this._prelimContent).forEach((value, key) => {\n this.set(key, value)\n })\n this._prelimContent = null\n }\n\n _copy () {\n return new YMap()\n }\n\n /**\n * Creates YMapEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs))\n }\n\n /**\n * Transforms this Shared Type to a JSON object.\n *\n * @return {Object}\n */\n toJSON () {\n /**\n * @type {Object}\n */\n const map = {}\n this._map.forEach((item, key) => {\n if (!item.deleted) {\n const v = item.content.getContent()[item.length - 1]\n map[key] = v instanceof AbstractType ? v.toJSON() : v\n }\n })\n return map\n }\n\n /**\n * Returns the size of the YMap (count of key/value pairs)\n *\n * @return {number}\n */\n get size () {\n return [...createMapIterator(this._map)].length\n }\n\n /**\n * Returns the keys for each element in the YMap Type.\n *\n * @return {IterableIterator}\n */\n keys () {\n return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[0])\n }\n\n /**\n * Returns the values for each element in the YMap Type.\n *\n * @return {IterableIterator}\n */\n values () {\n return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[1].content.getContent()[v[1].length - 1])\n }\n\n /**\n * Returns an Iterator of [key, value] pairs\n *\n * @return {IterableIterator}\n */\n entries () {\n return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => [v[0], v[1].content.getContent()[v[1].length - 1]])\n }\n\n /**\n * Executes a provided function on once on every key-value pair.\n *\n * @param {function(T,string,YMap):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n /**\n * @type {Object}\n */\n const map = {}\n this._map.forEach((item, key) => {\n if (!item.deleted) {\n f(item.content.getContent()[item.length - 1], key, this)\n }\n })\n return map\n }\n\n /**\n * @return {IterableIterator}\n */\n [Symbol.iterator] () {\n return this.entries()\n }\n\n /**\n * Remove a specified element from this YMap.\n *\n * @param {string} key The key of the element to remove.\n */\n delete (key) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, key)\n })\n } else {\n /** @type {Map} */ (this._prelimContent).delete(key)\n }\n }\n\n /**\n * Adds or updates an element with a specified key and value.\n *\n * @param {string} key The key of the element to add to this YMap\n * @param {T} value The value of the element to add\n */\n set (key, value) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, key, value)\n })\n } else {\n /** @type {Map} */ (this._prelimContent).set(key, value)\n }\n return value\n }\n\n /**\n * Returns a specified element from this YMap.\n *\n * @param {string} key\n * @return {T|undefined}\n */\n get (key) {\n return /** @type {any} */ (typeMapGet(this, key))\n }\n\n /**\n * Returns a boolean indicating whether the specified key exists or not.\n *\n * @param {string} key The key to test.\n * @return {boolean}\n */\n has (key) {\n return typeMapHas(this, key)\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YMapRefID)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n *\n * @private\n * @function\n */\nexport const readYMap = decoder => new YMap()\n","\n/**\n * @module YText\n */\n\nimport {\n YEvent,\n AbstractType,\n getItemCleanStart,\n getState,\n isVisible,\n createID,\n YTextRefID,\n callTypeObservers,\n transact,\n ContentEmbed,\n GC,\n ContentFormat,\n ContentString,\n splitSnapshotAffectedStructs,\n iterateDeletedStructs,\n iterateStructs,\n findMarker,\n updateMarkerChanges,\n ArraySearchMarker, AbstractUpdateDecoder, AbstractUpdateEncoder, ID, Doc, Item, Snapshot, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as object from 'lib0/object.js'\nimport * as map from 'lib0/map.js'\nimport * as error from 'lib0/error.js'\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nconst equalAttrs = (a, b) => a === b || (typeof a === 'object' && typeof b === 'object' && a && b && object.equalFlat(a, b))\n\nexport class ItemTextListPosition {\n /**\n * @param {Item|null} left\n * @param {Item|null} right\n * @param {number} index\n * @param {Map} currentAttributes\n */\n constructor (left, right, index, currentAttributes) {\n this.left = left\n this.right = right\n this.index = index\n this.currentAttributes = currentAttributes\n }\n\n /**\n * Only call this if you know that this.right is defined\n */\n forward () {\n if (this.right === null) {\n error.unexpectedCase()\n }\n switch (this.right.content.constructor) {\n case ContentEmbed:\n case ContentString:\n if (!this.right.deleted) {\n this.index += this.right.length\n }\n break\n case ContentFormat:\n if (!this.right.deleted) {\n updateCurrentAttributes(this.currentAttributes, /** @type {ContentFormat} */ (this.right.content))\n }\n break\n }\n this.left = this.right\n this.right = this.right.right\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {ItemTextListPosition} pos\n * @param {number} count steps to move forward\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst findNextPosition = (transaction, pos, count) => {\n while (pos.right !== null && count > 0) {\n switch (pos.right.content.constructor) {\n case ContentEmbed:\n case ContentString:\n if (!pos.right.deleted) {\n if (count < pos.right.length) {\n // split right\n getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count))\n }\n pos.index += pos.right.length\n count -= pos.right.length\n }\n break\n case ContentFormat:\n if (!pos.right.deleted) {\n updateCurrentAttributes(pos.currentAttributes, /** @type {ContentFormat} */ (pos.right.content))\n }\n break\n }\n pos.left = pos.right\n pos.right = pos.right.right\n // pos.forward() - we don't forward because that would halve the performance because we already do the checks above\n }\n return pos\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst findPosition = (transaction, parent, index) => {\n const currentAttributes = new Map()\n const marker = findMarker(parent, index)\n if (marker) {\n const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes)\n return findNextPosition(transaction, pos, index - marker.index)\n } else {\n const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes)\n return findNextPosition(transaction, pos, index)\n }\n}\n\n/**\n * Negate applied formats\n *\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {Map} negatedAttributes\n *\n * @private\n * @function\n */\nconst insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => {\n // check if we really need to remove attributes\n while (\n currPos.right !== null && (\n currPos.right.deleted === true || (\n currPos.right.content.constructor === ContentFormat &&\n equalAttrs(negatedAttributes.get(/** @type {ContentFormat} */ (currPos.right.content).key), /** @type {ContentFormat} */ (currPos.right.content).value)\n )\n )\n ) {\n if (!currPos.right.deleted) {\n negatedAttributes.delete(/** @type {ContentFormat} */ (currPos.right.content).key)\n }\n currPos.forward()\n }\n const doc = transaction.doc\n const ownClientId = doc.clientID\n let left = currPos.left\n const right = currPos.right\n negatedAttributes.forEach((val, key) => {\n left = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val))\n left.integrate(transaction, 0)\n })\n}\n\n/**\n * @param {Map} currentAttributes\n * @param {ContentFormat} format\n *\n * @private\n * @function\n */\nconst updateCurrentAttributes = (currentAttributes, format) => {\n const { key, value } = format\n if (value === null) {\n currentAttributes.delete(key)\n } else {\n currentAttributes.set(key, value)\n }\n}\n\n/**\n * @param {ItemTextListPosition} currPos\n * @param {Object} attributes\n *\n * @private\n * @function\n */\nconst minimizeAttributeChanges = (currPos, attributes) => {\n // go right while attributes[right.key] === right.value (or right is deleted)\n while (true) {\n if (currPos.right === null) {\n break\n } else if (currPos.right.deleted || (currPos.right.content.constructor === ContentFormat && equalAttrs(attributes[(/** @type {ContentFormat} */ (currPos.right.content)).key] || null, /** @type {ContentFormat} */ (currPos.right.content).value))) {\n //\n } else {\n break\n }\n currPos.forward()\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {Object} attributes\n * @return {Map}\n *\n * @private\n * @function\n **/\nconst insertAttributes = (transaction, parent, currPos, attributes) => {\n const doc = transaction.doc\n const ownClientId = doc.clientID\n const negatedAttributes = new Map()\n // insert format-start items\n for (const key in attributes) {\n const val = attributes[key]\n const currentVal = currPos.currentAttributes.get(key) || null\n if (!equalAttrs(currentVal, val)) {\n // save negated attribute (set null if currentVal undefined)\n negatedAttributes.set(key, currentVal)\n const { left, right } = currPos\n currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val))\n currPos.right.integrate(transaction, 0)\n currPos.forward()\n }\n }\n return negatedAttributes\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {string|object} text\n * @param {Object} attributes\n *\n * @private\n * @function\n **/\nconst insertText = (transaction, parent, currPos, text, attributes) => {\n currPos.currentAttributes.forEach((val, key) => {\n if (attributes[key] === undefined) {\n attributes[key] = null\n }\n })\n const doc = transaction.doc\n const ownClientId = doc.clientID\n minimizeAttributeChanges(currPos, attributes)\n const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes)\n // insert content\n const content = text.constructor === String ? new ContentString(/** @type {string} */ (text)) : new ContentEmbed(text)\n let { left, right, index } = currPos\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength())\n }\n right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content)\n right.integrate(transaction, 0)\n currPos.right = right\n currPos.index = index\n currPos.forward()\n insertNegatedAttributes(transaction, parent, currPos, negatedAttributes)\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {number} length\n * @param {Object} attributes\n *\n * @private\n * @function\n */\nconst formatText = (transaction, parent, currPos, length, attributes) => {\n const doc = transaction.doc\n const ownClientId = doc.clientID\n minimizeAttributeChanges(currPos, attributes)\n const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes)\n // iterate until first non-format or null is found\n // delete all formats with attributes[format.key] != null\n while (length > 0 && currPos.right !== null) {\n if (!currPos.right.deleted) {\n switch (currPos.right.content.constructor) {\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (currPos.right.content)\n const attr = attributes[key]\n if (attr !== undefined) {\n if (equalAttrs(attr, value)) {\n negatedAttributes.delete(key)\n } else {\n negatedAttributes.set(key, value)\n }\n currPos.right.delete(transaction)\n }\n break\n }\n case ContentEmbed:\n case ContentString:\n if (length < currPos.right.length) {\n getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length))\n }\n length -= currPos.right.length\n break\n }\n }\n currPos.forward()\n }\n // Quill just assumes that the editor starts with a newline and that it always\n // ends with a newline. We only insert that newline when a new newline is\n // inserted - i.e when length is bigger than type.length\n if (length > 0) {\n let newlines = ''\n for (; length > 0; length--) {\n newlines += '\\n'\n }\n currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines))\n currPos.right.integrate(transaction, 0)\n currPos.forward()\n }\n insertNegatedAttributes(transaction, parent, currPos, negatedAttributes)\n}\n\n/**\n * Call this function after string content has been deleted in order to\n * clean up formatting Items.\n *\n * @param {Transaction} transaction\n * @param {Item} start\n * @param {Item|null} end exclusive end, automatically iterates to the next Content Item\n * @param {Map} startAttributes\n * @param {Map} endAttributes This attribute is modified!\n * @return {number} The amount of formatting Items deleted.\n *\n * @function\n */\nconst cleanupFormattingGap = (transaction, start, end, startAttributes, endAttributes) => {\n while (end && end.content.constructor !== ContentString && end.content.constructor !== ContentEmbed) {\n if (!end.deleted && end.content.constructor === ContentFormat) {\n updateCurrentAttributes(endAttributes, /** @type {ContentFormat} */ (end.content))\n }\n end = end.right\n }\n let cleanups = 0\n while (start !== end) {\n if (!start.deleted) {\n const content = start.content\n switch (content.constructor) {\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (content)\n if ((endAttributes.get(key) || null) !== value || (startAttributes.get(key) || null) === value) {\n // Either this format is overwritten or it is not necessary because the attribute already existed.\n start.delete(transaction)\n cleanups++\n }\n break\n }\n }\n }\n start = /** @type {Item} */ (start.right)\n }\n return cleanups\n}\n\n/**\n * @param {Transaction} transaction\n * @param {Item | null} item\n */\nconst cleanupContextlessFormattingGap = (transaction, item) => {\n // iterate until item.right is null or content\n while (item && item.right && (item.right.deleted || (item.right.content.constructor !== ContentString && item.right.content.constructor !== ContentEmbed))) {\n item = item.right\n }\n const attrs = new Set()\n // iterate back until a content item is found\n while (item && (item.deleted || (item.content.constructor !== ContentString && item.content.constructor !== ContentEmbed))) {\n if (!item.deleted && item.content.constructor === ContentFormat) {\n const key = /** @type {ContentFormat} */ (item.content).key\n if (attrs.has(key)) {\n item.delete(transaction)\n } else {\n attrs.add(key)\n }\n }\n item = item.left\n }\n}\n\n/**\n * This function is experimental and subject to change / be removed.\n *\n * Ideally, we don't need this function at all. Formatting attributes should be cleaned up\n * automatically after each change. This function iterates twice over the complete YText type\n * and removes unnecessary formatting attributes. This is also helpful for testing.\n *\n * This function won't be exported anymore as soon as there is confidence that the YText type works as intended.\n *\n * @param {YText} type\n * @return {number} How many formatting attributes have been cleaned up.\n */\nexport const cleanupYTextFormatting = type => {\n let res = 0\n transact(/** @type {Doc} */ (type.doc), transaction => {\n let start = /** @type {Item} */ (type._start)\n let end = type._start\n let startAttributes = map.create()\n const currentAttributes = map.copy(startAttributes)\n while (end) {\n if (end.deleted === false) {\n switch (end.content.constructor) {\n case ContentFormat:\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (end.content))\n break\n case ContentEmbed:\n case ContentString:\n res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes)\n startAttributes = map.copy(currentAttributes)\n start = end\n break\n }\n }\n end = end.right\n }\n })\n return res\n}\n\n/**\n * @param {Transaction} transaction\n * @param {ItemTextListPosition} currPos\n * @param {number} length\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst deleteText = (transaction, currPos, length) => {\n const startLength = length\n const startAttrs = map.copy(currPos.currentAttributes)\n const start = currPos.right\n while (length > 0 && currPos.right !== null) {\n if (currPos.right.deleted === false) {\n switch (currPos.right.content.constructor) {\n case ContentEmbed:\n case ContentString:\n if (length < currPos.right.length) {\n getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length))\n }\n length -= currPos.right.length\n currPos.right.delete(transaction)\n break\n }\n }\n currPos.forward()\n }\n if (start) {\n cleanupFormattingGap(transaction, start, currPos.right, startAttrs, map.copy(currPos.currentAttributes))\n }\n const parent = /** @type {AbstractType} */ (/** @type {Item} */ (currPos.left || currPos.right).parent)\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length)\n }\n return currPos\n}\n\n/**\n * The Quill Delta format represents changes on a text document with\n * formatting information. For mor information visit {@link https://quilljs.com/docs/delta/|Quill Delta}\n *\n * @example\n * {\n * ops: [\n * { insert: 'Gandalf', attributes: { bold: true } },\n * { insert: ' the ' },\n * { insert: 'Grey', attributes: { color: '#cccccc' } }\n * ]\n * }\n *\n */\n\n/**\n * Attributes that can be assigned to a selection of text.\n *\n * @example\n * {\n * bold: true,\n * font-size: '40px'\n * }\n *\n * @typedef {Object} TextAttributes\n */\n\n/**\n * @typedef {Object} DeltaItem\n * @property {number|undefined} DeltaItem.delete\n * @property {number|undefined} DeltaItem.retain\n * @property {string|undefined} DeltaItem.insert\n * @property {Object} DeltaItem.attributes\n */\n\n/**\n * Event that describes the changes on a YText type.\n */\nexport class YTextEvent extends YEvent {\n /**\n * @param {YText} ytext\n * @param {Transaction} transaction\n */\n constructor (ytext, transaction) {\n super(ytext, transaction)\n /**\n * @type {Array|null}\n */\n this._delta = null\n }\n\n /**\n * Compute the changes in the delta format.\n * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document.\n *\n * @type {Array}\n *\n * @public\n */\n get delta () {\n if (this._delta === null) {\n const y = /** @type {Doc} */ (this.target.doc)\n this._delta = []\n transact(y, transaction => {\n const delta = /** @type {Array} */ (this._delta)\n const currentAttributes = new Map() // saves all current attributes for insert\n const oldAttributes = new Map()\n let item = this.target._start\n /**\n * @type {string?}\n */\n let action = null\n /**\n * @type {Object}\n */\n const attributes = {} // counts added or removed new attributes for retain\n /**\n * @type {string|object}\n */\n let insert = ''\n let retain = 0\n let deleteLen = 0\n const addOp = () => {\n if (action !== null) {\n /**\n * @type {any}\n */\n let op\n switch (action) {\n case 'delete':\n op = { delete: deleteLen }\n deleteLen = 0\n break\n case 'insert':\n op = { insert }\n if (currentAttributes.size > 0) {\n op.attributes = {}\n currentAttributes.forEach((value, key) => {\n if (value !== null) {\n op.attributes[key] = value\n }\n })\n }\n insert = ''\n break\n case 'retain':\n op = { retain }\n if (Object.keys(attributes).length > 0) {\n op.attributes = {}\n for (const key in attributes) {\n op.attributes[key] = attributes[key]\n }\n }\n retain = 0\n break\n }\n delta.push(op)\n action = null\n }\n }\n while (item !== null) {\n switch (item.content.constructor) {\n case ContentEmbed:\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n addOp()\n action = 'insert'\n insert = /** @type {ContentEmbed} */ (item.content).embed\n addOp()\n }\n } else if (this.deletes(item)) {\n if (action !== 'delete') {\n addOp()\n action = 'delete'\n }\n deleteLen += 1\n } else if (!item.deleted) {\n if (action !== 'retain') {\n addOp()\n action = 'retain'\n }\n retain += 1\n }\n break\n case ContentString:\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n if (action !== 'insert') {\n addOp()\n action = 'insert'\n }\n insert += /** @type {ContentString} */ (item.content).str\n }\n } else if (this.deletes(item)) {\n if (action !== 'delete') {\n addOp()\n action = 'delete'\n }\n deleteLen += item.length\n } else if (!item.deleted) {\n if (action !== 'retain') {\n addOp()\n action = 'retain'\n }\n retain += item.length\n }\n break\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (item.content)\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n const curVal = currentAttributes.get(key) || null\n if (!equalAttrs(curVal, value)) {\n if (action === 'retain') {\n addOp()\n }\n if (equalAttrs(value, (oldAttributes.get(key) || null))) {\n delete attributes[key]\n } else {\n attributes[key] = value\n }\n } else {\n item.delete(transaction)\n }\n }\n } else if (this.deletes(item)) {\n oldAttributes.set(key, value)\n const curVal = currentAttributes.get(key) || null\n if (!equalAttrs(curVal, value)) {\n if (action === 'retain') {\n addOp()\n }\n attributes[key] = curVal\n }\n } else if (!item.deleted) {\n oldAttributes.set(key, value)\n const attr = attributes[key]\n if (attr !== undefined) {\n if (!equalAttrs(attr, value)) {\n if (action === 'retain') {\n addOp()\n }\n if (value === null) {\n attributes[key] = value\n } else {\n delete attributes[key]\n }\n } else {\n item.delete(transaction)\n }\n }\n }\n if (!item.deleted) {\n if (action === 'insert') {\n addOp()\n }\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (item.content))\n }\n break\n }\n }\n item = item.right\n }\n addOp()\n while (delta.length > 0) {\n const lastOp = delta[delta.length - 1]\n if (lastOp.retain !== undefined && lastOp.attributes === undefined) {\n // retain delta's if they don't assign attributes\n delta.pop()\n } else {\n break\n }\n }\n })\n }\n return this._delta\n }\n}\n\n/**\n * Type that represents text with formatting information.\n *\n * This type replaces y-richtext as this implementation is able to handle\n * block formats (format information on a paragraph), embeds (complex elements\n * like pictures and videos), and text formats (**bold**, *italic*).\n *\n * @extends AbstractType\n */\nexport class YText extends AbstractType {\n /**\n * @param {String} [string] The initial value of the YText.\n */\n constructor (string) {\n super()\n /**\n * Array of pending operations on this type\n * @type {Array?}\n */\n this._pending = string !== undefined ? [() => this.insert(0, string)] : []\n /**\n * @type {Array}\n */\n this._searchMarker = []\n }\n\n /**\n * Number of characters of this text type.\n *\n * @type {number}\n */\n get length () {\n return this._length\n }\n\n /**\n * @param {Doc} y\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n try {\n /** @type {Array} */ (this._pending).forEach(f => f())\n } catch (e) {\n console.error(e)\n }\n this._pending = null\n }\n\n _copy () {\n return new YText()\n }\n\n /**\n * Creates YTextEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n super._callObserver(transaction, parentSubs)\n const event = new YTextEvent(this, transaction)\n const doc = transaction.doc\n // If a remote change happened, we try to cleanup potential formatting duplicates.\n if (!transaction.local) {\n // check if another formatting item was inserted\n let foundFormattingItem = false\n for (const [client, afterClock] of transaction.afterState.entries()) {\n const clock = transaction.beforeState.get(client) || 0\n if (afterClock === clock) {\n continue\n }\n iterateStructs(transaction, /** @type {Array} */ (doc.store.clients.get(client)), clock, afterClock, item => {\n if (!item.deleted && /** @type {Item} */ (item).content.constructor === ContentFormat) {\n foundFormattingItem = true\n }\n })\n if (foundFormattingItem) {\n break\n }\n }\n if (!foundFormattingItem) {\n iterateDeletedStructs(transaction, transaction.deleteSet, item => {\n if (item instanceof GC || foundFormattingItem) {\n return\n }\n if (item.parent === this && item.content.constructor === ContentFormat) {\n foundFormattingItem = true\n }\n })\n }\n transact(doc, (t) => {\n if (foundFormattingItem) {\n // If a formatting item was inserted, we simply clean the whole type.\n // We need to compute currentAttributes for the current position anyway.\n cleanupYTextFormatting(this)\n } else {\n // If no formatting attribute was inserted, we can make due with contextless\n // formatting cleanups.\n // Contextless: it is not necessary to compute currentAttributes for the affected position.\n iterateDeletedStructs(t, t.deleteSet, item => {\n if (item instanceof GC) {\n return\n }\n if (item.parent === this) {\n cleanupContextlessFormattingGap(t, item)\n }\n })\n }\n })\n }\n callTypeObservers(this, transaction, event)\n }\n\n /**\n * Returns the unformatted string representation of this YText type.\n *\n * @public\n */\n toString () {\n let str = ''\n /**\n * @type {Item|null}\n */\n let n = this._start\n while (n !== null) {\n if (!n.deleted && n.countable && n.content.constructor === ContentString) {\n str += /** @type {ContentString} */ (n.content).str\n }\n n = n.right\n }\n return str\n }\n\n /**\n * Returns the unformatted string representation of this YText type.\n *\n * @return {string}\n * @public\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * Apply a {@link Delta} on this shared YText type.\n *\n * @param {any} delta The changes to apply on this element.\n * @param {object} [opts]\n * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true.\n *\n *\n * @public\n */\n applyDelta (delta, { sanitize = true } = {}) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n const currPos = new ItemTextListPosition(null, this._start, 0, new Map())\n for (let i = 0; i < delta.length; i++) {\n const op = delta[i]\n if (op.insert !== undefined) {\n // Quill assumes that the content starts with an empty paragraph.\n // Yjs/Y.Text assumes that it starts empty. We always hide that\n // there is a newline at the end of the content.\n // If we omit this step, clients will see a different number of\n // paragraphs, but nothing bad will happen.\n const ins = (!sanitize && typeof op.insert === 'string' && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === '\\n') ? op.insert.slice(0, -1) : op.insert\n if (typeof ins !== 'string' || ins.length > 0) {\n insertText(transaction, this, currPos, ins, op.attributes || {})\n }\n } else if (op.retain !== undefined) {\n formatText(transaction, this, currPos, op.retain, op.attributes || {})\n } else if (op.delete !== undefined) {\n deleteText(transaction, currPos, op.delete)\n }\n }\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.applyDelta(delta))\n }\n }\n\n /**\n * Returns the Delta representation of this YText type.\n *\n * @param {Snapshot} [snapshot]\n * @param {Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', ID):any} [computeYChange]\n * @return {any} The Delta representation of this type.\n *\n * @public\n */\n toDelta (snapshot, prevSnapshot, computeYChange) {\n /**\n * @type{Array}\n */\n const ops = []\n const currentAttributes = new Map()\n const doc = /** @type {Doc} */ (this.doc)\n let str = ''\n let n = this._start\n function packStr () {\n if (str.length > 0) {\n // pack str with attributes to ops\n /**\n * @type {Object}\n */\n const attributes = {}\n let addAttributes = false\n currentAttributes.forEach((value, key) => {\n addAttributes = true\n attributes[key] = value\n })\n /**\n * @type {Object}\n */\n const op = { insert: str }\n if (addAttributes) {\n op.attributes = attributes\n }\n ops.push(op)\n str = ''\n }\n }\n // snapshots are merged again after the transaction, so we need to keep the\n // transalive until we are done\n transact(doc, transaction => {\n if (snapshot) {\n splitSnapshotAffectedStructs(transaction, snapshot)\n }\n if (prevSnapshot) {\n splitSnapshotAffectedStructs(transaction, prevSnapshot)\n }\n while (n !== null) {\n if (isVisible(n, snapshot) || (prevSnapshot !== undefined && isVisible(n, prevSnapshot))) {\n switch (n.content.constructor) {\n case ContentString: {\n const cur = currentAttributes.get('ychange')\n if (snapshot !== undefined && !isVisible(n, snapshot)) {\n if (cur === undefined || cur.user !== n.id.client || cur.state !== 'removed') {\n packStr()\n currentAttributes.set('ychange', computeYChange ? computeYChange('removed', n.id) : { type: 'removed' })\n }\n } else if (prevSnapshot !== undefined && !isVisible(n, prevSnapshot)) {\n if (cur === undefined || cur.user !== n.id.client || cur.state !== 'added') {\n packStr()\n currentAttributes.set('ychange', computeYChange ? computeYChange('added', n.id) : { type: 'added' })\n }\n } else if (cur !== undefined) {\n packStr()\n currentAttributes.delete('ychange')\n }\n str += /** @type {ContentString} */ (n.content).str\n break\n }\n case ContentEmbed: {\n packStr()\n /**\n * @type {Object}\n */\n const op = {\n insert: /** @type {ContentEmbed} */ (n.content).embed\n }\n if (currentAttributes.size > 0) {\n const attrs = /** @type {Object} */ ({})\n op.attributes = attrs\n currentAttributes.forEach((value, key) => {\n attrs[key] = value\n })\n }\n ops.push(op)\n break\n }\n case ContentFormat:\n if (isVisible(n, snapshot)) {\n packStr()\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (n.content))\n }\n break\n }\n }\n n = n.right\n }\n packStr()\n }, splitSnapshotAffectedStructs)\n return ops\n }\n\n /**\n * Insert text at a given index.\n *\n * @param {number} index The index at which to start inserting.\n * @param {String} text The text to insert at the specified position.\n * @param {TextAttributes} [attributes] Optionally define some formatting\n * information to apply on the inserted\n * Text.\n * @public\n */\n insert (index, text, attributes) {\n if (text.length <= 0) {\n return\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index)\n if (!attributes) {\n attributes = {}\n // @ts-ignore\n pos.currentAttributes.forEach((v, k) => { attributes[k] = v })\n }\n insertText(transaction, this, pos, text, attributes)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.insert(index, text, attributes))\n }\n }\n\n /**\n * Inserts an embed at a index.\n *\n * @param {number} index The index to insert the embed at.\n * @param {Object} embed The Object that represents the embed.\n * @param {TextAttributes} attributes Attribute information to apply on the\n * embed\n *\n * @public\n */\n insertEmbed (index, embed, attributes = {}) {\n if (embed.constructor !== Object) {\n throw new Error('Embed must be an Object')\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index)\n insertText(transaction, this, pos, embed, attributes)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.insertEmbed(index, embed, attributes))\n }\n }\n\n /**\n * Deletes text starting from an index.\n *\n * @param {number} index Index at which to start deleting.\n * @param {number} length The number of characters to remove. Defaults to 1.\n *\n * @public\n */\n delete (index, length) {\n if (length === 0) {\n return\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n deleteText(transaction, findPosition(transaction, this, index), length)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.delete(index, length))\n }\n }\n\n /**\n * Assigns properties to a range of text.\n *\n * @param {number} index The position where to start formatting.\n * @param {number} length The amount of characters to assign properties to.\n * @param {TextAttributes} attributes Attribute information to apply on the\n * text.\n *\n * @public\n */\n format (index, length, attributes) {\n if (length === 0) {\n return\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index)\n if (pos.right === null) {\n return\n }\n formatText(transaction, this, pos, length, attributes)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.format(index, length, attributes))\n }\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YTextRefID)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {YText}\n *\n * @private\n * @function\n */\nexport const readYText = decoder => new YText()\n","/**\n * @module YXml\n */\n\nimport {\n YXmlEvent,\n YXmlElement,\n AbstractType,\n typeListMap,\n typeListForEach,\n typeListInsertGenerics,\n typeListDelete,\n typeListToArray,\n YXmlFragmentRefID,\n callTypeObservers,\n transact,\n AbstractUpdateDecoder, AbstractUpdateEncoder, Doc, ContentType, Transaction, Item, YXmlText, YXmlHook, Snapshot // eslint-disable-line\n} from '../internals.js'\n\n/**\n * Define the elements to which a set of CSS queries apply.\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors|CSS_Selectors}\n *\n * @example\n * query = '.classSelector'\n * query = 'nodeSelector'\n * query = '#idSelector'\n *\n * @typedef {string} CSS_Selector\n */\n\n/**\n * Dom filter function.\n *\n * @callback domFilter\n * @param {string} nodeName The nodeName of the element\n * @param {Map} attributes The map of attributes.\n * @return {boolean} Whether to include the Dom node in the YXmlElement.\n */\n\n/**\n * Represents a subset of the nodes of a YXmlElement / YXmlFragment and a\n * position within them.\n *\n * Can be created with {@link YXmlFragment#createTreeWalker}\n *\n * @public\n * @implements {Iterable}\n */\nexport class YXmlTreeWalker {\n /**\n * @param {YXmlFragment | YXmlElement} root\n * @param {function(AbstractType):boolean} [f]\n */\n constructor (root, f = () => true) {\n this._filter = f\n this._root = root\n /**\n * @type {Item}\n */\n this._currentNode = /** @type {Item} */ (root._start)\n this._firstCall = true\n }\n\n [Symbol.iterator] () {\n return this\n }\n\n /**\n * Get the next node.\n *\n * @return {IteratorResult} The next node.\n *\n * @public\n */\n next () {\n /**\n * @type {Item|null}\n */\n let n = this._currentNode\n let type = /** @type {any} */ (n.content).type\n if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { // if first call, we check if we can use the first item\n do {\n type = /** @type {any} */ (n.content).type\n if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) {\n // walk down in the tree\n n = type._start\n } else {\n // walk right or up in the tree\n while (n !== null) {\n if (n.right !== null) {\n n = n.right\n break\n } else if (n.parent === this._root) {\n n = null\n } else {\n n = /** @type {AbstractType} */ (n.parent)._item\n }\n }\n }\n } while (n !== null && (n.deleted || !this._filter(/** @type {ContentType} */ (n.content).type)))\n }\n this._firstCall = false\n if (n === null) {\n // @ts-ignore\n return { value: undefined, done: true }\n }\n this._currentNode = n\n return { value: /** @type {any} */ (n.content).type, done: false }\n }\n}\n\n/**\n * Represents a list of {@link YXmlElement}.and {@link YXmlText} types.\n * A YxmlFragment is similar to a {@link YXmlElement}, but it does not have a\n * nodeName and it does not have attributes. Though it can be bound to a DOM\n * element - in this case the attributes and the nodeName are not shared.\n *\n * @public\n * @extends AbstractType\n */\nexport class YXmlFragment extends AbstractType {\n constructor () {\n super()\n /**\n * @type {Array|null}\n */\n this._prelimContent = []\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n this.insert(0, /** @type {Array} */ (this._prelimContent))\n this._prelimContent = null\n }\n\n _copy () {\n return new YXmlFragment()\n }\n\n get length () {\n return this._prelimContent === null ? this._length : this._prelimContent.length\n }\n\n /**\n * Create a subtree of childNodes.\n *\n * @example\n * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div')\n * for (let node in walker) {\n * // `node` is a div node\n * nop(node)\n * }\n *\n * @param {function(AbstractType):boolean} filter Function that is called on each child element and\n * returns a Boolean indicating whether the child\n * is to be included in the subtree.\n * @return {YXmlTreeWalker} A subtree and a position within it.\n *\n * @public\n */\n createTreeWalker (filter) {\n return new YXmlTreeWalker(this, filter)\n }\n\n /**\n * Returns the first YXmlElement that matches the query.\n * Similar to DOM's {@link querySelector}.\n *\n * Query support:\n * - tagname\n * TODO:\n * - id\n * - attribute\n *\n * @param {CSS_Selector} query The query on the children.\n * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null.\n *\n * @public\n */\n querySelector (query) {\n query = query.toUpperCase()\n // @ts-ignore\n const iterator = new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query)\n const next = iterator.next()\n if (next.done) {\n return null\n } else {\n return next.value\n }\n }\n\n /**\n * Returns all YXmlElements that match the query.\n * Similar to Dom's {@link querySelectorAll}.\n *\n * @todo Does not yet support all queries. Currently only query by tagName.\n *\n * @param {CSS_Selector} query The query on the children\n * @return {Array} The elements that match this query.\n *\n * @public\n */\n querySelectorAll (query) {\n query = query.toUpperCase()\n // @ts-ignore\n return Array.from(new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query))\n }\n\n /**\n * Creates YXmlEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction))\n }\n\n /**\n * Get the string representation of all the children of this YXmlFragment.\n *\n * @return {string} The string representation of all children.\n */\n toString () {\n return typeListMap(this, xml => xml.toString()).join('')\n }\n\n /**\n * @return {string}\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks={}] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const fragment = _document.createDocumentFragment()\n if (binding !== undefined) {\n binding._createAssociation(fragment, this)\n }\n typeListForEach(this, xmlType => {\n fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null)\n })\n return fragment\n }\n\n /**\n * Inserts new content at an index.\n *\n * @example\n * // Insert character 'a' at position 0\n * xml.insert(0, [new Y.XmlText('text')])\n *\n * @param {number} index The index to insert content at\n * @param {Array} content The array of content\n */\n insert (index, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListInsertGenerics(transaction, this, index, content)\n })\n } else {\n // @ts-ignore _prelimContent is defined because this is not yet integrated\n this._prelimContent.splice(index, 0, ...content)\n }\n }\n\n /**\n * Deletes elements starting from an index.\n *\n * @param {number} index Index at which to start deleting elements\n * @param {number} [length=1] The number of elements to remove. Defaults to 1.\n */\n delete (index, length = 1) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListDelete(transaction, this, index, length)\n })\n } else {\n // @ts-ignore _prelimContent is defined because this is not yet integrated\n this._prelimContent.splice(index, length)\n }\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @return {Array}\n */\n toArray () {\n return typeListToArray(this)\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {AbstractUpdateEncoder} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlFragmentRefID)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {YXmlFragment}\n *\n * @private\n * @function\n */\nexport const readYXmlFragment = decoder => new YXmlFragment()\n","\nimport {\n YXmlFragment,\n transact,\n typeMapDelete,\n typeMapSet,\n typeMapGet,\n typeMapGetAll,\n typeListForEach,\n YXmlElementRefID,\n AbstractUpdateDecoder, AbstractUpdateEncoder, Snapshot, Doc, Item // eslint-disable-line\n} from '../internals.js'\n\n/**\n * An YXmlElement imitates the behavior of a\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}.\n *\n * * An YXmlElement has attributes (key value pairs)\n * * An YXmlElement has childElements that must inherit from YXmlElement\n */\nexport class YXmlElement extends YXmlFragment {\n constructor (nodeName = 'UNDEFINED') {\n super()\n this.nodeName = nodeName\n /**\n * @type {Map|null}\n */\n this._prelimAttrs = new Map()\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n ;(/** @type {Map} */ (this._prelimAttrs)).forEach((value, key) => {\n this.setAttribute(key, value)\n })\n this._prelimAttrs = null\n }\n\n /**\n * Creates an Item with the same effect as this Item (without position effect)\n *\n * @return {YXmlElement}\n */\n _copy () {\n return new YXmlElement(this.nodeName)\n }\n\n /**\n * Returns the XML serialization of this YXmlElement.\n * The attributes are ordered by attribute-name, so you can easily use this\n * method to compare YXmlElements\n *\n * @return {string} The string representation of this type.\n *\n * @public\n */\n toString () {\n const attrs = this.getAttributes()\n const stringBuilder = []\n const keys = []\n for (const key in attrs) {\n keys.push(key)\n }\n keys.sort()\n const keysLen = keys.length\n for (let i = 0; i < keysLen; i++) {\n const key = keys[i]\n stringBuilder.push(key + '=\"' + attrs[key] + '\"')\n }\n const nodeName = this.nodeName.toLocaleLowerCase()\n const attrsString = stringBuilder.length > 0 ? ' ' + stringBuilder.join(' ') : ''\n return `<${nodeName}${attrsString}>${super.toString()}`\n }\n\n /**\n * Removes an attribute from this YXmlElement.\n *\n * @param {String} attributeName The attribute name that is to be removed.\n *\n * @public\n */\n removeAttribute (attributeName) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, attributeName)\n })\n } else {\n /** @type {Map} */ (this._prelimAttrs).delete(attributeName)\n }\n }\n\n /**\n * Sets or updates an attribute.\n *\n * @param {String} attributeName The attribute name that is to be set.\n * @param {String} attributeValue The attribute value that is to be set.\n *\n * @public\n */\n setAttribute (attributeName, attributeValue) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, attributeName, attributeValue)\n })\n } else {\n /** @type {Map} */ (this._prelimAttrs).set(attributeName, attributeValue)\n }\n }\n\n /**\n * Returns an attribute value that belongs to the attribute name.\n *\n * @param {String} attributeName The attribute name that identifies the\n * queried value.\n * @return {String} The queried attribute value.\n *\n * @public\n */\n getAttribute (attributeName) {\n return /** @type {any} */ (typeMapGet(this, attributeName))\n }\n\n /**\n * Returns all attribute name/value pairs in a JSON Object.\n *\n * @param {Snapshot} [snapshot]\n * @return {Object} A JSON Object that describes the attributes.\n *\n * @public\n */\n getAttributes (snapshot) {\n return typeMapGetAll(this)\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks={}] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const dom = _document.createElement(this.nodeName)\n const attrs = this.getAttributes()\n for (const key in attrs) {\n dom.setAttribute(key, attrs[key])\n }\n typeListForEach(this, yxml => {\n dom.appendChild(yxml.toDOM(_document, hooks, binding))\n })\n if (binding !== undefined) {\n binding._createAssociation(dom, this)\n }\n return dom\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {AbstractUpdateEncoder} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlElementRefID)\n encoder.writeKey(this.nodeName)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {YXmlElement}\n *\n * @function\n */\nexport const readYXmlElement = decoder => new YXmlElement(decoder.readKey())\n","\nimport {\n YEvent,\n YXmlElement, YXmlFragment, Transaction // eslint-disable-line\n} from '../internals.js'\n\n/**\n * An Event that describes changes on a YXml Element or Yxml Fragment\n */\nexport class YXmlEvent extends YEvent {\n /**\n * @param {YXmlElement|YXmlFragment} target The target on which the event is created.\n * @param {Set} subs The set of changed attributes. `null` is included if the\n * child list changed.\n * @param {Transaction} transaction The transaction instance with wich the\n * change was created.\n */\n constructor (target, subs, transaction) {\n super(target, transaction)\n /**\n * Whether the children changed.\n * @type {Boolean}\n * @private\n */\n this.childListChanged = false\n /**\n * Set of all changed attributes.\n * @type {Set}\n */\n this.attributesChanged = new Set()\n subs.forEach((sub) => {\n if (sub === null) {\n this.childListChanged = true\n } else {\n this.attributesChanged.add(sub)\n }\n })\n }\n}\n","\nimport {\n YMap,\n YXmlHookRefID,\n AbstractUpdateDecoder, AbstractUpdateEncoder // eslint-disable-line\n} from '../internals.js'\n\n/**\n * You can manage binding to a custom type with YXmlHook.\n *\n * @extends {YMap}\n */\nexport class YXmlHook extends YMap {\n /**\n * @param {string} hookName nodeName of the Dom Node.\n */\n constructor (hookName) {\n super()\n /**\n * @type {string}\n */\n this.hookName = hookName\n }\n\n /**\n * Creates an Item with the same effect as this Item (without position effect)\n */\n _copy () {\n return new YXmlHook(this.hookName)\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object.} [hooks] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type\n * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const hook = hooks[this.hookName]\n let dom\n if (hook !== undefined) {\n dom = hook.createDom(this)\n } else {\n dom = document.createElement(this.hookName)\n }\n dom.setAttribute('data-yjs-hook', this.hookName)\n if (binding !== undefined) {\n binding._createAssociation(dom, this)\n }\n return dom\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {AbstractUpdateEncoder} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlHookRefID)\n encoder.writeKey(this.hookName)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {YXmlHook}\n *\n * @private\n * @function\n */\nexport const readYXmlHook = decoder =>\n new YXmlHook(decoder.readKey())\n","\nimport {\n YText,\n YXmlTextRefID,\n AbstractUpdateDecoder, AbstractUpdateEncoder // eslint-disable-line\n} from '../internals.js'\n\n/**\n * Represents text in a Dom Element. In the future this type will also handle\n * simple formatting information like bold and italic.\n */\nexport class YXmlText extends YText {\n _copy () {\n return new YXmlText()\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlText.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks, binding) {\n const dom = _document.createTextNode(this.toString())\n if (binding !== undefined) {\n binding._createAssociation(dom, this)\n }\n return dom\n }\n\n toString () {\n // @ts-ignore\n return this.toDelta().map(delta => {\n const nestedNodes = []\n for (const nodeName in delta.attributes) {\n const attrs = []\n for (const key in delta.attributes[nodeName]) {\n attrs.push({ key, value: delta.attributes[nodeName][key] })\n }\n // sort attributes to get a unique order\n attrs.sort((a, b) => a.key < b.key ? -1 : 1)\n nestedNodes.push({ nodeName, attrs })\n }\n // sort node order to get a unique order\n nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1)\n // now convert to dom string\n let str = ''\n for (let i = 0; i < nestedNodes.length; i++) {\n const node = nestedNodes[i]\n str += `<${node.nodeName}`\n for (let j = 0; j < node.attrs.length; j++) {\n const attr = node.attrs[j]\n str += ` ${attr.key}=\"${attr.value}\"`\n }\n str += '>'\n }\n str += delta.insert\n for (let i = nestedNodes.length - 1; i >= 0; i--) {\n str += ``\n }\n return str\n }).join('')\n }\n\n /**\n * @return {string}\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlTextRefID)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {YXmlText}\n *\n * @private\n * @function\n */\nexport const readYXmlText = decoder => new YXmlText()\n","\nimport {\n AbstractUpdateEncoder, ID, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error.js'\n\nexport class AbstractStruct {\n /**\n * @param {ID} id\n * @param {number} length\n */\n constructor (id, length) {\n this.id = id\n this.length = length\n }\n\n /**\n * @type {boolean}\n */\n get deleted () {\n throw error.methodUnimplemented()\n }\n\n /**\n * Merge this struct with the item to the right.\n * This method is already assuming that `this.id.clock + this.length === this.id.clock`.\n * Also this method does *not* remove right from StructStore!\n * @param {AbstractStruct} right\n * @return {boolean} wether this merged with right\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder The encoder to write data to.\n * @param {number} offset\n * @param {number} encodingRef\n */\n write (encoder, offset, encodingRef) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n throw error.methodUnimplemented()\n }\n}\n","\nimport {\n AbstractStruct,\n addStruct,\n AbstractUpdateEncoder, StructStore, Transaction, ID // eslint-disable-line\n} from '../internals.js'\n\nexport const structGCRefNumber = 0\n\n/**\n * @private\n */\nexport class GC extends AbstractStruct {\n get deleted () {\n return true\n }\n\n delete () {}\n\n /**\n * @param {GC} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.length += right.length\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n if (offset > 0) {\n this.id.clock += offset\n this.length -= offset\n }\n addStruct(transaction.doc.store, this)\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeInfo(structGCRefNumber)\n encoder.writeLen(this.length - offset)\n }\n\n /**\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n return null\n }\n}\n","import {\n AbstractUpdateDecoder, AbstractUpdateEncoder, StructStore, Item, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error.js'\n\nexport class ContentBinary {\n /**\n * @param {Uint8Array} content\n */\n constructor (content) {\n this.content = content\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.content]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentBinary}\n */\n copy () {\n return new ContentBinary(this.content)\n }\n\n /**\n * @param {number} offset\n * @return {ContentBinary}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentBinary} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeBuf(this.content)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 3\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentBinary}\n */\nexport const readContentBinary = decoder => new ContentBinary(decoder.readBuf())\n","\nimport {\n addToDeleteSet,\n AbstractUpdateDecoder, AbstractUpdateEncoder, StructStore, Item, Transaction // eslint-disable-line\n} from '../internals.js'\n\nexport class ContentDeleted {\n /**\n * @param {number} len\n */\n constructor (len) {\n this.len = len\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.len\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return []\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return false\n }\n\n /**\n * @return {ContentDeleted}\n */\n copy () {\n return new ContentDeleted(this.len)\n }\n\n /**\n * @param {number} offset\n * @return {ContentDeleted}\n */\n splice (offset) {\n const right = new ContentDeleted(this.len - offset)\n this.len = offset\n return right\n }\n\n /**\n * @param {ContentDeleted} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.len += right.len\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len)\n item.markDeleted()\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeLen(this.len - offset)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 1\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentDeleted}\n */\nexport const readContentDeleted = decoder => new ContentDeleted(decoder.readLen())\n","\nimport {\n Doc, AbstractUpdateDecoder, AbstractUpdateEncoder, StructStore, Transaction, Item // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error.js'\n\n/**\n * @private\n */\nexport class ContentDoc {\n /**\n * @param {Doc} doc\n */\n constructor (doc) {\n if (doc._item) {\n console.error('This document was already integrated as a sub-document. You should create a second instance instead with the same guid.')\n }\n /**\n * @type {Doc}\n */\n this.doc = doc\n /**\n * @type {any}\n */\n const opts = {}\n this.opts = opts\n if (!doc.gc) {\n opts.gc = false\n }\n if (doc.autoLoad) {\n opts.autoLoad = true\n }\n if (doc.meta !== null) {\n opts.meta = doc.meta\n }\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.doc]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentDoc}\n */\n copy () {\n return new ContentDoc(this.doc)\n }\n\n /**\n * @param {number} offset\n * @return {ContentDoc}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentDoc} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n // this needs to be reflected in doc.destroy as well\n this.doc._item = item\n transaction.subdocsAdded.add(this.doc)\n if (this.doc.shouldLoad) {\n transaction.subdocsLoaded.add(this.doc)\n }\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n if (transaction.subdocsAdded.has(this.doc)) {\n transaction.subdocsAdded.delete(this.doc)\n } else {\n transaction.subdocsRemoved.add(this.doc)\n }\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) { }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeString(this.doc.guid)\n encoder.writeAny(this.opts)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 9\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentDoc}\n */\nexport const readContentDoc = decoder => new ContentDoc(new Doc({ guid: decoder.readString(), ...decoder.readAny() }))\n","\nimport {\n AbstractUpdateDecoder, AbstractUpdateEncoder, StructStore, Item, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error.js'\n\n/**\n * @private\n */\nexport class ContentEmbed {\n /**\n * @param {Object} embed\n */\n constructor (embed) {\n this.embed = embed\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.embed]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentEmbed}\n */\n copy () {\n return new ContentEmbed(this.embed)\n }\n\n /**\n * @param {number} offset\n * @return {ContentEmbed}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentEmbed} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeJSON(this.embed)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 5\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentEmbed}\n */\nexport const readContentEmbed = decoder => new ContentEmbed(decoder.readJSON())\n","\nimport {\n AbstractType, AbstractUpdateDecoder, AbstractUpdateEncoder, Item, StructStore, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error.js'\n\n/**\n * @private\n */\nexport class ContentFormat {\n /**\n * @param {string} key\n * @param {Object} value\n */\n constructor (key, value) {\n this.key = key\n this.value = value\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return []\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return false\n }\n\n /**\n * @return {ContentFormat}\n */\n copy () {\n return new ContentFormat(this.key, this.value)\n }\n\n /**\n * @param {number} offset\n * @return {ContentFormat}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentFormat} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n // @todo searchmarker are currently unsupported for rich text documents\n /** @type {AbstractType} */ (item.parent)._searchMarker = null\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeKey(this.key)\n encoder.writeJSON(this.value)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 6\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentFormat}\n */\nexport const readContentFormat = decoder => new ContentFormat(decoder.readString(), decoder.readJSON())\n","import {\n AbstractUpdateDecoder, AbstractUpdateEncoder, Transaction, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @private\n */\nexport class ContentJSON {\n /**\n * @param {Array} arr\n */\n constructor (arr) {\n /**\n * @type {Array}\n */\n this.arr = arr\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.arr.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.arr\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentJSON}\n */\n copy () {\n return new ContentJSON(this.arr)\n }\n\n /**\n * @param {number} offset\n * @return {ContentJSON}\n */\n splice (offset) {\n const right = new ContentJSON(this.arr.slice(offset))\n this.arr = this.arr.slice(0, offset)\n return right\n }\n\n /**\n * @param {ContentJSON} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.arr = this.arr.concat(right.arr)\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n const len = this.arr.length\n encoder.writeLen(len - offset)\n for (let i = offset; i < len; i++) {\n const c = this.arr[i]\n encoder.writeString(c === undefined ? 'undefined' : JSON.stringify(c))\n }\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 2\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentJSON}\n */\nexport const readContentJSON = decoder => {\n const len = decoder.readLen()\n const cs = []\n for (let i = 0; i < len; i++) {\n const c = decoder.readString()\n if (c === 'undefined') {\n cs.push(undefined)\n } else {\n cs.push(JSON.parse(c))\n }\n }\n return new ContentJSON(cs)\n}\n","import {\n AbstractUpdateDecoder, AbstractUpdateEncoder, Transaction, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\nexport class ContentAny {\n /**\n * @param {Array} arr\n */\n constructor (arr) {\n /**\n * @type {Array}\n */\n this.arr = arr\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.arr.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.arr\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentAny}\n */\n copy () {\n return new ContentAny(this.arr)\n }\n\n /**\n * @param {number} offset\n * @return {ContentAny}\n */\n splice (offset) {\n const right = new ContentAny(this.arr.slice(offset))\n this.arr = this.arr.slice(0, offset)\n return right\n }\n\n /**\n * @param {ContentAny} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.arr = this.arr.concat(right.arr)\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n const len = this.arr.length\n encoder.writeLen(len - offset)\n for (let i = offset; i < len; i++) {\n const c = this.arr[i]\n encoder.writeAny(c)\n }\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 8\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentAny}\n */\nexport const readContentAny = decoder => {\n const len = decoder.readLen()\n const cs = []\n for (let i = 0; i < len; i++) {\n cs.push(decoder.readAny())\n }\n return new ContentAny(cs)\n}\n","import {\n AbstractUpdateDecoder, AbstractUpdateEncoder, Transaction, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @private\n */\nexport class ContentString {\n /**\n * @param {string} str\n */\n constructor (str) {\n /**\n * @type {string}\n */\n this.str = str\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.str.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.str.split('')\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentString}\n */\n copy () {\n return new ContentString(this.str)\n }\n\n /**\n * @param {number} offset\n * @return {ContentString}\n */\n splice (offset) {\n const right = new ContentString(this.str.slice(offset))\n this.str = this.str.slice(0, offset)\n\n // Prevent encoding invalid documents because of splitting of surrogate pairs: https://github.com/yjs/yjs/issues/248\n const firstCharCode = this.str.charCodeAt(offset - 1)\n if (firstCharCode >= 0xD800 && firstCharCode <= 0xDBFF) {\n // Last character of the left split is the start of a surrogate utf16/ucs2 pair.\n // We don't support splitting of surrogate pairs because this may lead to invalid documents.\n // Replace the invalid character with a unicode replacement character (� / U+FFFD)\n this.str = this.str.slice(0, offset - 1) + '�'\n // replace right as well\n right.str = '�' + right.str.slice(1)\n }\n return right\n }\n\n /**\n * @param {ContentString} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.str += right.str\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeString(offset === 0 ? this.str : this.str.slice(offset))\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 4\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentString}\n */\nexport const readContentString = decoder => new ContentString(decoder.readString())\n","\nimport {\n readYArray,\n readYMap,\n readYText,\n readYXmlElement,\n readYXmlFragment,\n readYXmlHook,\n readYXmlText,\n AbstractUpdateDecoder, AbstractUpdateEncoder, StructStore, Transaction, Item, YEvent, AbstractType // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error.js'\n\n/**\n * @type {Array>}\n * @private\n */\nexport const typeRefs = [\n readYArray,\n readYMap,\n readYText,\n readYXmlElement,\n readYXmlFragment,\n readYXmlHook,\n readYXmlText\n]\n\nexport const YArrayRefID = 0\nexport const YMapRefID = 1\nexport const YTextRefID = 2\nexport const YXmlElementRefID = 3\nexport const YXmlFragmentRefID = 4\nexport const YXmlHookRefID = 5\nexport const YXmlTextRefID = 6\n\n/**\n * @private\n */\nexport class ContentType {\n /**\n * @param {AbstractType} type\n */\n constructor (type) {\n /**\n * @type {AbstractType}\n */\n this.type = type\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.type]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentType}\n */\n copy () {\n return new ContentType(this.type._copy())\n }\n\n /**\n * @param {number} offset\n * @return {ContentType}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentType} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n this.type._integrate(transaction.doc, item)\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n let item = this.type._start\n while (item !== null) {\n if (!item.deleted) {\n item.delete(transaction)\n } else {\n // Whis will be gc'd later and we want to merge it if possible\n // We try to merge all deleted items after each transaction,\n // but we have no knowledge about that this needs to be merged\n // since it is not in transaction.ds. Hence we add it to transaction._mergeStructs\n transaction._mergeStructs.push(item)\n }\n item = item.right\n }\n this.type._map.forEach(item => {\n if (!item.deleted) {\n item.delete(transaction)\n } else {\n // same as above\n transaction._mergeStructs.push(item)\n }\n })\n transaction.changed.delete(this.type)\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) {\n let item = this.type._start\n while (item !== null) {\n item.gc(store, true)\n item = item.right\n }\n this.type._start = null\n this.type._map.forEach(/** @param {Item | null} item */ (item) => {\n while (item !== null) {\n item.gc(store, true)\n item = item.left\n }\n })\n this.type._map = new Map()\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n this.type._write(encoder)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 7\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentType}\n */\nexport const readContentType = decoder => new ContentType(typeRefs[decoder.readTypeRef()](decoder))\n","\nimport {\n GC,\n getState,\n AbstractStruct,\n replaceStruct,\n addStruct,\n addToDeleteSet,\n findRootTypeKey,\n compareIDs,\n getItem,\n getItemCleanEnd,\n getItemCleanStart,\n readContentDeleted,\n readContentBinary,\n readContentJSON,\n readContentAny,\n readContentString,\n readContentEmbed,\n readContentDoc,\n createID,\n readContentFormat,\n readContentType,\n addChangedTypeToTransaction,\n AbstractUpdateDecoder, AbstractUpdateEncoder, ContentType, ContentDeleted, StructStore, ID, AbstractType, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error.js'\nimport * as binary from 'lib0/binary.js'\n\n/**\n * @todo This should return several items\n *\n * @param {StructStore} store\n * @param {ID} id\n * @return {{item:Item, diff:number}}\n */\nexport const followRedone = (store, id) => {\n /**\n * @type {ID|null}\n */\n let nextID = id\n let diff = 0\n let item\n do {\n if (diff > 0) {\n nextID = createID(nextID.client, nextID.clock + diff)\n }\n item = getItem(store, nextID)\n diff = nextID.clock - item.id.clock\n nextID = item.redone\n } while (nextID !== null && item instanceof Item)\n return {\n item, diff\n }\n}\n\n/**\n * Make sure that neither item nor any of its parents is ever deleted.\n *\n * This property does not persist when storing it into a database or when\n * sending it to other peers\n *\n * @param {Item|null} item\n * @param {boolean} keep\n */\nexport const keepItem = (item, keep) => {\n while (item !== null && item.keep !== keep) {\n item.keep = keep\n item = /** @type {AbstractType} */ (item.parent)._item\n }\n}\n\n/**\n * Split leftItem into two items\n * @param {Transaction} transaction\n * @param {Item} leftItem\n * @param {number} diff\n * @return {Item}\n *\n * @function\n * @private\n */\nexport const splitItem = (transaction, leftItem, diff) => {\n // create rightItem\n const { client, clock } = leftItem.id\n const rightItem = new Item(\n createID(client, clock + diff),\n leftItem,\n createID(client, clock + diff - 1),\n leftItem.right,\n leftItem.rightOrigin,\n leftItem.parent,\n leftItem.parentSub,\n leftItem.content.splice(diff)\n )\n if (leftItem.deleted) {\n rightItem.markDeleted()\n }\n if (leftItem.keep) {\n rightItem.keep = true\n }\n if (leftItem.redone !== null) {\n rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff)\n }\n // update left (do not set leftItem.rightOrigin as it will lead to problems when syncing)\n leftItem.right = rightItem\n // update right\n if (rightItem.right !== null) {\n rightItem.right.left = rightItem\n }\n // right is more specific.\n transaction._mergeStructs.push(rightItem)\n // update parent._map\n if (rightItem.parentSub !== null && rightItem.right === null) {\n /** @type {AbstractType} */ (rightItem.parent)._map.set(rightItem.parentSub, rightItem)\n }\n leftItem.length = diff\n return rightItem\n}\n\n/**\n * Redoes the effect of this operation.\n *\n * @param {Transaction} transaction The Yjs instance.\n * @param {Item} item\n * @param {Set} redoitems\n *\n * @return {Item|null}\n *\n * @private\n */\nexport const redoItem = (transaction, item, redoitems) => {\n const doc = transaction.doc\n const store = doc.store\n const ownClientID = doc.clientID\n const redone = item.redone\n if (redone !== null) {\n return getItemCleanStart(transaction, redone)\n }\n let parentItem = /** @type {AbstractType} */ (item.parent)._item\n /**\n * @type {Item|null}\n */\n let left\n /**\n * @type {Item|null}\n */\n let right\n if (item.parentSub === null) {\n // Is an array item. Insert at the old position\n left = item.left\n right = item\n } else {\n // Is a map item. Insert as current value\n left = item\n while (left.right !== null) {\n left = left.right\n if (left.id.client !== ownClientID) {\n // It is not possible to redo this item because it conflicts with a\n // change from another client\n return null\n }\n }\n if (left.right !== null) {\n left = /** @type {Item} */ (/** @type {AbstractType} */ (item.parent)._map.get(item.parentSub))\n }\n right = null\n }\n // make sure that parent is redone\n if (parentItem !== null && parentItem.deleted === true && parentItem.redone === null) {\n // try to undo parent if it will be undone anyway\n if (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems) === null) {\n return null\n }\n }\n if (parentItem !== null && parentItem.redone !== null) {\n while (parentItem.redone !== null) {\n parentItem = getItemCleanStart(transaction, parentItem.redone)\n }\n // find next cloned_redo items\n while (left !== null) {\n /**\n * @type {Item|null}\n */\n let leftTrace = left\n // trace redone until parent matches\n while (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item !== parentItem) {\n leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone)\n }\n if (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item === parentItem) {\n left = leftTrace\n break\n }\n left = left.left\n }\n while (right !== null) {\n /**\n * @type {Item|null}\n */\n let rightTrace = right\n // trace redone until parent matches\n while (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item !== parentItem) {\n rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone)\n }\n if (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item === parentItem) {\n right = rightTrace\n break\n }\n right = right.right\n }\n }\n const nextClock = getState(store, ownClientID)\n const nextId = createID(ownClientID, nextClock)\n const redoneItem = new Item(\n nextId,\n left, left && left.lastId,\n right, right && right.id,\n parentItem === null ? item.parent : /** @type {ContentType} */ (parentItem.content).type,\n item.parentSub,\n item.content.copy()\n )\n item.redone = nextId\n keepItem(redoneItem, true)\n redoneItem.integrate(transaction, 0)\n return redoneItem\n}\n\n/**\n * Abstract class that represents any content.\n */\nexport class Item extends AbstractStruct {\n /**\n * @param {ID} id\n * @param {Item | null} left\n * @param {ID | null} origin\n * @param {Item | null} right\n * @param {ID | null} rightOrigin\n * @param {AbstractType|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it.\n * @param {string | null} parentSub\n * @param {AbstractContent} content\n */\n constructor (id, left, origin, right, rightOrigin, parent, parentSub, content) {\n super(id, content.getLength())\n /**\n * The item that was originally to the left of this item.\n * @type {ID | null}\n */\n this.origin = origin\n /**\n * The item that is currently to the left of this item.\n * @type {Item | null}\n */\n this.left = left\n /**\n * The item that is currently to the right of this item.\n * @type {Item | null}\n */\n this.right = right\n /**\n * The item that was originally to the right of this item.\n * @type {ID | null}\n */\n this.rightOrigin = rightOrigin\n /**\n * @type {AbstractType|ID|null}\n */\n this.parent = parent\n /**\n * If the parent refers to this item with some kind of key (e.g. YMap, the\n * key is specified here. The key is then used to refer to the list in which\n * to insert this item. If `parentSub = null` type._start is the list in\n * which to insert to. Otherwise it is `parent._map`.\n * @type {String | null}\n */\n this.parentSub = parentSub\n /**\n * If this type's effect is reundone this type refers to the type that undid\n * this operation.\n * @type {ID | null}\n */\n this.redone = null\n /**\n * @type {AbstractContent}\n */\n this.content = content\n /**\n * bit1: keep\n * bit2: countable\n * bit3: deleted\n * bit4: mark - mark node as fast-search-marker\n * @type {number} byte\n */\n this.info = this.content.isCountable() ? binary.BIT2 : 0\n }\n\n /**\n * This is used to mark the item as an indexed fast-search marker\n *\n * @type {boolean}\n */\n set marker (isMarked) {\n if (((this.info & binary.BIT4) > 0) !== isMarked) {\n this.info ^= binary.BIT4\n }\n }\n\n get marker () {\n return (this.info & binary.BIT4) > 0\n }\n\n /**\n * If true, do not garbage collect this Item.\n */\n get keep () {\n return (this.info & binary.BIT1) > 0\n }\n\n set keep (doKeep) {\n if (this.keep !== doKeep) {\n this.info ^= binary.BIT1\n }\n }\n\n get countable () {\n return (this.info & binary.BIT2) > 0\n }\n\n /**\n * Whether this item was deleted or not.\n * @type {Boolean}\n */\n get deleted () {\n return (this.info & binary.BIT3) > 0\n }\n\n set deleted (doDelete) {\n if (this.deleted !== doDelete) {\n this.info ^= binary.BIT3\n }\n }\n\n markDeleted () {\n this.info |= binary.BIT3\n }\n\n /**\n * Return the creator clientID of the missing op or define missing items and return null.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) {\n return this.origin.client\n }\n if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) {\n return this.rightOrigin.client\n }\n if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) {\n return this.parent.client\n }\n\n // We have all missing ids, now find the items\n\n if (this.origin) {\n this.left = getItemCleanEnd(transaction, store, this.origin)\n this.origin = this.left.lastId\n }\n if (this.rightOrigin) {\n this.right = getItemCleanStart(transaction, this.rightOrigin)\n this.rightOrigin = this.right.id\n }\n if ((this.left && this.left.constructor === GC) || (this.right && this.right.constructor === GC)) {\n this.parent = null\n }\n // only set parent if this shouldn't be garbage collected\n if (!this.parent) {\n if (this.left && this.left.constructor === Item) {\n this.parent = this.left.parent\n this.parentSub = this.left.parentSub\n }\n if (this.right && this.right.constructor === Item) {\n this.parent = this.right.parent\n this.parentSub = this.right.parentSub\n }\n } else if (this.parent.constructor === ID) {\n const parentItem = getItem(store, this.parent)\n if (parentItem.constructor === GC) {\n this.parent = null\n } else {\n this.parent = /** @type {ContentType} */ (parentItem.content).type\n }\n }\n return null\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n if (offset > 0) {\n this.id.clock += offset\n this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1))\n this.origin = this.left.lastId\n this.content = this.content.splice(offset)\n this.length -= offset\n }\n\n if (this.parent) {\n if ((!this.left && (!this.right || this.right.left !== null)) || (this.left && this.left.right !== this.right)) {\n /**\n * @type {Item|null}\n */\n let left = this.left\n\n /**\n * @type {Item|null}\n */\n let o\n // set o to the first conflicting item\n if (left !== null) {\n o = left.right\n } else if (this.parentSub !== null) {\n o = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null\n while (o !== null && o.left !== null) {\n o = o.left\n }\n } else {\n o = /** @type {AbstractType} */ (this.parent)._start\n }\n // TODO: use something like DeleteSet here (a tree implementation would be best)\n // @todo use global set definitions\n /**\n * @type {Set}\n */\n const conflictingItems = new Set()\n /**\n * @type {Set}\n */\n const itemsBeforeOrigin = new Set()\n // Let c in conflictingItems, b in itemsBeforeOrigin\n // ***{origin}bbbb{this}{c,b}{c,b}{o}***\n // Note that conflictingItems is a subset of itemsBeforeOrigin\n while (o !== null && o !== this.right) {\n itemsBeforeOrigin.add(o)\n conflictingItems.add(o)\n if (compareIDs(this.origin, o.origin)) {\n // case 1\n if (o.id.client < this.id.client) {\n left = o\n conflictingItems.clear()\n } else if (compareIDs(this.rightOrigin, o.rightOrigin)) {\n // this and o are conflicting and point to the same integration points. The id decides which item comes first.\n // Since this is to the left of o, we can break here\n break\n } // else, o might be integrated before an item that this conflicts with. If so, we will find it in the next iterations\n } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) { // use getItem instead of getItemCleanEnd because we don't want / need to split items.\n // case 2\n if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) {\n left = o\n conflictingItems.clear()\n }\n } else {\n break\n }\n o = o.right\n }\n this.left = left\n }\n // reconnect left/right + update parent map/start if necessary\n if (this.left !== null) {\n const right = this.left.right\n this.right = right\n this.left.right = this\n } else {\n let r\n if (this.parentSub !== null) {\n r = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null\n while (r !== null && r.left !== null) {\n r = r.left\n }\n } else {\n r = /** @type {AbstractType} */ (this.parent)._start\n ;/** @type {AbstractType} */ (this.parent)._start = this\n }\n this.right = r\n }\n if (this.right !== null) {\n this.right.left = this\n } else if (this.parentSub !== null) {\n // set as current parent value if right === null and this is parentSub\n /** @type {AbstractType} */ (this.parent)._map.set(this.parentSub, this)\n if (this.left !== null) {\n // this is the current attribute value of parent. delete right\n this.left.delete(transaction)\n }\n }\n // adjust length of parent\n if (this.parentSub === null && this.countable && !this.deleted) {\n /** @type {AbstractType} */ (this.parent)._length += this.length\n }\n addStruct(transaction.doc.store, this)\n this.content.integrate(transaction, this)\n // add parent to transaction.changed\n addChangedTypeToTransaction(transaction, /** @type {AbstractType} */ (this.parent), this.parentSub)\n if ((/** @type {AbstractType} */ (this.parent)._item !== null && /** @type {AbstractType} */ (this.parent)._item.deleted) || (this.parentSub !== null && this.right !== null)) {\n // delete if parent is deleted or if this is not the current attribute value of parent\n this.delete(transaction)\n }\n } else {\n // parent is not defined. Integrate GC struct instead\n new GC(this.id, this.length).integrate(transaction, 0)\n }\n }\n\n /**\n * Returns the next non-deleted item\n */\n get next () {\n let n = this.right\n while (n !== null && n.deleted) {\n n = n.right\n }\n return n\n }\n\n /**\n * Returns the previous non-deleted item\n */\n get prev () {\n let n = this.left\n while (n !== null && n.deleted) {\n n = n.left\n }\n return n\n }\n\n /**\n * Computes the last content address of this Item.\n */\n get lastId () {\n // allocating ids is pretty costly because of the amount of ids created, so we try to reuse whenever possible\n return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1)\n }\n\n /**\n * Try to merge two items\n *\n * @param {Item} right\n * @return {boolean}\n */\n mergeWith (right) {\n if (\n compareIDs(right.origin, this.lastId) &&\n this.right === right &&\n compareIDs(this.rightOrigin, right.rightOrigin) &&\n this.id.client === right.id.client &&\n this.id.clock + this.length === right.id.clock &&\n this.deleted === right.deleted &&\n this.redone === null &&\n right.redone === null &&\n this.content.constructor === right.content.constructor &&\n this.content.mergeWith(right.content)\n ) {\n if (right.keep) {\n this.keep = true\n }\n this.right = right.right\n if (this.right !== null) {\n this.right.left = this\n }\n this.length += right.length\n return true\n }\n return false\n }\n\n /**\n * Mark this Item as deleted.\n *\n * @param {Transaction} transaction\n */\n delete (transaction) {\n if (!this.deleted) {\n const parent = /** @type {AbstractType} */ (this.parent)\n // adjust the length of parent\n if (this.countable && this.parentSub === null) {\n parent._length -= this.length\n }\n this.markDeleted()\n addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length)\n addChangedTypeToTransaction(transaction, parent, this.parentSub)\n this.content.delete(transaction)\n }\n }\n\n /**\n * @param {StructStore} store\n * @param {boolean} parentGCd\n */\n gc (store, parentGCd) {\n if (!this.deleted) {\n throw error.unexpectedCase()\n }\n this.content.gc(store)\n if (parentGCd) {\n replaceStruct(store, this, new GC(this.id, this.length))\n } else {\n this.content = new ContentDeleted(this.length)\n }\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {AbstractUpdateEncoder} encoder The encoder to write data to.\n * @param {number} offset\n */\n write (encoder, offset) {\n const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin\n const rightOrigin = this.rightOrigin\n const parentSub = this.parentSub\n const info = (this.content.getRef() & binary.BITS5) |\n (origin === null ? 0 : binary.BIT8) | // origin is defined\n (rightOrigin === null ? 0 : binary.BIT7) | // right origin is defined\n (parentSub === null ? 0 : binary.BIT6) // parentSub is non-null\n encoder.writeInfo(info)\n if (origin !== null) {\n encoder.writeLeftID(origin)\n }\n if (rightOrigin !== null) {\n encoder.writeRightID(rightOrigin)\n }\n if (origin === null && rightOrigin === null) {\n const parent = /** @type {AbstractType} */ (this.parent)\n const parentItem = parent._item\n if (parentItem === null) {\n // parent type on y._map\n // find the correct key\n const ykey = findRootTypeKey(parent)\n encoder.writeParentInfo(true) // write parentYKey\n encoder.writeString(ykey)\n } else {\n encoder.writeParentInfo(false) // write parent id\n encoder.writeLeftID(parentItem.id)\n }\n if (parentSub !== null) {\n encoder.writeString(parentSub)\n }\n }\n this.content.write(encoder, offset)\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @param {number} info\n */\nexport const readItemContent = (decoder, info) => contentRefs[info & binary.BITS5](decoder)\n\n/**\n * A lookup map for reading Item content.\n *\n * @type {Array}\n */\nexport const contentRefs = [\n () => { throw error.unexpectedCase() }, // GC is not ItemContent\n readContentDeleted, // 1\n readContentJSON, // 2\n readContentBinary, // 3\n readContentString, // 4\n readContentEmbed, // 5\n readContentFormat, // 6\n readContentType, // 7\n readContentAny, // 8\n readContentDoc // 9\n]\n\n/**\n * Do not implement this class!\n */\nexport class AbstractContent {\n /**\n * @return {number}\n */\n getLength () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n throw error.methodUnimplemented()\n }\n\n /**\n * Should return false if this Item is some kind of meta information\n * (e.g. format information).\n *\n * * Whether this Item should be addressable via `yarray.get(i)`\n * * Whether this Item should be counted when computing yarray.length\n *\n * @return {boolean}\n */\n isCountable () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {AbstractContent}\n */\n copy () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {number} offset\n * @return {AbstractContent}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {AbstractContent} right\n * @return {boolean}\n */\n mergeWith (right) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {number}\n */\n getRef () {\n throw error.methodUnimplemented()\n }\n}\n","/**\n * @module sync-protocol\n */\n\nimport * as encoding from 'lib0/encoding.js'\nimport * as decoding from 'lib0/decoding.js'\nimport * as Y from 'yjs'\n\n/**\n * @typedef {Map} StateMap\n */\n\n/**\n * Core Yjs defines three message types:\n * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.\n * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the the client is assured that\n * it received all information from the remote client.\n *\n * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection\n * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both\n * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.\n *\n * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.\n * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies\n * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the\n * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can\n * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them.\n * Therefore it is necesarry that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep1)\n const sv = Y.encodeStateVector(doc)\n encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep2)\n encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin) => {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n encoding.writeVarUint(encoder, messageYjsUpdate)\n encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {\n const messageType = decoding.readVarUint(decoder)\n switch (messageType) {\n case messageYjsSyncStep1:\n readSyncStep1(decoder, encoder, doc)\n break\n case messageYjsSyncStep2:\n readSyncStep2(decoder, doc, transactionOrigin)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n","\nimport * as t from 'lib0/testing.js'\nimport * as prng from 'lib0/prng.js'\nimport * as encoding from 'lib0/encoding.js'\nimport * as decoding from 'lib0/decoding.js'\nimport * as syncProtocol from 'y-protocols/sync.js'\nimport * as object from 'lib0/object.js'\nimport * as Y from '../src/internals.js'\nexport * from '../src/internals.js'\n\nif (typeof window !== 'undefined') {\n // @ts-ignore\n window.Y = Y // eslint-disable-line\n}\n\n/**\n * @param {TestYInstance} y // publish message created by `y` to all other online clients\n * @param {Uint8Array} m\n */\nconst broadcastMessage = (y, m) => {\n if (y.tc.onlineConns.has(y)) {\n y.tc.onlineConns.forEach(remoteYInstance => {\n if (remoteYInstance !== y) {\n remoteYInstance._receive(m, y)\n }\n })\n }\n}\n\nexport class TestYInstance extends Y.Doc {\n /**\n * @param {TestConnector} testConnector\n * @param {number} clientID\n */\n constructor (testConnector, clientID) {\n super()\n this.userID = clientID // overwriting clientID\n /**\n * @type {TestConnector}\n */\n this.tc = testConnector\n /**\n * @type {Map>}\n */\n this.receiving = new Map()\n testConnector.allConns.add(this)\n // set up observe on local model\n this.on('update', /** @param {Uint8Array} update @param {any} origin */ (update, origin) => {\n if (origin !== testConnector) {\n const encoder = encoding.createEncoder()\n syncProtocol.writeUpdate(encoder, update)\n broadcastMessage(this, encoding.toUint8Array(encoder))\n }\n })\n this.connect()\n }\n\n /**\n * Disconnect from TestConnector.\n */\n disconnect () {\n this.receiving = new Map()\n this.tc.onlineConns.delete(this)\n }\n\n /**\n * Append yourself to the list of known Y instances in testconnector.\n * Also initiate sync with all clients.\n */\n connect () {\n if (!this.tc.onlineConns.has(this)) {\n this.tc.onlineConns.add(this)\n const encoder = encoding.createEncoder()\n syncProtocol.writeSyncStep1(encoder, this)\n // publish SyncStep1\n broadcastMessage(this, encoding.toUint8Array(encoder))\n this.tc.onlineConns.forEach(remoteYInstance => {\n if (remoteYInstance !== this) {\n // remote instance sends instance to this instance\n const encoder = encoding.createEncoder()\n syncProtocol.writeSyncStep1(encoder, remoteYInstance)\n this._receive(encoding.toUint8Array(encoder), remoteYInstance)\n }\n })\n }\n }\n\n /**\n * Receive a message from another client. This message is only appended to the list of receiving messages.\n * TestConnector decides when this client actually reads this message.\n *\n * @param {Uint8Array} message\n * @param {TestYInstance} remoteClient\n */\n _receive (message, remoteClient) {\n let messages = this.receiving.get(remoteClient)\n if (messages === undefined) {\n messages = []\n this.receiving.set(remoteClient, messages)\n }\n messages.push(message)\n }\n}\n\n/**\n * Keeps track of TestYInstances.\n *\n * The TestYInstances add/remove themselves from the list of connections maiained in this object.\n * I think it makes sense. Deal with it.\n */\nexport class TestConnector {\n /**\n * @param {prng.PRNG} gen\n */\n constructor (gen) {\n /**\n * @type {Set}\n */\n this.allConns = new Set()\n /**\n * @type {Set}\n */\n this.onlineConns = new Set()\n /**\n * @type {prng.PRNG}\n */\n this.prng = gen\n }\n\n /**\n * Create a new Y instance and add it to the list of connections\n * @param {number} clientID\n */\n createY (clientID) {\n return new TestYInstance(this, clientID)\n }\n\n /**\n * Choose random connection and flush a random message from a random sender.\n *\n * If this function was unable to flush a message, because there are no more messages to flush, it returns false. true otherwise.\n * @return {boolean}\n */\n flushRandomMessage () {\n const gen = this.prng\n const conns = Array.from(this.onlineConns).filter(conn => conn.receiving.size > 0)\n if (conns.length > 0) {\n const receiver = prng.oneOf(gen, conns)\n const [sender, messages] = prng.oneOf(gen, Array.from(receiver.receiving))\n const m = messages.shift()\n if (messages.length === 0) {\n receiver.receiving.delete(sender)\n }\n if (m === undefined) {\n return this.flushRandomMessage()\n }\n const encoder = encoding.createEncoder()\n // console.log('receive (' + sender.userID + '->' + receiver.userID + '):\\n', syncProtocol.stringifySyncMessage(decoding.createDecoder(m), receiver))\n // do not publish data created when this function is executed (could be ss2 or update message)\n syncProtocol.readSyncMessage(decoding.createDecoder(m), encoder, receiver, receiver.tc)\n if (encoding.length(encoder) > 0) {\n // send reply message\n sender._receive(encoding.toUint8Array(encoder), receiver)\n }\n return true\n }\n return false\n }\n\n /**\n * @return {boolean} True iff this function actually flushed something\n */\n flushAllMessages () {\n let didSomething = false\n while (this.flushRandomMessage()) {\n didSomething = true\n }\n return didSomething\n }\n\n reconnectAll () {\n this.allConns.forEach(conn => conn.connect())\n }\n\n disconnectAll () {\n this.allConns.forEach(conn => conn.disconnect())\n }\n\n syncAll () {\n this.reconnectAll()\n this.flushAllMessages()\n }\n\n /**\n * @return {boolean} Whether it was possible to disconnect a randon connection.\n */\n disconnectRandom () {\n if (this.onlineConns.size === 0) {\n return false\n }\n prng.oneOf(this.prng, Array.from(this.onlineConns)).disconnect()\n return true\n }\n\n /**\n * @return {boolean} Whether it was possible to reconnect a random connection.\n */\n reconnectRandom () {\n /**\n * @type {Array}\n */\n const reconnectable = []\n this.allConns.forEach(conn => {\n if (!this.onlineConns.has(conn)) {\n reconnectable.push(conn)\n }\n })\n if (reconnectable.length === 0) {\n return false\n }\n prng.oneOf(this.prng, reconnectable).connect()\n return true\n }\n}\n\n/**\n * @template T\n * @param {t.TestCase} tc\n * @param {{users?:number}} conf\n * @param {InitTestObjectCallback} [initTestObject]\n * @return {{testObjects:Array,testConnector:TestConnector,users:Array,array0:Y.YArray,array1:Y.YArray,array2:Y.YArray,map0:Y.YMap,map1:Y.YMap,map2:Y.YMap,map3:Y.YMap,text0:Y.YText,text1:Y.YText,text2:Y.YText,xml0:Y.YXmlElement,xml1:Y.YXmlElement,xml2:Y.YXmlElement}}\n */\nexport const init = (tc, { users = 5 } = {}, initTestObject) => {\n /**\n * @type {Object}\n */\n const result = {\n users: []\n }\n const gen = tc.prng\n // choose an encoding approach at random\n if (prng.bool(gen)) {\n Y.useV2Encoding()\n } else {\n Y.useV1Encoding()\n }\n\n const testConnector = new TestConnector(gen)\n result.testConnector = testConnector\n for (let i = 0; i < users; i++) {\n const y = testConnector.createY(i)\n y.clientID = i\n result.users.push(y)\n result['array' + i] = y.getArray('array')\n result['map' + i] = y.getMap('map')\n result['xml' + i] = y.get('xml', Y.YXmlElement)\n result['text' + i] = y.getText('text')\n }\n testConnector.syncAll()\n result.testObjects = result.users.map(initTestObject || (() => null))\n Y.useV1Encoding()\n return /** @type {any} */ (result)\n}\n\n/**\n * 1. reconnect and flush all\n * 2. user 0 gc\n * 3. get type content\n * 4. disconnect & reconnect all (so gc is propagated)\n * 5. compare os, ds, ss\n *\n * @param {Array} users\n */\nexport const compare = users => {\n users.forEach(u => u.connect())\n while (users[0].tc.flushAllMessages()) {}\n const userArrayValues = users.map(u => u.getArray('array').toJSON())\n const userMapValues = users.map(u => u.getMap('map').toJSON())\n const userXmlValues = users.map(u => u.get('xml', Y.YXmlElement).toString())\n const userTextValues = users.map(u => u.getText('text').toDelta())\n for (const u of users) {\n t.assert(u.store.pendingDeleteReaders.length === 0)\n t.assert(u.store.pendingStack.length === 0)\n t.assert(u.store.pendingClientsStructRefs.size === 0)\n }\n // Test Array iterator\n t.compare(users[0].getArray('array').toArray(), Array.from(users[0].getArray('array')))\n // Test Map iterator\n const ymapkeys = Array.from(users[0].getMap('map').keys())\n t.assert(ymapkeys.length === Object.keys(userMapValues[0]).length)\n ymapkeys.forEach(key => t.assert(object.hasProperty(userMapValues[0], key)))\n /**\n * @type {Object}\n */\n const mapRes = {}\n for (const [k, v] of users[0].getMap('map')) {\n mapRes[k] = v instanceof Y.AbstractType ? v.toJSON() : v\n }\n t.compare(userMapValues[0], mapRes)\n // Compare all users\n for (let i = 0; i < users.length - 1; i++) {\n t.compare(userArrayValues[i].length, users[i].getArray('array').length)\n t.compare(userArrayValues[i], userArrayValues[i + 1])\n t.compare(userMapValues[i], userMapValues[i + 1])\n t.compare(userXmlValues[i], userXmlValues[i + 1])\n t.compare(userTextValues[i].map(/** @param {any} a */ a => typeof a.insert === 'string' ? a.insert : ' ').join('').length, users[i].getText('text').length)\n t.compare(userTextValues[i], userTextValues[i + 1])\n t.compare(Y.getStateVector(users[i].store), Y.getStateVector(users[i + 1].store))\n compareDS(Y.createDeleteSetFromStructStore(users[i].store), Y.createDeleteSetFromStructStore(users[i + 1].store))\n compareStructStores(users[i].store, users[i + 1].store)\n }\n users.map(u => u.destroy())\n}\n\n/**\n * @param {Y.Item?} a\n * @param {Y.Item?} b\n * @return {boolean}\n */\nexport const compareItemIDs = (a, b) => a === b || (a !== null && b != null && Y.compareIDs(a.id, b.id))\n\n/**\n * @param {Y.StructStore} ss1\n * @param {Y.StructStore} ss2\n */\nexport const compareStructStores = (ss1, ss2) => {\n t.assert(ss1.clients.size === ss2.clients.size)\n for (const [client, structs1] of ss1.clients) {\n const structs2 = /** @type {Array} */ (ss2.clients.get(client))\n t.assert(structs2 !== undefined && structs1.length === structs2.length)\n for (let i = 0; i < structs1.length; i++) {\n const s1 = structs1[i]\n const s2 = structs2[i]\n // checks for abstract struct\n if (\n s1.constructor !== s2.constructor ||\n !Y.compareIDs(s1.id, s2.id) ||\n s1.deleted !== s2.deleted ||\n // @ts-ignore\n s1.length !== s2.length\n ) {\n t.fail('Structs dont match')\n }\n if (s1 instanceof Y.Item) {\n if (\n !(s2 instanceof Y.Item) ||\n !((s1.left === null && s2.left === null) || (s1.left !== null && s2.left !== null && Y.compareIDs(s1.left.lastId, s2.left.lastId))) ||\n !compareItemIDs(s1.right, s2.right) ||\n !Y.compareIDs(s1.origin, s2.origin) ||\n !Y.compareIDs(s1.rightOrigin, s2.rightOrigin) ||\n s1.parentSub !== s2.parentSub\n ) {\n return t.fail('Items dont match')\n }\n // make sure that items are connected correctly\n t.assert(s1.left === null || s1.left.right === s1)\n t.assert(s1.right === null || s1.right.left === s1)\n t.assert(s2.left === null || s2.left.right === s2)\n t.assert(s2.right === null || s2.right.left === s2)\n }\n }\n }\n}\n\n/**\n * @param {Y.DeleteSet} ds1\n * @param {Y.DeleteSet} ds2\n */\nexport const compareDS = (ds1, ds2) => {\n t.assert(ds1.clients.size === ds2.clients.size)\n ds1.clients.forEach((deleteItems1, client) => {\n const deleteItems2 = /** @type {Array} */ (ds2.clients.get(client))\n t.assert(deleteItems2 !== undefined && deleteItems1.length === deleteItems2.length)\n for (let i = 0; i < deleteItems1.length; i++) {\n const di1 = deleteItems1[i]\n const di2 = deleteItems2[i]\n if (di1.clock !== di2.clock || di1.len !== di2.len) {\n t.fail('DeleteSets dont match')\n }\n }\n })\n}\n\n/**\n * @template T\n * @callback InitTestObjectCallback\n * @param {TestYInstance} y\n * @return {T}\n */\n\n/**\n * @template T\n * @param {t.TestCase} tc\n * @param {Array} mods\n * @param {number} iterations\n * @param {InitTestObjectCallback} [initTestObject]\n */\nexport const applyRandomTests = (tc, mods, iterations, initTestObject) => {\n const gen = tc.prng\n const result = init(tc, { users: 5 }, initTestObject)\n const { testConnector, users } = result\n for (let i = 0; i < iterations; i++) {\n if (prng.int32(gen, 0, 100) <= 2) {\n // 2% chance to disconnect/reconnect a random user\n if (prng.bool(gen)) {\n testConnector.disconnectRandom()\n } else {\n testConnector.reconnectRandom()\n }\n } else if (prng.int32(gen, 0, 100) <= 1) {\n // 1% chance to flush all\n testConnector.flushAllMessages()\n } else if (prng.int32(gen, 0, 100) <= 50) {\n // 50% chance to flush a random message\n testConnector.flushRandomMessage()\n }\n const user = prng.int32(gen, 0, users.length - 1)\n const test = prng.oneOf(gen, mods)\n test(users[user], gen, result.testObjects[user])\n }\n compare(users)\n return result\n}\n","// ::- Persistent data structure representing an ordered mapping from\n// strings to values, with some convenient update methods.\nfunction OrderedMap(content) {\n this.content = content;\n}\n\nOrderedMap.prototype = {\n constructor: OrderedMap,\n\n find: function(key) {\n for (var i = 0; i < this.content.length; i += 2)\n if (this.content[i] === key) return i\n return -1\n },\n\n // :: (string) → ?any\n // Retrieve the value stored under `key`, or return undefined when\n // no such key exists.\n get: function(key) {\n var found = this.find(key);\n return found == -1 ? undefined : this.content[found + 1]\n },\n\n // :: (string, any, ?string) → OrderedMap\n // Create a new map by replacing the value of `key` with a new\n // value, or adding a binding to the end of the map. If `newKey` is\n // given, the key of the binding will be replaced with that key.\n update: function(key, value, newKey) {\n var self = newKey && newKey != key ? this.remove(newKey) : this;\n var found = self.find(key), content = self.content.slice();\n if (found == -1) {\n content.push(newKey || key, value);\n } else {\n content[found + 1] = value;\n if (newKey) content[found] = newKey;\n }\n return new OrderedMap(content)\n },\n\n // :: (string) → OrderedMap\n // Return a map with the given key removed, if it existed.\n remove: function(key) {\n var found = this.find(key);\n if (found == -1) return this\n var content = this.content.slice();\n content.splice(found, 2);\n return new OrderedMap(content)\n },\n\n // :: (string, any) → OrderedMap\n // Add a new key to the start of the map.\n addToStart: function(key, value) {\n return new OrderedMap([key, value].concat(this.remove(key).content))\n },\n\n // :: (string, any) → OrderedMap\n // Add a new key to the end of the map.\n addToEnd: function(key, value) {\n var content = this.remove(key).content.slice();\n content.push(key, value);\n return new OrderedMap(content)\n },\n\n // :: (string, string, any) → OrderedMap\n // Add a key after the given key. If `place` is not found, the new\n // key is added to the end.\n addBefore: function(place, key, value) {\n var without = this.remove(key), content = without.content.slice();\n var found = without.find(place);\n content.splice(found == -1 ? content.length : found, 0, key, value);\n return new OrderedMap(content)\n },\n\n // :: ((key: string, value: any))\n // Call the given function for each key/value pair in the map, in\n // order.\n forEach: function(f) {\n for (var i = 0; i < this.content.length; i += 2)\n f(this.content[i], this.content[i + 1]);\n },\n\n // :: (union) → OrderedMap\n // Create a new map by prepending the keys in this map that don't\n // appear in `map` before the keys in `map`.\n prepend: function(map) {\n map = OrderedMap.from(map);\n if (!map.size) return this\n return new OrderedMap(map.content.concat(this.subtract(map).content))\n },\n\n // :: (union) → OrderedMap\n // Create a new map by appending the keys in this map that don't\n // appear in `map` after the keys in `map`.\n append: function(map) {\n map = OrderedMap.from(map);\n if (!map.size) return this\n return new OrderedMap(this.subtract(map).content.concat(map.content))\n },\n\n // :: (union) → OrderedMap\n // Create a map containing all the keys in this map that don't\n // appear in `map`.\n subtract: function(map) {\n var result = this;\n map = OrderedMap.from(map);\n for (var i = 0; i < map.content.length; i += 2)\n result = result.remove(map.content[i]);\n return result\n },\n\n // :: number\n // The amount of keys in this map.\n get size() {\n return this.content.length >> 1\n }\n};\n\n// :: (?union) → OrderedMap\n// Return a map with the given content. If null, create an empty\n// map. If given an ordered map, return that map itself. If given an\n// object, create a map from the object's properties.\nOrderedMap.from = function(value) {\n if (value instanceof OrderedMap) return value\n var content = [];\n if (value) for (var prop in value) content.push(prop, value[prop]);\n return new OrderedMap(content)\n};\n\nvar orderedmap = OrderedMap;\n\nexport default orderedmap;\n","import OrderedMap from 'orderedmap';\n\nfunction findDiffStart(a, b, pos) {\n for (var i = 0;; i++) {\n if (i == a.childCount || i == b.childCount)\n { return a.childCount == b.childCount ? null : pos }\n\n var childA = a.child(i), childB = b.child(i);\n if (childA == childB) { pos += childA.nodeSize; continue }\n\n if (!childA.sameMarkup(childB)) { return pos }\n\n if (childA.isText && childA.text != childB.text) {\n for (var j = 0; childA.text[j] == childB.text[j]; j++)\n { pos++; }\n return pos\n }\n if (childA.content.size || childB.content.size) {\n var inner = findDiffStart(childA.content, childB.content, pos + 1);\n if (inner != null) { return inner }\n }\n pos += childA.nodeSize;\n }\n}\n\nfunction findDiffEnd(a, b, posA, posB) {\n for (var iA = a.childCount, iB = b.childCount;;) {\n if (iA == 0 || iB == 0)\n { return iA == iB ? null : {a: posA, b: posB} }\n\n var childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;\n if (childA == childB) {\n posA -= size; posB -= size;\n continue\n }\n\n if (!childA.sameMarkup(childB)) { return {a: posA, b: posB} }\n\n if (childA.isText && childA.text != childB.text) {\n var same = 0, minSize = Math.min(childA.text.length, childB.text.length);\n while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {\n same++; posA--; posB--;\n }\n return {a: posA, b: posB}\n }\n if (childA.content.size || childB.content.size) {\n var inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);\n if (inner) { return inner }\n }\n posA -= size; posB -= size;\n }\n}\n\n// ::- A fragment represents a node's collection of child nodes.\n//\n// Like nodes, fragments are persistent data structures, and you\n// should not mutate them or their content. Rather, you create new\n// instances whenever needed. The API tries to make this easy.\nvar Fragment = function Fragment(content, size) {\n this.content = content;\n // :: number\n // The size of the fragment, which is the total of the size of its\n // content nodes.\n this.size = size || 0;\n if (size == null) { for (var i = 0; i < content.length; i++)\n { this.size += content[i].nodeSize; } }\n};\n\nvar prototypeAccessors = { firstChild: { configurable: true },lastChild: { configurable: true },childCount: { configurable: true } };\n\n// :: (number, number, (node: Node, start: number, parent: Node, index: number) → ?bool, ?number)\n// Invoke a callback for all descendant nodes between the given two\n// positions (relative to start of this fragment). Doesn't descend\n// into a node when the callback returns `false`.\nFragment.prototype.nodesBetween = function nodesBetween (from, to, f, nodeStart, parent) {\n if ( nodeStart === void 0 ) nodeStart = 0;\n\n for (var i = 0, pos = 0; pos < to; i++) {\n var child = this.content[i], end = pos + child.nodeSize;\n if (end > from && f(child, nodeStart + pos, parent, i) !== false && child.content.size) {\n var start = pos + 1;\n child.nodesBetween(Math.max(0, from - start),\n Math.min(child.content.size, to - start),\n f, nodeStart + start);\n }\n pos = end;\n }\n};\n\n// :: ((node: Node, pos: number, parent: Node) → ?bool)\n// Call the given callback for every descendant node. The callback\n// may return `false` to prevent traversal of a given node's children.\nFragment.prototype.descendants = function descendants (f) {\n this.nodesBetween(0, this.size, f);\n};\n\n// : (number, number, ?string, ?string) → string\nFragment.prototype.textBetween = function textBetween (from, to, blockSeparator, leafText) {\n var text = \"\", separated = true;\n this.nodesBetween(from, to, function (node, pos) {\n if (node.isText) {\n text += node.text.slice(Math.max(from, pos) - pos, to - pos);\n separated = !blockSeparator;\n } else if (node.isLeaf && leafText) {\n text += leafText;\n separated = !blockSeparator;\n } else if (!separated && node.isBlock) {\n text += blockSeparator;\n separated = true;\n }\n }, 0);\n return text\n};\n\n// :: (Fragment) → Fragment\n// Create a new fragment containing the combined content of this\n// fragment and the other.\nFragment.prototype.append = function append (other) {\n if (!other.size) { return this }\n if (!this.size) { return other }\n var last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;\n if (last.isText && last.sameMarkup(first)) {\n content[content.length - 1] = last.withText(last.text + first.text);\n i = 1;\n }\n for (; i < other.content.length; i++) { content.push(other.content[i]); }\n return new Fragment(content, this.size + other.size)\n};\n\n// :: (number, ?number) → Fragment\n// Cut out the sub-fragment between the two given positions.\nFragment.prototype.cut = function cut (from, to) {\n if (to == null) { to = this.size; }\n if (from == 0 && to == this.size) { return this }\n var result = [], size = 0;\n if (to > from) { for (var i = 0, pos = 0; pos < to; i++) {\n var child = this.content[i], end = pos + child.nodeSize;\n if (end > from) {\n if (pos < from || end > to) {\n if (child.isText)\n { child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos)); }\n else\n { child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1)); }\n }\n result.push(child);\n size += child.nodeSize;\n }\n pos = end;\n } }\n return new Fragment(result, size)\n};\n\nFragment.prototype.cutByIndex = function cutByIndex (from, to) {\n if (from == to) { return Fragment.empty }\n if (from == 0 && to == this.content.length) { return this }\n return new Fragment(this.content.slice(from, to))\n};\n\n// :: (number, Node) → Fragment\n// Create a new fragment in which the node at the given index is\n// replaced by the given node.\nFragment.prototype.replaceChild = function replaceChild (index, node) {\n var current = this.content[index];\n if (current == node) { return this }\n var copy = this.content.slice();\n var size = this.size + node.nodeSize - current.nodeSize;\n copy[index] = node;\n return new Fragment(copy, size)\n};\n\n// : (Node) → Fragment\n// Create a new fragment by prepending the given node to this\n// fragment.\nFragment.prototype.addToStart = function addToStart (node) {\n return new Fragment([node].concat(this.content), this.size + node.nodeSize)\n};\n\n// : (Node) → Fragment\n// Create a new fragment by appending the given node to this\n// fragment.\nFragment.prototype.addToEnd = function addToEnd (node) {\n return new Fragment(this.content.concat(node), this.size + node.nodeSize)\n};\n\n// :: (Fragment) → bool\n// Compare this fragment to another one.\nFragment.prototype.eq = function eq (other) {\n if (this.content.length != other.content.length) { return false }\n for (var i = 0; i < this.content.length; i++)\n { if (!this.content[i].eq(other.content[i])) { return false } }\n return true\n};\n\n// :: ?Node\n// The first child of the fragment, or `null` if it is empty.\nprototypeAccessors.firstChild.get = function () { return this.content.length ? this.content[0] : null };\n\n// :: ?Node\n// The last child of the fragment, or `null` if it is empty.\nprototypeAccessors.lastChild.get = function () { return this.content.length ? this.content[this.content.length - 1] : null };\n\n// :: number\n// The number of child nodes in this fragment.\nprototypeAccessors.childCount.get = function () { return this.content.length };\n\n// :: (number) → Node\n// Get the child node at the given index. Raise an error when the\n// index is out of range.\nFragment.prototype.child = function child (index) {\n var found = this.content[index];\n if (!found) { throw new RangeError(\"Index \" + index + \" out of range for \" + this) }\n return found\n};\n\n// :: (number) → ?Node\n// Get the child node at the given index, if it exists.\nFragment.prototype.maybeChild = function maybeChild (index) {\n return this.content[index]\n};\n\n// :: ((node: Node, offset: number, index: number))\n// Call `f` for every child node, passing the node, its offset\n// into this parent node, and its index.\nFragment.prototype.forEach = function forEach (f) {\n for (var i = 0, p = 0; i < this.content.length; i++) {\n var child = this.content[i];\n f(child, p, i);\n p += child.nodeSize;\n }\n};\n\n// :: (Fragment) → ?number\n// Find the first position at which this fragment and another\n// fragment differ, or `null` if they are the same.\nFragment.prototype.findDiffStart = function findDiffStart$1 (other, pos) {\n if ( pos === void 0 ) pos = 0;\n\n return findDiffStart(this, other, pos)\n};\n\n// :: (Fragment) → ?{a: number, b: number}\n// Find the first position, searching from the end, at which this\n// fragment and the given fragment differ, or `null` if they are the\n// same. Since this position will not be the same in both nodes, an\n// object with two separate positions is returned.\nFragment.prototype.findDiffEnd = function findDiffEnd$1 (other, pos, otherPos) {\n if ( pos === void 0 ) pos = this.size;\n if ( otherPos === void 0 ) otherPos = other.size;\n\n return findDiffEnd(this, other, pos, otherPos)\n};\n\n// : (number, ?number) → {index: number, offset: number}\n// Find the index and inner offset corresponding to a given relative\n// position in this fragment. The result object will be reused\n// (overwritten) the next time the function is called. (Not public.)\nFragment.prototype.findIndex = function findIndex (pos, round) {\n if ( round === void 0 ) round = -1;\n\n if (pos == 0) { return retIndex(0, pos) }\n if (pos == this.size) { return retIndex(this.content.length, pos) }\n if (pos > this.size || pos < 0) { throw new RangeError((\"Position \" + pos + \" outside of fragment (\" + (this) + \")\")) }\n for (var i = 0, curPos = 0;; i++) {\n var cur = this.child(i), end = curPos + cur.nodeSize;\n if (end >= pos) {\n if (end == pos || round > 0) { return retIndex(i + 1, end) }\n return retIndex(i, curPos)\n }\n curPos = end;\n }\n};\n\n// :: () → string\n// Return a debugging string that describes this fragment.\nFragment.prototype.toString = function toString () { return \"<\" + this.toStringInner() + \">\" };\n\nFragment.prototype.toStringInner = function toStringInner () { return this.content.join(\", \") };\n\n// :: () → ?Object\n// Create a JSON-serializeable representation of this fragment.\nFragment.prototype.toJSON = function toJSON () {\n return this.content.length ? this.content.map(function (n) { return n.toJSON(); }) : null\n};\n\n// :: (Schema, ?Object) → Fragment\n// Deserialize a fragment from its JSON representation.\nFragment.fromJSON = function fromJSON (schema, value) {\n if (!value) { return Fragment.empty }\n if (!Array.isArray(value)) { throw new RangeError(\"Invalid input for Fragment.fromJSON\") }\n return new Fragment(value.map(schema.nodeFromJSON))\n};\n\n// :: ([Node]) → Fragment\n// Build a fragment from an array of nodes. Ensures that adjacent\n// text nodes with the same marks are joined together.\nFragment.fromArray = function fromArray (array) {\n if (!array.length) { return Fragment.empty }\n var joined, size = 0;\n for (var i = 0; i < array.length; i++) {\n var node = array[i];\n size += node.nodeSize;\n if (i && node.isText && array[i - 1].sameMarkup(node)) {\n if (!joined) { joined = array.slice(0, i); }\n joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text);\n } else if (joined) {\n joined.push(node);\n }\n }\n return new Fragment(joined || array, size)\n};\n\n// :: (?union) → Fragment\n// Create a fragment from something that can be interpreted as a set\n// of nodes. For `null`, it returns the empty fragment. For a\n// fragment, the fragment itself. For a node or array of nodes, a\n// fragment containing those nodes.\nFragment.from = function from (nodes) {\n if (!nodes) { return Fragment.empty }\n if (nodes instanceof Fragment) { return nodes }\n if (Array.isArray(nodes)) { return this.fromArray(nodes) }\n if (nodes.attrs) { return new Fragment([nodes], nodes.nodeSize) }\n throw new RangeError(\"Can not convert \" + nodes + \" to a Fragment\" +\n (nodes.nodesBetween ? \" (looks like multiple versions of prosemirror-model were loaded)\" : \"\"))\n};\n\nObject.defineProperties( Fragment.prototype, prototypeAccessors );\n\nvar found = {index: 0, offset: 0};\nfunction retIndex(index, offset) {\n found.index = index;\n found.offset = offset;\n return found\n}\n\n// :: Fragment\n// An empty fragment. Intended to be reused whenever a node doesn't\n// contain anything (rather than allocating a new empty fragment for\n// each leaf node).\nFragment.empty = new Fragment([], 0);\n\nfunction compareDeep(a, b) {\n if (a === b) { return true }\n if (!(a && typeof a == \"object\") ||\n !(b && typeof b == \"object\")) { return false }\n var array = Array.isArray(a);\n if (Array.isArray(b) != array) { return false }\n if (array) {\n if (a.length != b.length) { return false }\n for (var i = 0; i < a.length; i++) { if (!compareDeep(a[i], b[i])) { return false } }\n } else {\n for (var p in a) { if (!(p in b) || !compareDeep(a[p], b[p])) { return false } }\n for (var p$1 in b) { if (!(p$1 in a)) { return false } }\n }\n return true\n}\n\n// ::- A mark is a piece of information that can be attached to a node,\n// such as it being emphasized, in code font, or a link. It has a type\n// and optionally a set of attributes that provide further information\n// (such as the target of the link). Marks are created through a\n// `Schema`, which controls which types exist and which\n// attributes they have.\nvar Mark = function Mark(type, attrs) {\n // :: MarkType\n // The type of this mark.\n this.type = type;\n // :: Object\n // The attributes associated with this mark.\n this.attrs = attrs;\n};\n\n// :: ([Mark]) → [Mark]\n// Given a set of marks, create a new set which contains this one as\n// well, in the right position. If this mark is already in the set,\n// the set itself is returned. If any marks that are set to be\n// [exclusive](#model.MarkSpec.excludes) with this mark are present,\n// those are replaced by this one.\nMark.prototype.addToSet = function addToSet (set) {\n var copy, placed = false;\n for (var i = 0; i < set.length; i++) {\n var other = set[i];\n if (this.eq(other)) { return set }\n if (this.type.excludes(other.type)) {\n if (!copy) { copy = set.slice(0, i); }\n } else if (other.type.excludes(this.type)) {\n return set\n } else {\n if (!placed && other.type.rank > this.type.rank) {\n if (!copy) { copy = set.slice(0, i); }\n copy.push(this);\n placed = true;\n }\n if (copy) { copy.push(other); }\n }\n }\n if (!copy) { copy = set.slice(); }\n if (!placed) { copy.push(this); }\n return copy\n};\n\n// :: ([Mark]) → [Mark]\n// Remove this mark from the given set, returning a new set. If this\n// mark is not in the set, the set itself is returned.\nMark.prototype.removeFromSet = function removeFromSet (set) {\n for (var i = 0; i < set.length; i++)\n { if (this.eq(set[i]))\n { return set.slice(0, i).concat(set.slice(i + 1)) } }\n return set\n};\n\n// :: ([Mark]) → bool\n// Test whether this mark is in the given set of marks.\nMark.prototype.isInSet = function isInSet (set) {\n for (var i = 0; i < set.length; i++)\n { if (this.eq(set[i])) { return true } }\n return false\n};\n\n// :: (Mark) → bool\n// Test whether this mark has the same type and attributes as\n// another mark.\nMark.prototype.eq = function eq (other) {\n return this == other ||\n (this.type == other.type && compareDeep(this.attrs, other.attrs))\n};\n\n// :: () → Object\n// Convert this mark to a JSON-serializeable representation.\nMark.prototype.toJSON = function toJSON () {\n var obj = {type: this.type.name};\n for (var _ in this.attrs) {\n obj.attrs = this.attrs;\n break\n }\n return obj\n};\n\n// :: (Schema, Object) → Mark\nMark.fromJSON = function fromJSON (schema, json) {\n if (!json) { throw new RangeError(\"Invalid input for Mark.fromJSON\") }\n var type = schema.marks[json.type];\n if (!type) { throw new RangeError((\"There is no mark type \" + (json.type) + \" in this schema\")) }\n return type.create(json.attrs)\n};\n\n// :: ([Mark], [Mark]) → bool\n// Test whether two sets of marks are identical.\nMark.sameSet = function sameSet (a, b) {\n if (a == b) { return true }\n if (a.length != b.length) { return false }\n for (var i = 0; i < a.length; i++)\n { if (!a[i].eq(b[i])) { return false } }\n return true\n};\n\n// :: (?union) → [Mark]\n// Create a properly sorted mark set from null, a single mark, or an\n// unsorted array of marks.\nMark.setFrom = function setFrom (marks) {\n if (!marks || marks.length == 0) { return Mark.none }\n if (marks instanceof Mark) { return [marks] }\n var copy = marks.slice();\n copy.sort(function (a, b) { return a.type.rank - b.type.rank; });\n return copy\n};\n\n// :: [Mark] The empty set of marks.\nMark.none = [];\n\n// ReplaceError:: class extends Error\n// Error type raised by [`Node.replace`](#model.Node.replace) when\n// given an invalid replacement.\n\nfunction ReplaceError(message) {\n var err = Error.call(this, message);\n err.__proto__ = ReplaceError.prototype;\n return err\n}\n\nReplaceError.prototype = Object.create(Error.prototype);\nReplaceError.prototype.constructor = ReplaceError;\nReplaceError.prototype.name = \"ReplaceError\";\n\n// ::- A slice represents a piece cut out of a larger document. It\n// stores not only a fragment, but also the depth up to which nodes on\n// both side are ‘open’ (cut through).\nvar Slice = function Slice(content, openStart, openEnd) {\n // :: Fragment The slice's content.\n this.content = content;\n // :: number The open depth at the start.\n this.openStart = openStart;\n // :: number The open depth at the end.\n this.openEnd = openEnd;\n};\n\nvar prototypeAccessors$1 = { size: { configurable: true } };\n\n// :: number\n// The size this slice would add when inserted into a document.\nprototypeAccessors$1.size.get = function () {\n return this.content.size - this.openStart - this.openEnd\n};\n\nSlice.prototype.insertAt = function insertAt (pos, fragment) {\n var content = insertInto(this.content, pos + this.openStart, fragment, null);\n return content && new Slice(content, this.openStart, this.openEnd)\n};\n\nSlice.prototype.removeBetween = function removeBetween (from, to) {\n return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd)\n};\n\n// :: (Slice) → bool\n// Tests whether this slice is equal to another slice.\nSlice.prototype.eq = function eq (other) {\n return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd\n};\n\nSlice.prototype.toString = function toString () {\n return this.content + \"(\" + this.openStart + \",\" + this.openEnd + \")\"\n};\n\n// :: () → ?Object\n// Convert a slice to a JSON-serializable representation.\nSlice.prototype.toJSON = function toJSON () {\n if (!this.content.size) { return null }\n var json = {content: this.content.toJSON()};\n if (this.openStart > 0) { json.openStart = this.openStart; }\n if (this.openEnd > 0) { json.openEnd = this.openEnd; }\n return json\n};\n\n// :: (Schema, ?Object) → Slice\n// Deserialize a slice from its JSON representation.\nSlice.fromJSON = function fromJSON (schema, json) {\n if (!json) { return Slice.empty }\n var openStart = json.openStart || 0, openEnd = json.openEnd || 0;\n if (typeof openStart != \"number\" || typeof openEnd != \"number\")\n { throw new RangeError(\"Invalid input for Slice.fromJSON\") }\n return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd)\n};\n\n// :: (Fragment, ?bool) → Slice\n// Create a slice from a fragment by taking the maximum possible\n// open value on both side of the fragment.\nSlice.maxOpen = function maxOpen (fragment, openIsolating) {\n if ( openIsolating === void 0 ) openIsolating=true;\n\n var openStart = 0, openEnd = 0;\n for (var n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild) { openStart++; }\n for (var n$1 = fragment.lastChild; n$1 && !n$1.isLeaf && (openIsolating || !n$1.type.spec.isolating); n$1 = n$1.lastChild) { openEnd++; }\n return new Slice(fragment, openStart, openEnd)\n};\n\nObject.defineProperties( Slice.prototype, prototypeAccessors$1 );\n\nfunction removeRange(content, from, to) {\n var ref = content.findIndex(from);\n var index = ref.index;\n var offset = ref.offset;\n var child = content.maybeChild(index);\n var ref$1 = content.findIndex(to);\n var indexTo = ref$1.index;\n var offsetTo = ref$1.offset;\n if (offset == from || child.isText) {\n if (offsetTo != to && !content.child(indexTo).isText) { throw new RangeError(\"Removing non-flat range\") }\n return content.cut(0, from).append(content.cut(to))\n }\n if (index != indexTo) { throw new RangeError(\"Removing non-flat range\") }\n return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)))\n}\n\nfunction insertInto(content, dist, insert, parent) {\n var ref = content.findIndex(dist);\n var index = ref.index;\n var offset = ref.offset;\n var child = content.maybeChild(index);\n if (offset == dist || child.isText) {\n if (parent && !parent.canReplace(index, index, insert)) { return null }\n return content.cut(0, dist).append(insert).append(content.cut(dist))\n }\n var inner = insertInto(child.content, dist - offset - 1, insert);\n return inner && content.replaceChild(index, child.copy(inner))\n}\n\n// :: Slice\n// The empty slice.\nSlice.empty = new Slice(Fragment.empty, 0, 0);\n\nfunction replace($from, $to, slice) {\n if (slice.openStart > $from.depth)\n { throw new ReplaceError(\"Inserted content deeper than insertion position\") }\n if ($from.depth - slice.openStart != $to.depth - slice.openEnd)\n { throw new ReplaceError(\"Inconsistent open depths\") }\n return replaceOuter($from, $to, slice, 0)\n}\n\nfunction replaceOuter($from, $to, slice, depth) {\n var index = $from.index(depth), node = $from.node(depth);\n if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {\n var inner = replaceOuter($from, $to, slice, depth + 1);\n return node.copy(node.content.replaceChild(index, inner))\n } else if (!slice.content.size) {\n return close(node, replaceTwoWay($from, $to, depth))\n } else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case\n var parent = $from.parent, content = parent.content;\n return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)))\n } else {\n var ref = prepareSliceForReplace(slice, $from);\n var start = ref.start;\n var end = ref.end;\n return close(node, replaceThreeWay($from, start, end, $to, depth))\n }\n}\n\nfunction checkJoin(main, sub) {\n if (!sub.type.compatibleContent(main.type))\n { throw new ReplaceError(\"Cannot join \" + sub.type.name + \" onto \" + main.type.name) }\n}\n\nfunction joinable($before, $after, depth) {\n var node = $before.node(depth);\n checkJoin(node, $after.node(depth));\n return node\n}\n\nfunction addNode(child, target) {\n var last = target.length - 1;\n if (last >= 0 && child.isText && child.sameMarkup(target[last]))\n { target[last] = child.withText(target[last].text + child.text); }\n else\n { target.push(child); }\n}\n\nfunction addRange($start, $end, depth, target) {\n var node = ($end || $start).node(depth);\n var startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;\n if ($start) {\n startIndex = $start.index(depth);\n if ($start.depth > depth) {\n startIndex++;\n } else if ($start.textOffset) {\n addNode($start.nodeAfter, target);\n startIndex++;\n }\n }\n for (var i = startIndex; i < endIndex; i++) { addNode(node.child(i), target); }\n if ($end && $end.depth == depth && $end.textOffset)\n { addNode($end.nodeBefore, target); }\n}\n\nfunction close(node, content) {\n if (!node.type.validContent(content))\n { throw new ReplaceError(\"Invalid content for node \" + node.type.name) }\n return node.copy(content)\n}\n\nfunction replaceThreeWay($from, $start, $end, $to, depth) {\n var openStart = $from.depth > depth && joinable($from, $start, depth + 1);\n var openEnd = $to.depth > depth && joinable($end, $to, depth + 1);\n\n var content = [];\n addRange(null, $from, depth, content);\n if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {\n checkJoin(openStart, openEnd);\n addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);\n } else {\n if (openStart)\n { addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content); }\n addRange($start, $end, depth, content);\n if (openEnd)\n { addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content); }\n }\n addRange($to, null, depth, content);\n return new Fragment(content)\n}\n\nfunction replaceTwoWay($from, $to, depth) {\n var content = [];\n addRange(null, $from, depth, content);\n if ($from.depth > depth) {\n var type = joinable($from, $to, depth + 1);\n addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content)\n}\n\nfunction prepareSliceForReplace(slice, $along) {\n var extra = $along.depth - slice.openStart, parent = $along.node(extra);\n var node = parent.copy(slice.content);\n for (var i = extra - 1; i >= 0; i--)\n { node = $along.node(i).copy(Fragment.from(node)); }\n return {start: node.resolveNoCache(slice.openStart + extra),\n end: node.resolveNoCache(node.content.size - slice.openEnd - extra)}\n}\n\n// ::- You can [_resolve_](#model.Node.resolve) a position to get more\n// information about it. Objects of this class represent such a\n// resolved position, providing various pieces of context information,\n// and some helper methods.\n//\n// Throughout this interface, methods that take an optional `depth`\n// parameter will interpret undefined as `this.depth` and negative\n// numbers as `this.depth + value`.\nvar ResolvedPos = function ResolvedPos(pos, path, parentOffset) {\n // :: number The position that was resolved.\n this.pos = pos;\n this.path = path;\n // :: number\n // The number of levels the parent node is from the root. If this\n // position points directly into the root node, it is 0. If it\n // points into a top-level paragraph, 1, and so on.\n this.depth = path.length / 3 - 1;\n // :: number The offset this position has into its parent node.\n this.parentOffset = parentOffset;\n};\n\nvar prototypeAccessors$2 = { parent: { configurable: true },doc: { configurable: true },textOffset: { configurable: true },nodeAfter: { configurable: true },nodeBefore: { configurable: true } };\n\nResolvedPos.prototype.resolveDepth = function resolveDepth (val) {\n if (val == null) { return this.depth }\n if (val < 0) { return this.depth + val }\n return val\n};\n\n// :: Node\n// The parent node that the position points into. Note that even if\n// a position points into a text node, that node is not considered\n// the parent—text nodes are ‘flat’ in this model, and have no content.\nprototypeAccessors$2.parent.get = function () { return this.node(this.depth) };\n\n// :: Node\n// The root node in which the position was resolved.\nprototypeAccessors$2.doc.get = function () { return this.node(0) };\n\n// :: (?number) → Node\n// The ancestor node at the given level. `p.node(p.depth)` is the\n// same as `p.parent`.\nResolvedPos.prototype.node = function node (depth) { return this.path[this.resolveDepth(depth) * 3] };\n\n// :: (?number) → number\n// The index into the ancestor at the given level. If this points at\n// the 3rd node in the 2nd paragraph on the top level, for example,\n// `p.index(0)` is 1 and `p.index(1)` is 2.\nResolvedPos.prototype.index = function index (depth) { return this.path[this.resolveDepth(depth) * 3 + 1] };\n\n// :: (?number) → number\n// The index pointing after this position into the ancestor at the\n// given level.\nResolvedPos.prototype.indexAfter = function indexAfter (depth) {\n depth = this.resolveDepth(depth);\n return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1)\n};\n\n// :: (?number) → number\n// The (absolute) position at the start of the node at the given\n// level.\nResolvedPos.prototype.start = function start (depth) {\n depth = this.resolveDepth(depth);\n return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1\n};\n\n// :: (?number) → number\n// The (absolute) position at the end of the node at the given\n// level.\nResolvedPos.prototype.end = function end (depth) {\n depth = this.resolveDepth(depth);\n return this.start(depth) + this.node(depth).content.size\n};\n\n// :: (?number) → number\n// The (absolute) position directly before the wrapping node at the\n// given level, or, when `depth` is `this.depth + 1`, the original\n// position.\nResolvedPos.prototype.before = function before (depth) {\n depth = this.resolveDepth(depth);\n if (!depth) { throw new RangeError(\"There is no position before the top-level node\") }\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1]\n};\n\n// :: (?number) → number\n// The (absolute) position directly after the wrapping node at the\n// given level, or the original position when `depth` is `this.depth + 1`.\nResolvedPos.prototype.after = function after (depth) {\n depth = this.resolveDepth(depth);\n if (!depth) { throw new RangeError(\"There is no position after the top-level node\") }\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize\n};\n\n// :: number\n// When this position points into a text node, this returns the\n// distance between the position and the start of the text node.\n// Will be zero for positions that point between nodes.\nprototypeAccessors$2.textOffset.get = function () { return this.pos - this.path[this.path.length - 1] };\n\n// :: ?Node\n// Get the node directly after the position, if any. If the position\n// points into a text node, only the part of that node after the\n// position is returned.\nprototypeAccessors$2.nodeAfter.get = function () {\n var parent = this.parent, index = this.index(this.depth);\n if (index == parent.childCount) { return null }\n var dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);\n return dOff ? parent.child(index).cut(dOff) : child\n};\n\n// :: ?Node\n// Get the node directly before the position, if any. If the\n// position points into a text node, only the part of that node\n// before the position is returned.\nprototypeAccessors$2.nodeBefore.get = function () {\n var index = this.index(this.depth);\n var dOff = this.pos - this.path[this.path.length - 1];\n if (dOff) { return this.parent.child(index).cut(0, dOff) }\n return index == 0 ? null : this.parent.child(index - 1)\n};\n\n// :: (number, ?number) → number\n// Get the position at the given index in the parent node at the\n// given depth (which defaults to `this.depth`).\nResolvedPos.prototype.posAtIndex = function posAtIndex (index, depth) {\n depth = this.resolveDepth(depth);\n var node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n for (var i = 0; i < index; i++) { pos += node.child(i).nodeSize; }\n return pos\n};\n\n// :: () → [Mark]\n// Get the marks at this position, factoring in the surrounding\n// marks' [`inclusive`](#model.MarkSpec.inclusive) property. If the\n// position is at the start of a non-empty node, the marks of the\n// node after it (if any) are returned.\nResolvedPos.prototype.marks = function marks () {\n var parent = this.parent, index = this.index();\n\n // In an empty parent, return the empty array\n if (parent.content.size == 0) { return Mark.none }\n\n // When inside a text node, just return the text node's marks\n if (this.textOffset) { return parent.child(index).marks }\n\n var main = parent.maybeChild(index - 1), other = parent.maybeChild(index);\n // If the `after` flag is true of there is no node before, make\n // the node after this position the main reference.\n if (!main) { var tmp = main; main = other; other = tmp; }\n\n // Use all marks in the main node, except those that have\n // `inclusive` set to false and are not present in the other node.\n var marks = main.marks;\n for (var i = 0; i < marks.length; i++)\n { if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks)))\n { marks = marks[i--].removeFromSet(marks); } }\n\n return marks\n};\n\n// :: (ResolvedPos) → ?[Mark]\n// Get the marks after the current position, if any, except those\n// that are non-inclusive and not present at position `$end`. This\n// is mostly useful for getting the set of marks to preserve after a\n// deletion. Will return `null` if this position is at the end of\n// its parent node or its parent node isn't a textblock (in which\n// case no marks should be preserved).\nResolvedPos.prototype.marksAcross = function marksAcross ($end) {\n var after = this.parent.maybeChild(this.index());\n if (!after || !after.isInline) { return null }\n\n var marks = after.marks, next = $end.parent.maybeChild($end.index());\n for (var i = 0; i < marks.length; i++)\n { if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))\n { marks = marks[i--].removeFromSet(marks); } }\n return marks\n};\n\n// :: (number) → number\n// The depth up to which this position and the given (non-resolved)\n// position share the same parent nodes.\nResolvedPos.prototype.sharedDepth = function sharedDepth (pos) {\n for (var depth = this.depth; depth > 0; depth--)\n { if (this.start(depth) <= pos && this.end(depth) >= pos) { return depth } }\n return 0\n};\n\n// :: (?ResolvedPos, ?(Node) → bool) → ?NodeRange\n// Returns a range based on the place where this position and the\n// given position diverge around block content. If both point into\n// the same textblock, for example, a range around that textblock\n// will be returned. If they point into different blocks, the range\n// around those blocks in their shared ancestor is returned. You can\n// pass in an optional predicate that will be called with a parent\n// node to see if a range into that parent is acceptable.\nResolvedPos.prototype.blockRange = function blockRange (other, pred) {\n if ( other === void 0 ) other = this;\n\n if (other.pos < this.pos) { return other.blockRange(this) }\n for (var d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)\n { if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))\n { return new NodeRange(this, other, d) } }\n};\n\n// :: (ResolvedPos) → bool\n// Query whether the given position shares the same parent node.\nResolvedPos.prototype.sameParent = function sameParent (other) {\n return this.pos - this.parentOffset == other.pos - other.parentOffset\n};\n\n// :: (ResolvedPos) → ResolvedPos\n// Return the greater of this and the given position.\nResolvedPos.prototype.max = function max (other) {\n return other.pos > this.pos ? other : this\n};\n\n// :: (ResolvedPos) → ResolvedPos\n// Return the smaller of this and the given position.\nResolvedPos.prototype.min = function min (other) {\n return other.pos < this.pos ? other : this\n};\n\nResolvedPos.prototype.toString = function toString () {\n var str = \"\";\n for (var i = 1; i <= this.depth; i++)\n { str += (str ? \"/\" : \"\") + this.node(i).type.name + \"_\" + this.index(i - 1); }\n return str + \":\" + this.parentOffset\n};\n\nResolvedPos.resolve = function resolve (doc, pos) {\n if (!(pos >= 0 && pos <= doc.content.size)) { throw new RangeError(\"Position \" + pos + \" out of range\") }\n var path = [];\n var start = 0, parentOffset = pos;\n for (var node = doc;;) {\n var ref = node.content.findIndex(parentOffset);\n var index = ref.index;\n var offset = ref.offset;\n var rem = parentOffset - offset;\n path.push(node, index, start + offset);\n if (!rem) { break }\n node = node.child(index);\n if (node.isText) { break }\n parentOffset = rem - 1;\n start += offset + 1;\n }\n return new ResolvedPos(pos, path, parentOffset)\n};\n\nResolvedPos.resolveCached = function resolveCached (doc, pos) {\n for (var i = 0; i < resolveCache.length; i++) {\n var cached = resolveCache[i];\n if (cached.pos == pos && cached.doc == doc) { return cached }\n }\n var result = resolveCache[resolveCachePos] = ResolvedPos.resolve(doc, pos);\n resolveCachePos = (resolveCachePos + 1) % resolveCacheSize;\n return result\n};\n\nObject.defineProperties( ResolvedPos.prototype, prototypeAccessors$2 );\n\nvar resolveCache = [], resolveCachePos = 0, resolveCacheSize = 12;\n\n// ::- Represents a flat range of content, i.e. one that starts and\n// ends in the same node.\nvar NodeRange = function NodeRange($from, $to, depth) {\n // :: ResolvedPos A resolved position along the start of the\n // content. May have a `depth` greater than this object's `depth`\n // property, since these are the positions that were used to\n // compute the range, not re-resolved positions directly at its\n // boundaries.\n this.$from = $from;\n // :: ResolvedPos A position along the end of the content. See\n // caveat for [`$from`](#model.NodeRange.$from).\n this.$to = $to;\n // :: number The depth of the node that this range points into.\n this.depth = depth;\n};\n\nvar prototypeAccessors$1$1 = { start: { configurable: true },end: { configurable: true },parent: { configurable: true },startIndex: { configurable: true },endIndex: { configurable: true } };\n\n// :: number The position at the start of the range.\nprototypeAccessors$1$1.start.get = function () { return this.$from.before(this.depth + 1) };\n// :: number The position at the end of the range.\nprototypeAccessors$1$1.end.get = function () { return this.$to.after(this.depth + 1) };\n\n// :: Node The parent node that the range points into.\nprototypeAccessors$1$1.parent.get = function () { return this.$from.node(this.depth) };\n// :: number The start index of the range in the parent node.\nprototypeAccessors$1$1.startIndex.get = function () { return this.$from.index(this.depth) };\n// :: number The end index of the range in the parent node.\nprototypeAccessors$1$1.endIndex.get = function () { return this.$to.indexAfter(this.depth) };\n\nObject.defineProperties( NodeRange.prototype, prototypeAccessors$1$1 );\n\nvar emptyAttrs = Object.create(null);\n\n// ::- This class represents a node in the tree that makes up a\n// ProseMirror document. So a document is an instance of `Node`, with\n// children that are also instances of `Node`.\n//\n// Nodes are persistent data structures. Instead of changing them, you\n// create new ones with the content you want. Old ones keep pointing\n// at the old document shape. This is made cheaper by sharing\n// structure between the old and new data as much as possible, which a\n// tree shape like this (without back pointers) makes easy.\n//\n// **Do not** directly mutate the properties of a `Node` object. See\n// [the guide](/docs/guide/#doc) for more information.\nvar Node = function Node(type, attrs, content, marks) {\n // :: NodeType\n // The type of node that this is.\n this.type = type;\n\n // :: Object\n // An object mapping attribute names to values. The kind of\n // attributes allowed and required are\n // [determined](#model.NodeSpec.attrs) by the node type.\n this.attrs = attrs;\n\n // :: Fragment\n // A container holding the node's children.\n this.content = content || Fragment.empty;\n\n // :: [Mark]\n // The marks (things like whether it is emphasized or part of a\n // link) applied to this node.\n this.marks = marks || Mark.none;\n};\n\nvar prototypeAccessors$3 = { nodeSize: { configurable: true },childCount: { configurable: true },textContent: { configurable: true },firstChild: { configurable: true },lastChild: { configurable: true },isBlock: { configurable: true },isTextblock: { configurable: true },inlineContent: { configurable: true },isInline: { configurable: true },isText: { configurable: true },isLeaf: { configurable: true },isAtom: { configurable: true } };\n\n// text:: ?string\n// For text nodes, this contains the node's text content.\n\n// :: number\n// The size of this node, as defined by the integer-based [indexing\n// scheme](/docs/guide/#doc.indexing). For text nodes, this is the\n// amount of characters. For other leaf nodes, it is one. For\n// non-leaf nodes, it is the size of the content plus two (the start\n// and end token).\nprototypeAccessors$3.nodeSize.get = function () { return this.isLeaf ? 1 : 2 + this.content.size };\n\n// :: number\n// The number of children that the node has.\nprototypeAccessors$3.childCount.get = function () { return this.content.childCount };\n\n// :: (number) → Node\n// Get the child node at the given index. Raises an error when the\n// index is out of range.\nNode.prototype.child = function child (index) { return this.content.child(index) };\n\n// :: (number) → ?Node\n// Get the child node at the given index, if it exists.\nNode.prototype.maybeChild = function maybeChild (index) { return this.content.maybeChild(index) };\n\n// :: ((node: Node, offset: number, index: number))\n// Call `f` for every child node, passing the node, its offset\n// into this parent node, and its index.\nNode.prototype.forEach = function forEach (f) { this.content.forEach(f); };\n\n// :: (number, number, (node: Node, pos: number, parent: Node, index: number) → ?bool, ?number)\n// Invoke a callback for all descendant nodes recursively between\n// the given two positions that are relative to start of this node's\n// content. The callback is invoked with the node, its\n// parent-relative position, its parent node, and its child index.\n// When the callback returns false for a given node, that node's\n// children will not be recursed over. The last parameter can be\n// used to specify a starting position to count from.\nNode.prototype.nodesBetween = function nodesBetween (from, to, f, startPos) {\n if ( startPos === void 0 ) startPos = 0;\n\n this.content.nodesBetween(from, to, f, startPos, this);\n};\n\n// :: ((node: Node, pos: number, parent: Node) → ?bool)\n// Call the given callback for every descendant node. Doesn't\n// descend into a node when the callback returns `false`.\nNode.prototype.descendants = function descendants (f) {\n this.nodesBetween(0, this.content.size, f);\n};\n\n// :: string\n// Concatenates all the text nodes found in this fragment and its\n// children.\nprototypeAccessors$3.textContent.get = function () { return this.textBetween(0, this.content.size, \"\") };\n\n// :: (number, number, ?string, ?string) → string\n// Get all text between positions `from` and `to`. When\n// `blockSeparator` is given, it will be inserted whenever a new\n// block node is started. When `leafText` is given, it'll be\n// inserted for every non-text leaf node encountered.\nNode.prototype.textBetween = function textBetween (from, to, blockSeparator, leafText) {\n return this.content.textBetween(from, to, blockSeparator, leafText)\n};\n\n// :: ?Node\n// Returns this node's first child, or `null` if there are no\n// children.\nprototypeAccessors$3.firstChild.get = function () { return this.content.firstChild };\n\n// :: ?Node\n// Returns this node's last child, or `null` if there are no\n// children.\nprototypeAccessors$3.lastChild.get = function () { return this.content.lastChild };\n\n// :: (Node) → bool\n// Test whether two nodes represent the same piece of document.\nNode.prototype.eq = function eq (other) {\n return this == other || (this.sameMarkup(other) && this.content.eq(other.content))\n};\n\n// :: (Node) → bool\n// Compare the markup (type, attributes, and marks) of this node to\n// those of another. Returns `true` if both have the same markup.\nNode.prototype.sameMarkup = function sameMarkup (other) {\n return this.hasMarkup(other.type, other.attrs, other.marks)\n};\n\n// :: (NodeType, ?Object, ?[Mark]) → bool\n// Check whether this node's markup correspond to the given type,\n// attributes, and marks.\nNode.prototype.hasMarkup = function hasMarkup (type, attrs, marks) {\n return this.type == type &&\n compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) &&\n Mark.sameSet(this.marks, marks || Mark.none)\n};\n\n// :: (?Fragment) → Node\n// Create a new node with the same markup as this node, containing\n// the given content (or empty, if no content is given).\nNode.prototype.copy = function copy (content) {\n if ( content === void 0 ) content = null;\n\n if (content == this.content) { return this }\n return new this.constructor(this.type, this.attrs, content, this.marks)\n};\n\n// :: ([Mark]) → Node\n// Create a copy of this node, with the given set of marks instead\n// of the node's own marks.\nNode.prototype.mark = function mark (marks) {\n return marks == this.marks ? this : new this.constructor(this.type, this.attrs, this.content, marks)\n};\n\n// :: (number, ?number) → Node\n// Create a copy of this node with only the content between the\n// given positions. If `to` is not given, it defaults to the end of\n// the node.\nNode.prototype.cut = function cut (from, to) {\n if (from == 0 && to == this.content.size) { return this }\n return this.copy(this.content.cut(from, to))\n};\n\n// :: (number, ?number) → Slice\n// Cut out the part of the document between the given positions, and\n// return it as a `Slice` object.\nNode.prototype.slice = function slice (from, to, includeParents) {\n if ( to === void 0 ) to = this.content.size;\n if ( includeParents === void 0 ) includeParents = false;\n\n if (from == to) { return Slice.empty }\n\n var $from = this.resolve(from), $to = this.resolve(to);\n var depth = includeParents ? 0 : $from.sharedDepth(to);\n var start = $from.start(depth), node = $from.node(depth);\n var content = node.content.cut($from.pos - start, $to.pos - start);\n return new Slice(content, $from.depth - depth, $to.depth - depth)\n};\n\n// :: (number, number, Slice) → Node\n// Replace the part of the document between the given positions with\n// the given slice. The slice must 'fit', meaning its open sides\n// must be able to connect to the surrounding content, and its\n// content nodes must be valid children for the node they are placed\n// into. If any of this is violated, an error of type\n// [`ReplaceError`](#model.ReplaceError) is thrown.\nNode.prototype.replace = function replace$1 (from, to, slice) {\n return replace(this.resolve(from), this.resolve(to), slice)\n};\n\n// :: (number) → ?Node\n// Find the node directly after the given position.\nNode.prototype.nodeAt = function nodeAt (pos) {\n for (var node = this;;) {\n var ref = node.content.findIndex(pos);\n var index = ref.index;\n var offset = ref.offset;\n node = node.maybeChild(index);\n if (!node) { return null }\n if (offset == pos || node.isText) { return node }\n pos -= offset + 1;\n }\n};\n\n// :: (number) → {node: ?Node, index: number, offset: number}\n// Find the (direct) child node after the given offset, if any,\n// and return it along with its index and offset relative to this\n// node.\nNode.prototype.childAfter = function childAfter (pos) {\n var ref = this.content.findIndex(pos);\n var index = ref.index;\n var offset = ref.offset;\n return {node: this.content.maybeChild(index), index: index, offset: offset}\n};\n\n// :: (number) → {node: ?Node, index: number, offset: number}\n// Find the (direct) child node before the given offset, if any,\n// and return it along with its index and offset relative to this\n// node.\nNode.prototype.childBefore = function childBefore (pos) {\n if (pos == 0) { return {node: null, index: 0, offset: 0} }\n var ref = this.content.findIndex(pos);\n var index = ref.index;\n var offset = ref.offset;\n if (offset < pos) { return {node: this.content.child(index), index: index, offset: offset} }\n var node = this.content.child(index - 1);\n return {node: node, index: index - 1, offset: offset - node.nodeSize}\n};\n\n// :: (number) → ResolvedPos\n// Resolve the given position in the document, returning an\n// [object](#model.ResolvedPos) with information about its context.\nNode.prototype.resolve = function resolve (pos) { return ResolvedPos.resolveCached(this, pos) };\n\nNode.prototype.resolveNoCache = function resolveNoCache (pos) { return ResolvedPos.resolve(this, pos) };\n\n// :: (number, number, union) → bool\n// Test whether a given mark or mark type occurs in this document\n// between the two given positions.\nNode.prototype.rangeHasMark = function rangeHasMark (from, to, type) {\n var found = false;\n if (to > from) { this.nodesBetween(from, to, function (node) {\n if (type.isInSet(node.marks)) { found = true; }\n return !found\n }); }\n return found\n};\n\n// :: bool\n// True when this is a block (non-inline node)\nprototypeAccessors$3.isBlock.get = function () { return this.type.isBlock };\n\n// :: bool\n// True when this is a textblock node, a block node with inline\n// content.\nprototypeAccessors$3.isTextblock.get = function () { return this.type.isTextblock };\n\n// :: bool\n// True when this node allows inline content.\nprototypeAccessors$3.inlineContent.get = function () { return this.type.inlineContent };\n\n// :: bool\n// True when this is an inline node (a text node or a node that can\n// appear among text).\nprototypeAccessors$3.isInline.get = function () { return this.type.isInline };\n\n// :: bool\n// True when this is a text node.\nprototypeAccessors$3.isText.get = function () { return this.type.isText };\n\n// :: bool\n// True when this is a leaf node.\nprototypeAccessors$3.isLeaf.get = function () { return this.type.isLeaf };\n\n// :: bool\n// True when this is an atom, i.e. when it does not have directly\n// editable content. This is usually the same as `isLeaf`, but can\n// be configured with the [`atom` property](#model.NodeSpec.atom) on\n// a node's spec (typically used when the node is displayed as an\n// uneditable [node view](#view.NodeView)).\nprototypeAccessors$3.isAtom.get = function () { return this.type.isAtom };\n\n// :: () → string\n// Return a string representation of this node for debugging\n// purposes.\nNode.prototype.toString = function toString () {\n if (this.type.spec.toDebugString) { return this.type.spec.toDebugString(this) }\n var name = this.type.name;\n if (this.content.size)\n { name += \"(\" + this.content.toStringInner() + \")\"; }\n return wrapMarks(this.marks, name)\n};\n\n// :: (number) → ContentMatch\n// Get the content match in this node at the given index.\nNode.prototype.contentMatchAt = function contentMatchAt (index) {\n var match = this.type.contentMatch.matchFragment(this.content, 0, index);\n if (!match) { throw new Error(\"Called contentMatchAt on a node with invalid content\") }\n return match\n};\n\n// :: (number, number, ?Fragment, ?number, ?number) → bool\n// Test whether replacing the range between `from` and `to` (by\n// child index) with the given replacement fragment (which defaults\n// to the empty fragment) would leave the node's content valid. You\n// can optionally pass `start` and `end` indices into the\n// replacement fragment.\nNode.prototype.canReplace = function canReplace (from, to, replacement, start, end) {\n if ( replacement === void 0 ) replacement = Fragment.empty;\n if ( start === void 0 ) start = 0;\n if ( end === void 0 ) end = replacement.childCount;\n\n var one = this.contentMatchAt(from).matchFragment(replacement, start, end);\n var two = one && one.matchFragment(this.content, to);\n if (!two || !two.validEnd) { return false }\n for (var i = start; i < end; i++) { if (!this.type.allowsMarks(replacement.child(i).marks)) { return false } }\n return true\n};\n\n// :: (number, number, NodeType, ?[Mark]) → bool\n// Test whether replacing the range `from` to `to` (by index) with a\n// node of the given type would leave the node's content valid.\nNode.prototype.canReplaceWith = function canReplaceWith (from, to, type, marks) {\n if (marks && !this.type.allowsMarks(marks)) { return false }\n var start = this.contentMatchAt(from).matchType(type);\n var end = start && start.matchFragment(this.content, to);\n return end ? end.validEnd : false\n};\n\n// :: (Node) → bool\n// Test whether the given node's content could be appended to this\n// node. If that node is empty, this will only return true if there\n// is at least one node type that can appear in both nodes (to avoid\n// merging completely incompatible nodes).\nNode.prototype.canAppend = function canAppend (other) {\n if (other.content.size) { return this.canReplace(this.childCount, this.childCount, other.content) }\n else { return this.type.compatibleContent(other.type) }\n};\n\n// :: ()\n// Check whether this node and its descendants conform to the\n// schema, and raise error when they do not.\nNode.prototype.check = function check () {\n if (!this.type.validContent(this.content))\n { throw new RangeError((\"Invalid content for node \" + (this.type.name) + \": \" + (this.content.toString().slice(0, 50)))) }\n this.content.forEach(function (node) { return node.check(); });\n};\n\n// :: () → Object\n// Return a JSON-serializeable representation of this node.\nNode.prototype.toJSON = function toJSON () {\n var obj = {type: this.type.name};\n for (var _ in this.attrs) {\n obj.attrs = this.attrs;\n break\n }\n if (this.content.size)\n { obj.content = this.content.toJSON(); }\n if (this.marks.length)\n { obj.marks = this.marks.map(function (n) { return n.toJSON(); }); }\n return obj\n};\n\n// :: (Schema, Object) → Node\n// Deserialize a node from its JSON representation.\nNode.fromJSON = function fromJSON (schema, json) {\n if (!json) { throw new RangeError(\"Invalid input for Node.fromJSON\") }\n var marks = null;\n if (json.marks) {\n if (!Array.isArray(json.marks)) { throw new RangeError(\"Invalid mark data for Node.fromJSON\") }\n marks = json.marks.map(schema.markFromJSON);\n }\n if (json.type == \"text\") {\n if (typeof json.text != \"string\") { throw new RangeError(\"Invalid text node in JSON\") }\n return schema.text(json.text, marks)\n }\n var content = Fragment.fromJSON(schema, json.content);\n return schema.nodeType(json.type).create(json.attrs, content, marks)\n};\n\nObject.defineProperties( Node.prototype, prototypeAccessors$3 );\n\nvar TextNode = /*@__PURE__*/(function (Node) {\n function TextNode(type, attrs, content, marks) {\n Node.call(this, type, attrs, null, marks);\n\n if (!content) { throw new RangeError(\"Empty text nodes are not allowed\") }\n\n this.text = content;\n }\n\n if ( Node ) TextNode.__proto__ = Node;\n TextNode.prototype = Object.create( Node && Node.prototype );\n TextNode.prototype.constructor = TextNode;\n\n var prototypeAccessors$1 = { textContent: { configurable: true },nodeSize: { configurable: true } };\n\n TextNode.prototype.toString = function toString () {\n if (this.type.spec.toDebugString) { return this.type.spec.toDebugString(this) }\n return wrapMarks(this.marks, JSON.stringify(this.text))\n };\n\n prototypeAccessors$1.textContent.get = function () { return this.text };\n\n TextNode.prototype.textBetween = function textBetween (from, to) { return this.text.slice(from, to) };\n\n prototypeAccessors$1.nodeSize.get = function () { return this.text.length };\n\n TextNode.prototype.mark = function mark (marks) {\n return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks)\n };\n\n TextNode.prototype.withText = function withText (text) {\n if (text == this.text) { return this }\n return new TextNode(this.type, this.attrs, text, this.marks)\n };\n\n TextNode.prototype.cut = function cut (from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.text.length;\n\n if (from == 0 && to == this.text.length) { return this }\n return this.withText(this.text.slice(from, to))\n };\n\n TextNode.prototype.eq = function eq (other) {\n return this.sameMarkup(other) && this.text == other.text\n };\n\n TextNode.prototype.toJSON = function toJSON () {\n var base = Node.prototype.toJSON.call(this);\n base.text = this.text;\n return base\n };\n\n Object.defineProperties( TextNode.prototype, prototypeAccessors$1 );\n\n return TextNode;\n}(Node));\n\nfunction wrapMarks(marks, str) {\n for (var i = marks.length - 1; i >= 0; i--)\n { str = marks[i].type.name + \"(\" + str + \")\"; }\n return str\n}\n\n// ::- Instances of this class represent a match state of a node\n// type's [content expression](#model.NodeSpec.content), and can be\n// used to find out whether further content matches here, and whether\n// a given position is a valid end of the node.\nvar ContentMatch = function ContentMatch(validEnd) {\n // :: bool\n // True when this match state represents a valid end of the node.\n this.validEnd = validEnd;\n this.next = [];\n this.wrapCache = [];\n};\n\nvar prototypeAccessors$4 = { inlineContent: { configurable: true },defaultType: { configurable: true },edgeCount: { configurable: true } };\n\nContentMatch.parse = function parse (string, nodeTypes) {\n var stream = new TokenStream(string, nodeTypes);\n if (stream.next == null) { return ContentMatch.empty }\n var expr = parseExpr(stream);\n if (stream.next) { stream.err(\"Unexpected trailing text\"); }\n var match = dfa(nfa(expr));\n checkForDeadEnds(match, stream);\n return match\n};\n\n// :: (NodeType) → ?ContentMatch\n// Match a node type, returning a match after that node if\n// successful.\nContentMatch.prototype.matchType = function matchType (type) {\n for (var i = 0; i < this.next.length; i += 2)\n { if (this.next[i] == type) { return this.next[i + 1] } }\n return null\n};\n\n// :: (Fragment, ?number, ?number) → ?ContentMatch\n// Try to match a fragment. Returns the resulting match when\n// successful.\nContentMatch.prototype.matchFragment = function matchFragment (frag, start, end) {\n if ( start === void 0 ) start = 0;\n if ( end === void 0 ) end = frag.childCount;\n\n var cur = this;\n for (var i = start; cur && i < end; i++)\n { cur = cur.matchType(frag.child(i).type); }\n return cur\n};\n\nprototypeAccessors$4.inlineContent.get = function () {\n var first = this.next[0];\n return first ? first.isInline : false\n};\n\n// :: ?NodeType\n// Get the first matching node type at this match position that can\n// be generated.\nprototypeAccessors$4.defaultType.get = function () {\n for (var i = 0; i < this.next.length; i += 2) {\n var type = this.next[i];\n if (!(type.isText || type.hasRequiredAttrs())) { return type }\n }\n};\n\nContentMatch.prototype.compatible = function compatible (other) {\n for (var i = 0; i < this.next.length; i += 2)\n { for (var j = 0; j < other.next.length; j += 2)\n { if (this.next[i] == other.next[j]) { return true } } }\n return false\n};\n\n// :: (Fragment, bool, ?number) → ?Fragment\n// Try to match the given fragment, and if that fails, see if it can\n// be made to match by inserting nodes in front of it. When\n// successful, return a fragment of inserted nodes (which may be\n// empty if nothing had to be inserted). When `toEnd` is true, only\n// return a fragment if the resulting match goes to the end of the\n// content expression.\nContentMatch.prototype.fillBefore = function fillBefore (after, toEnd, startIndex) {\n if ( toEnd === void 0 ) toEnd = false;\n if ( startIndex === void 0 ) startIndex = 0;\n\n var seen = [this];\n function search(match, types) {\n var finished = match.matchFragment(after, startIndex);\n if (finished && (!toEnd || finished.validEnd))\n { return Fragment.from(types.map(function (tp) { return tp.createAndFill(); })) }\n\n for (var i = 0; i < match.next.length; i += 2) {\n var type = match.next[i], next = match.next[i + 1];\n if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {\n seen.push(next);\n var found = search(next, types.concat(type));\n if (found) { return found }\n }\n }\n }\n\n return search(this, [])\n};\n\n// :: (NodeType) → ?[NodeType]\n// Find a set of wrapping node types that would allow a node of the\n// given type to appear at this position. The result may be empty\n// (when it fits directly) and will be null when no such wrapping\n// exists.\nContentMatch.prototype.findWrapping = function findWrapping (target) {\n for (var i = 0; i < this.wrapCache.length; i += 2)\n { if (this.wrapCache[i] == target) { return this.wrapCache[i + 1] } }\n var computed = this.computeWrapping(target);\n this.wrapCache.push(target, computed);\n return computed\n};\n\nContentMatch.prototype.computeWrapping = function computeWrapping (target) {\n var seen = Object.create(null), active = [{match: this, type: null, via: null}];\n while (active.length) {\n var current = active.shift(), match = current.match;\n if (match.matchType(target)) {\n var result = [];\n for (var obj = current; obj.type; obj = obj.via)\n { result.push(obj.type); }\n return result.reverse()\n }\n for (var i = 0; i < match.next.length; i += 2) {\n var type = match.next[i];\n if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || match.next[i + 1].validEnd)) {\n active.push({match: type.contentMatch, type: type, via: current});\n seen[type.name] = true;\n }\n }\n }\n};\n\n// :: number\n// The number of outgoing edges this node has in the finite\n// automaton that describes the content expression.\nprototypeAccessors$4.edgeCount.get = function () {\n return this.next.length >> 1\n};\n\n// :: (number) → {type: NodeType, next: ContentMatch}\n// Get the _n_​th outgoing edge from this node in the finite\n// automaton that describes the content expression.\nContentMatch.prototype.edge = function edge (n) {\n var i = n << 1;\n if (i >= this.next.length) { throw new RangeError((\"There's no \" + n + \"th edge in this content match\")) }\n return {type: this.next[i], next: this.next[i + 1]}\n};\n\nContentMatch.prototype.toString = function toString () {\n var seen = [];\n function scan(m) {\n seen.push(m);\n for (var i = 1; i < m.next.length; i += 2)\n { if (seen.indexOf(m.next[i]) == -1) { scan(m.next[i]); } }\n }\n scan(this);\n return seen.map(function (m, i) {\n var out = i + (m.validEnd ? \"*\" : \" \") + \" \";\n for (var i$1 = 0; i$1 < m.next.length; i$1 += 2)\n { out += (i$1 ? \", \" : \"\") + m.next[i$1].name + \"->\" + seen.indexOf(m.next[i$1 + 1]); }\n return out\n }).join(\"\\n\")\n};\n\nObject.defineProperties( ContentMatch.prototype, prototypeAccessors$4 );\n\nContentMatch.empty = new ContentMatch(true);\n\nvar TokenStream = function TokenStream(string, nodeTypes) {\n this.string = string;\n this.nodeTypes = nodeTypes;\n this.inline = null;\n this.pos = 0;\n this.tokens = string.split(/\\s*(?=\\b|\\W|$)/);\n if (this.tokens[this.tokens.length - 1] == \"\") { this.tokens.pop(); }\n if (this.tokens[0] == \"\") { this.tokens.unshift(); }\n};\n\nvar prototypeAccessors$1$2 = { next: { configurable: true } };\n\nprototypeAccessors$1$2.next.get = function () { return this.tokens[this.pos] };\n\nTokenStream.prototype.eat = function eat (tok) { return this.next == tok && (this.pos++ || true) };\n\nTokenStream.prototype.err = function err (str) { throw new SyntaxError(str + \" (in content expression '\" + this.string + \"')\") };\n\nObject.defineProperties( TokenStream.prototype, prototypeAccessors$1$2 );\n\nfunction parseExpr(stream) {\n var exprs = [];\n do { exprs.push(parseExprSeq(stream)); }\n while (stream.eat(\"|\"))\n return exprs.length == 1 ? exprs[0] : {type: \"choice\", exprs: exprs}\n}\n\nfunction parseExprSeq(stream) {\n var exprs = [];\n do { exprs.push(parseExprSubscript(stream)); }\n while (stream.next && stream.next != \")\" && stream.next != \"|\")\n return exprs.length == 1 ? exprs[0] : {type: \"seq\", exprs: exprs}\n}\n\nfunction parseExprSubscript(stream) {\n var expr = parseExprAtom(stream);\n for (;;) {\n if (stream.eat(\"+\"))\n { expr = {type: \"plus\", expr: expr}; }\n else if (stream.eat(\"*\"))\n { expr = {type: \"star\", expr: expr}; }\n else if (stream.eat(\"?\"))\n { expr = {type: \"opt\", expr: expr}; }\n else if (stream.eat(\"{\"))\n { expr = parseExprRange(stream, expr); }\n else { break }\n }\n return expr\n}\n\nfunction parseNum(stream) {\n if (/\\D/.test(stream.next)) { stream.err(\"Expected number, got '\" + stream.next + \"'\"); }\n var result = Number(stream.next);\n stream.pos++;\n return result\n}\n\nfunction parseExprRange(stream, expr) {\n var min = parseNum(stream), max = min;\n if (stream.eat(\",\")) {\n if (stream.next != \"}\") { max = parseNum(stream); }\n else { max = -1; }\n }\n if (!stream.eat(\"}\")) { stream.err(\"Unclosed braced range\"); }\n return {type: \"range\", min: min, max: max, expr: expr}\n}\n\nfunction resolveName(stream, name) {\n var types = stream.nodeTypes, type = types[name];\n if (type) { return [type] }\n var result = [];\n for (var typeName in types) {\n var type$1 = types[typeName];\n if (type$1.groups.indexOf(name) > -1) { result.push(type$1); }\n }\n if (result.length == 0) { stream.err(\"No node type or group '\" + name + \"' found\"); }\n return result\n}\n\nfunction parseExprAtom(stream) {\n if (stream.eat(\"(\")) {\n var expr = parseExpr(stream);\n if (!stream.eat(\")\")) { stream.err(\"Missing closing paren\"); }\n return expr\n } else if (!/\\W/.test(stream.next)) {\n var exprs = resolveName(stream, stream.next).map(function (type) {\n if (stream.inline == null) { stream.inline = type.isInline; }\n else if (stream.inline != type.isInline) { stream.err(\"Mixing inline and block content\"); }\n return {type: \"name\", value: type}\n });\n stream.pos++;\n return exprs.length == 1 ? exprs[0] : {type: \"choice\", exprs: exprs}\n } else {\n stream.err(\"Unexpected token '\" + stream.next + \"'\");\n }\n}\n\n// The code below helps compile a regular-expression-like language\n// into a deterministic finite automaton. For a good introduction to\n// these concepts, see https://swtch.com/~rsc/regexp/regexp1.html\n\n// : (Object) → [[{term: ?any, to: number}]]\n// Construct an NFA from an expression as returned by the parser. The\n// NFA is represented as an array of states, which are themselves\n// arrays of edges, which are `{term, to}` objects. The first state is\n// the entry state and the last node is the success state.\n//\n// Note that unlike typical NFAs, the edge ordering in this one is\n// significant, in that it is used to contruct filler content when\n// necessary.\nfunction nfa(expr) {\n var nfa = [[]];\n connect(compile(expr, 0), node());\n return nfa\n\n function node() { return nfa.push([]) - 1 }\n function edge(from, to, term) {\n var edge = {term: term, to: to};\n nfa[from].push(edge);\n return edge\n }\n function connect(edges, to) { edges.forEach(function (edge) { return edge.to = to; }); }\n\n function compile(expr, from) {\n if (expr.type == \"choice\") {\n return expr.exprs.reduce(function (out, expr) { return out.concat(compile(expr, from)); }, [])\n } else if (expr.type == \"seq\") {\n for (var i = 0;; i++) {\n var next = compile(expr.exprs[i], from);\n if (i == expr.exprs.length - 1) { return next }\n connect(next, from = node());\n }\n } else if (expr.type == \"star\") {\n var loop = node();\n edge(from, loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)]\n } else if (expr.type == \"plus\") {\n var loop$1 = node();\n connect(compile(expr.expr, from), loop$1);\n connect(compile(expr.expr, loop$1), loop$1);\n return [edge(loop$1)]\n } else if (expr.type == \"opt\") {\n return [edge(from)].concat(compile(expr.expr, from))\n } else if (expr.type == \"range\") {\n var cur = from;\n for (var i$1 = 0; i$1 < expr.min; i$1++) {\n var next$1 = node();\n connect(compile(expr.expr, cur), next$1);\n cur = next$1;\n }\n if (expr.max == -1) {\n connect(compile(expr.expr, cur), cur);\n } else {\n for (var i$2 = expr.min; i$2 < expr.max; i$2++) {\n var next$2 = node();\n edge(cur, next$2);\n connect(compile(expr.expr, cur), next$2);\n cur = next$2;\n }\n }\n return [edge(cur)]\n } else if (expr.type == \"name\") {\n return [edge(from, null, expr.value)]\n }\n }\n}\n\nfunction cmp(a, b) { return b - a }\n\n// Get the set of nodes reachable by null edges from `node`. Omit\n// nodes with only a single null-out-edge, since they may lead to\n// needless duplicated nodes.\nfunction nullFrom(nfa, node) {\n var result = [];\n scan(node);\n return result.sort(cmp)\n\n function scan(node) {\n var edges = nfa[node];\n if (edges.length == 1 && !edges[0].term) { return scan(edges[0].to) }\n result.push(node);\n for (var i = 0; i < edges.length; i++) {\n var ref = edges[i];\n var term = ref.term;\n var to = ref.to;\n if (!term && result.indexOf(to) == -1) { scan(to); }\n }\n }\n}\n\n// : ([[{term: ?any, to: number}]]) → ContentMatch\n// Compiles an NFA as produced by `nfa` into a DFA, modeled as a set\n// of state objects (`ContentMatch` instances) with transitions\n// between them.\nfunction dfa(nfa) {\n var labeled = Object.create(null);\n return explore(nullFrom(nfa, 0))\n\n function explore(states) {\n var out = [];\n states.forEach(function (node) {\n nfa[node].forEach(function (ref) {\n var term = ref.term;\n var to = ref.to;\n\n if (!term) { return }\n var known = out.indexOf(term), set = known > -1 && out[known + 1];\n nullFrom(nfa, to).forEach(function (node) {\n if (!set) { out.push(term, set = []); }\n if (set.indexOf(node) == -1) { set.push(node); }\n });\n });\n });\n var state = labeled[states.join(\",\")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1);\n for (var i = 0; i < out.length; i += 2) {\n var states$1 = out[i + 1].sort(cmp);\n state.next.push(out[i], labeled[states$1.join(\",\")] || explore(states$1));\n }\n return state\n }\n}\n\nfunction checkForDeadEnds(match, stream) {\n for (var i = 0, work = [match]; i < work.length; i++) {\n var state = work[i], dead = !state.validEnd, nodes = [];\n for (var j = 0; j < state.next.length; j += 2) {\n var node = state.next[j], next = state.next[j + 1];\n nodes.push(node.name);\n if (dead && !(node.isText || node.hasRequiredAttrs())) { dead = false; }\n if (work.indexOf(next) == -1) { work.push(next); }\n }\n if (dead) { stream.err(\"Only non-generatable nodes (\" + nodes.join(\", \") + \") in a required position (see https://prosemirror.net/docs/guide/#generatable)\"); }\n }\n}\n\n// For node types where all attrs have a default value (or which don't\n// have any attributes), build up a single reusable default attribute\n// object, and use it for all nodes that don't specify specific\n// attributes.\nfunction defaultAttrs(attrs) {\n var defaults = Object.create(null);\n for (var attrName in attrs) {\n var attr = attrs[attrName];\n if (!attr.hasDefault) { return null }\n defaults[attrName] = attr.default;\n }\n return defaults\n}\n\nfunction computeAttrs(attrs, value) {\n var built = Object.create(null);\n for (var name in attrs) {\n var given = value && value[name];\n if (given === undefined) {\n var attr = attrs[name];\n if (attr.hasDefault) { given = attr.default; }\n else { throw new RangeError(\"No value supplied for attribute \" + name) }\n }\n built[name] = given;\n }\n return built\n}\n\nfunction initAttrs(attrs) {\n var result = Object.create(null);\n if (attrs) { for (var name in attrs) { result[name] = new Attribute(attrs[name]); } }\n return result\n}\n\n// ::- Node types are objects allocated once per `Schema` and used to\n// [tag](#model.Node.type) `Node` instances. They contain information\n// about the node type, such as its name and what kind of node it\n// represents.\nvar NodeType = function NodeType(name, schema, spec) {\n // :: string\n // The name the node type has in this schema.\n this.name = name;\n\n // :: Schema\n // A link back to the `Schema` the node type belongs to.\n this.schema = schema;\n\n // :: NodeSpec\n // The spec that this type is based on\n this.spec = spec;\n\n this.groups = spec.group ? spec.group.split(\" \") : [];\n this.attrs = initAttrs(spec.attrs);\n\n this.defaultAttrs = defaultAttrs(this.attrs);\n\n // :: ContentMatch\n // The starting match of the node type's content expression.\n this.contentMatch = null;\n\n // : ?[MarkType]\n // The set of marks allowed in this node. `null` means all marks\n // are allowed.\n this.markSet = null;\n\n // :: bool\n // True if this node type has inline content.\n this.inlineContent = null;\n\n // :: bool\n // True if this is a block type\n this.isBlock = !(spec.inline || name == \"text\");\n\n // :: bool\n // True if this is the text node type.\n this.isText = name == \"text\";\n};\n\nvar prototypeAccessors$5 = { isInline: { configurable: true },isTextblock: { configurable: true },isLeaf: { configurable: true },isAtom: { configurable: true } };\n\n// :: bool\n// True if this is an inline type.\nprototypeAccessors$5.isInline.get = function () { return !this.isBlock };\n\n// :: bool\n// True if this is a textblock type, a block that contains inline\n// content.\nprototypeAccessors$5.isTextblock.get = function () { return this.isBlock && this.inlineContent };\n\n// :: bool\n// True for node types that allow no content.\nprototypeAccessors$5.isLeaf.get = function () { return this.contentMatch == ContentMatch.empty };\n\n// :: bool\n// True when this node is an atom, i.e. when it does not have\n// directly editable content.\nprototypeAccessors$5.isAtom.get = function () { return this.isLeaf || this.spec.atom };\n\n// :: () → bool\n// Tells you whether this node type has any required attributes.\nNodeType.prototype.hasRequiredAttrs = function hasRequiredAttrs () {\n for (var n in this.attrs) { if (this.attrs[n].isRequired) { return true } }\n return false\n};\n\nNodeType.prototype.compatibleContent = function compatibleContent (other) {\n return this == other || this.contentMatch.compatible(other.contentMatch)\n};\n\nNodeType.prototype.computeAttrs = function computeAttrs$1 (attrs) {\n if (!attrs && this.defaultAttrs) { return this.defaultAttrs }\n else { return computeAttrs(this.attrs, attrs) }\n};\n\n// :: (?Object, ?union, ?[Mark]) → Node\n// Create a `Node` of this type. The given attributes are\n// checked and defaulted (you can pass `null` to use the type's\n// defaults entirely, if no required attributes exist). `content`\n// may be a `Fragment`, a node, an array of nodes, or\n// `null`. Similarly `marks` may be `null` to default to the empty\n// set of marks.\nNodeType.prototype.create = function create (attrs, content, marks) {\n if (this.isText) { throw new Error(\"NodeType.create can't construct text nodes\") }\n return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks))\n};\n\n// :: (?Object, ?union, ?[Mark]) → Node\n// Like [`create`](#model.NodeType.create), but check the given content\n// against the node type's content restrictions, and throw an error\n// if it doesn't match.\nNodeType.prototype.createChecked = function createChecked (attrs, content, marks) {\n content = Fragment.from(content);\n if (!this.validContent(content))\n { throw new RangeError(\"Invalid content for node \" + this.name) }\n return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks))\n};\n\n// :: (?Object, ?union, ?[Mark]) → ?Node\n// Like [`create`](#model.NodeType.create), but see if it is necessary to\n// add nodes to the start or end of the given fragment to make it\n// fit the node. If no fitting wrapping can be found, return null.\n// Note that, due to the fact that required nodes can always be\n// created, this will always succeed if you pass null or\n// `Fragment.empty` as content.\nNodeType.prototype.createAndFill = function createAndFill (attrs, content, marks) {\n attrs = this.computeAttrs(attrs);\n content = Fragment.from(content);\n if (content.size) {\n var before = this.contentMatch.fillBefore(content);\n if (!before) { return null }\n content = before.append(content);\n }\n var after = this.contentMatch.matchFragment(content).fillBefore(Fragment.empty, true);\n if (!after) { return null }\n return new Node(this, attrs, content.append(after), Mark.setFrom(marks))\n};\n\n// :: (Fragment) → bool\n// Returns true if the given fragment is valid content for this node\n// type with the given attributes.\nNodeType.prototype.validContent = function validContent (content) {\n var result = this.contentMatch.matchFragment(content);\n if (!result || !result.validEnd) { return false }\n for (var i = 0; i < content.childCount; i++)\n { if (!this.allowsMarks(content.child(i).marks)) { return false } }\n return true\n};\n\n// :: (MarkType) → bool\n// Check whether the given mark type is allowed in this node.\nNodeType.prototype.allowsMarkType = function allowsMarkType (markType) {\n return this.markSet == null || this.markSet.indexOf(markType) > -1\n};\n\n// :: ([Mark]) → bool\n// Test whether the given set of marks are allowed in this node.\nNodeType.prototype.allowsMarks = function allowsMarks (marks) {\n if (this.markSet == null) { return true }\n for (var i = 0; i < marks.length; i++) { if (!this.allowsMarkType(marks[i].type)) { return false } }\n return true\n};\n\n// :: ([Mark]) → [Mark]\n// Removes the marks that are not allowed in this node from the given set.\nNodeType.prototype.allowedMarks = function allowedMarks (marks) {\n if (this.markSet == null) { return marks }\n var copy;\n for (var i = 0; i < marks.length; i++) {\n if (!this.allowsMarkType(marks[i].type)) {\n if (!copy) { copy = marks.slice(0, i); }\n } else if (copy) {\n copy.push(marks[i]);\n }\n }\n return !copy ? marks : copy.length ? copy : Mark.empty\n};\n\nNodeType.compile = function compile (nodes, schema) {\n var result = Object.create(null);\n nodes.forEach(function (name, spec) { return result[name] = new NodeType(name, schema, spec); });\n\n var topType = schema.spec.topNode || \"doc\";\n if (!result[topType]) { throw new RangeError(\"Schema is missing its top node type ('\" + topType + \"')\") }\n if (!result.text) { throw new RangeError(\"Every schema needs a 'text' type\") }\n for (var _ in result.text.attrs) { throw new RangeError(\"The text node type should not have attributes\") }\n\n return result\n};\n\nObject.defineProperties( NodeType.prototype, prototypeAccessors$5 );\n\n// Attribute descriptors\n\nvar Attribute = function Attribute(options) {\n this.hasDefault = Object.prototype.hasOwnProperty.call(options, \"default\");\n this.default = options.default;\n};\n\nvar prototypeAccessors$1$3 = { isRequired: { configurable: true } };\n\nprototypeAccessors$1$3.isRequired.get = function () {\n return !this.hasDefault\n};\n\nObject.defineProperties( Attribute.prototype, prototypeAccessors$1$3 );\n\n// Marks\n\n// ::- Like nodes, marks (which are associated with nodes to signify\n// things like emphasis or being part of a link) are\n// [tagged](#model.Mark.type) with type objects, which are\n// instantiated once per `Schema`.\nvar MarkType = function MarkType(name, rank, schema, spec) {\n // :: string\n // The name of the mark type.\n this.name = name;\n\n // :: Schema\n // The schema that this mark type instance is part of.\n this.schema = schema;\n\n // :: MarkSpec\n // The spec on which the type is based.\n this.spec = spec;\n\n this.attrs = initAttrs(spec.attrs);\n\n this.rank = rank;\n this.excluded = null;\n var defaults = defaultAttrs(this.attrs);\n this.instance = defaults && new Mark(this, defaults);\n};\n\n// :: (?Object) → Mark\n// Create a mark of this type. `attrs` may be `null` or an object\n// containing only some of the mark's attributes. The others, if\n// they have defaults, will be added.\nMarkType.prototype.create = function create (attrs) {\n if (!attrs && this.instance) { return this.instance }\n return new Mark(this, computeAttrs(this.attrs, attrs))\n};\n\nMarkType.compile = function compile (marks, schema) {\n var result = Object.create(null), rank = 0;\n marks.forEach(function (name, spec) { return result[name] = new MarkType(name, rank++, schema, spec); });\n return result\n};\n\n// :: ([Mark]) → [Mark]\n// When there is a mark of this type in the given set, a new set\n// without it is returned. Otherwise, the input set is returned.\nMarkType.prototype.removeFromSet = function removeFromSet (set) {\n for (var i = 0; i < set.length; i++)\n { if (set[i].type == this)\n { return set.slice(0, i).concat(set.slice(i + 1)) } }\n return set\n};\n\n// :: ([Mark]) → ?Mark\n// Tests whether there is a mark of this type in the given set.\nMarkType.prototype.isInSet = function isInSet (set) {\n for (var i = 0; i < set.length; i++)\n { if (set[i].type == this) { return set[i] } }\n};\n\n// :: (MarkType) → bool\n// Queries whether a given mark type is\n// [excluded](#model.MarkSpec.excludes) by this one.\nMarkType.prototype.excludes = function excludes (other) {\n return this.excluded.indexOf(other) > -1\n};\n\n// SchemaSpec:: interface\n// An object describing a schema, as passed to the [`Schema`](#model.Schema)\n// constructor.\n//\n// nodes:: union, OrderedMap>\n// The node types in this schema. Maps names to\n// [`NodeSpec`](#model.NodeSpec) objects that describe the node type\n// associated with that name. Their order is significant—it\n// determines which [parse rules](#model.NodeSpec.parseDOM) take\n// precedence by default, and which nodes come first in a given\n// [group](#model.NodeSpec.group).\n//\n// marks:: ?union, OrderedMap>\n// The mark types that exist in this schema. The order in which they\n// are provided determines the order in which [mark\n// sets](#model.Mark.addToSet) are sorted and in which [parse\n// rules](#model.MarkSpec.parseDOM) are tried.\n//\n// topNode:: ?string\n// The name of the default top-level node for the schema. Defaults\n// to `\"doc\"`.\n\n// NodeSpec:: interface\n//\n// content:: ?string\n// The content expression for this node, as described in the [schema\n// guide](/docs/guide/#schema.content_expressions). When not given,\n// the node does not allow any content.\n//\n// marks:: ?string\n// The marks that are allowed inside of this node. May be a\n// space-separated string referring to mark names or groups, `\"_\"`\n// to explicitly allow all marks, or `\"\"` to disallow marks. When\n// not given, nodes with inline content default to allowing all\n// marks, other nodes default to not allowing marks.\n//\n// group:: ?string\n// The group or space-separated groups to which this node belongs,\n// which can be referred to in the content expressions for the\n// schema.\n//\n// inline:: ?bool\n// Should be set to true for inline nodes. (Implied for text nodes.)\n//\n// atom:: ?bool\n// Can be set to true to indicate that, though this isn't a [leaf\n// node](#model.NodeType.isLeaf), it doesn't have directly editable\n// content and should be treated as a single unit in the view.\n//\n// attrs:: ?Object\n// The attributes that nodes of this type get.\n//\n// selectable:: ?bool\n// Controls whether nodes of this type can be selected as a [node\n// selection](#state.NodeSelection). Defaults to true for non-text\n// nodes.\n//\n// draggable:: ?bool\n// Determines whether nodes of this type can be dragged without\n// being selected. Defaults to false.\n//\n// code:: ?bool\n// Can be used to indicate that this node contains code, which\n// causes some commands to behave differently.\n//\n// defining:: ?bool\n// Determines whether this node is considered an important parent\n// node during replace operations (such as paste). Non-defining (the\n// default) nodes get dropped when their entire content is replaced,\n// whereas defining nodes persist and wrap the inserted content.\n// Likewise, in _inserted_ content the defining parents of the\n// content are preserved when possible. Typically,\n// non-default-paragraph textblock types, and possibly list items,\n// are marked as defining.\n//\n// isolating:: ?bool\n// When enabled (default is false), the sides of nodes of this type\n// count as boundaries that regular editing operations, like\n// backspacing or lifting, won't cross. An example of a node that\n// should probably have this enabled is a table cell.\n//\n// toDOM:: ?(node: Node) → DOMOutputSpec\n// Defines the default way a node of this type should be serialized\n// to DOM/HTML (as used by\n// [`DOMSerializer.fromSchema`](#model.DOMSerializer^fromSchema)).\n// Should return a DOM node or an [array\n// structure](#model.DOMOutputSpec) that describes one, with an\n// optional number zero (“hole”) in it to indicate where the node's\n// content should be inserted.\n//\n// For text nodes, the default is to create a text DOM node. Though\n// it is possible to create a serializer where text is rendered\n// differently, this is not supported inside the editor, so you\n// shouldn't override that in your text node spec.\n//\n// parseDOM:: ?[ParseRule]\n// Associates DOM parser information with this node, which can be\n// used by [`DOMParser.fromSchema`](#model.DOMParser^fromSchema) to\n// automatically derive a parser. The `node` field in the rules is\n// implied (the name of this node will be filled in automatically).\n// If you supply your own parser, you do not need to also specify\n// parsing rules in your schema.\n//\n// toDebugString:: ?(node: Node) -> string\n// Defines the default way a node of this type should be serialized\n// to a string representation for debugging (e.g. in error messages).\n\n// MarkSpec:: interface\n//\n// attrs:: ?Object\n// The attributes that marks of this type get.\n//\n// inclusive:: ?bool\n// Whether this mark should be active when the cursor is positioned\n// at its end (or at its start when that is also the start of the\n// parent node). Defaults to true.\n//\n// excludes:: ?string\n// Determines which other marks this mark can coexist with. Should\n// be a space-separated strings naming other marks or groups of marks.\n// When a mark is [added](#model.Mark.addToSet) to a set, all marks\n// that it excludes are removed in the process. If the set contains\n// any mark that excludes the new mark but is not, itself, excluded\n// by the new mark, the mark can not be added an the set. You can\n// use the value `\"_\"` to indicate that the mark excludes all\n// marks in the schema.\n//\n// Defaults to only being exclusive with marks of the same type. You\n// can set it to an empty string (or any string not containing the\n// mark's own name) to allow multiple marks of a given type to\n// coexist (as long as they have different attributes).\n//\n// group:: ?string\n// The group or space-separated groups to which this mark belongs.\n//\n// spanning:: ?bool\n// Determines whether marks of this type can span multiple adjacent\n// nodes when serialized to DOM/HTML. Defaults to true.\n//\n// toDOM:: ?(mark: Mark, inline: bool) → DOMOutputSpec\n// Defines the default way marks of this type should be serialized\n// to DOM/HTML. When the resulting spec contains a hole, that is\n// where the marked content is placed. Otherwise, it is appended to\n// the top node.\n//\n// parseDOM:: ?[ParseRule]\n// Associates DOM parser information with this mark (see the\n// corresponding [node spec field](#model.NodeSpec.parseDOM)). The\n// `mark` field in the rules is implied.\n\n// AttributeSpec:: interface\n//\n// Used to [define](#model.NodeSpec.attrs) attributes on nodes or\n// marks.\n//\n// default:: ?any\n// The default value for this attribute, to use when no explicit\n// value is provided. Attributes that have no default must be\n// provided whenever a node or mark of a type that has them is\n// created.\n\n// ::- A document schema. Holds [node](#model.NodeType) and [mark\n// type](#model.MarkType) objects for the nodes and marks that may\n// occur in conforming documents, and provides functionality for\n// creating and deserializing such documents.\nvar Schema = function Schema(spec) {\n // :: SchemaSpec\n // The [spec](#model.SchemaSpec) on which the schema is based,\n // with the added guarantee that its `nodes` and `marks`\n // properties are\n // [`OrderedMap`](https://github.com/marijnh/orderedmap) instances\n // (not raw objects).\n this.spec = {};\n for (var prop in spec) { this.spec[prop] = spec[prop]; }\n this.spec.nodes = OrderedMap.from(spec.nodes);\n this.spec.marks = OrderedMap.from(spec.marks);\n\n // :: Object\n // An object mapping the schema's node names to node type objects.\n this.nodes = NodeType.compile(this.spec.nodes, this);\n\n // :: Object\n // A map from mark names to mark type objects.\n this.marks = MarkType.compile(this.spec.marks, this);\n\n var contentExprCache = Object.create(null);\n for (var prop$1 in this.nodes) {\n if (prop$1 in this.marks)\n { throw new RangeError(prop$1 + \" can not be both a node and a mark\") }\n var type = this.nodes[prop$1], contentExpr = type.spec.content || \"\", markExpr = type.spec.marks;\n type.contentMatch = contentExprCache[contentExpr] ||\n (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));\n type.inlineContent = type.contentMatch.inlineContent;\n type.markSet = markExpr == \"_\" ? null :\n markExpr ? gatherMarks(this, markExpr.split(\" \")) :\n markExpr == \"\" || !type.inlineContent ? [] : null;\n }\n for (var prop$2 in this.marks) {\n var type$1 = this.marks[prop$2], excl = type$1.spec.excludes;\n type$1.excluded = excl == null ? [type$1] : excl == \"\" ? [] : gatherMarks(this, excl.split(\" \"));\n }\n\n this.nodeFromJSON = this.nodeFromJSON.bind(this);\n this.markFromJSON = this.markFromJSON.bind(this);\n\n // :: NodeType\n // The type of the [default top node](#model.SchemaSpec.topNode)\n // for this schema.\n this.topNodeType = this.nodes[this.spec.topNode || \"doc\"];\n\n // :: Object\n // An object for storing whatever values modules may want to\n // compute and cache per schema. (If you want to store something\n // in it, try to use property names unlikely to clash.)\n this.cached = Object.create(null);\n this.cached.wrappings = Object.create(null);\n};\n\n// :: (union, ?Object, ?union, ?[Mark]) → Node\n// Create a node in this schema. The `type` may be a string or a\n// `NodeType` instance. Attributes will be extended\n// with defaults, `content` may be a `Fragment`,\n// `null`, a `Node`, or an array of nodes.\nSchema.prototype.node = function node (type, attrs, content, marks) {\n if (typeof type == \"string\")\n { type = this.nodeType(type); }\n else if (!(type instanceof NodeType))\n { throw new RangeError(\"Invalid node type: \" + type) }\n else if (type.schema != this)\n { throw new RangeError(\"Node type from different schema used (\" + type.name + \")\") }\n\n return type.createChecked(attrs, content, marks)\n};\n\n// :: (string, ?[Mark]) → Node\n// Create a text node in the schema. Empty text nodes are not\n// allowed.\nSchema.prototype.text = function text (text$1, marks) {\n var type = this.nodes.text;\n return new TextNode(type, type.defaultAttrs, text$1, Mark.setFrom(marks))\n};\n\n// :: (union, ?Object) → Mark\n// Create a mark with the given type and attributes.\nSchema.prototype.mark = function mark (type, attrs) {\n if (typeof type == \"string\") { type = this.marks[type]; }\n return type.create(attrs)\n};\n\n// :: (Object) → Node\n// Deserialize a node from its JSON representation. This method is\n// bound.\nSchema.prototype.nodeFromJSON = function nodeFromJSON (json) {\n return Node.fromJSON(this, json)\n};\n\n// :: (Object) → Mark\n// Deserialize a mark from its JSON representation. This method is\n// bound.\nSchema.prototype.markFromJSON = function markFromJSON (json) {\n return Mark.fromJSON(this, json)\n};\n\nSchema.prototype.nodeType = function nodeType (name) {\n var found = this.nodes[name];\n if (!found) { throw new RangeError(\"Unknown node type: \" + name) }\n return found\n};\n\nfunction gatherMarks(schema, marks) {\n var found = [];\n for (var i = 0; i < marks.length; i++) {\n var name = marks[i], mark = schema.marks[name], ok = mark;\n if (mark) {\n found.push(mark);\n } else {\n for (var prop in schema.marks) {\n var mark$1 = schema.marks[prop];\n if (name == \"_\" || (mark$1.spec.group && mark$1.spec.group.split(\" \").indexOf(name) > -1))\n { found.push(ok = mark$1); }\n }\n }\n if (!ok) { throw new SyntaxError(\"Unknown mark type: '\" + marks[i] + \"'\") }\n }\n return found\n}\n\n// ParseOptions:: interface\n// These are the options recognized by the\n// [`parse`](#model.DOMParser.parse) and\n// [`parseSlice`](#model.DOMParser.parseSlice) methods.\n//\n// preserveWhitespace:: ?union\n// By default, whitespace is collapsed as per HTML's rules. Pass\n// `true` to preserve whitespace, but normalize newlines to\n// spaces, and `\"full\"` to preserve whitespace entirely.\n//\n// findPositions:: ?[{node: dom.Node, offset: number}]\n// When given, the parser will, beside parsing the content,\n// record the document positions of the given DOM positions. It\n// will do so by writing to the objects, adding a `pos` property\n// that holds the document position. DOM positions that are not\n// in the parsed content will not be written to.\n//\n// from:: ?number\n// The child node index to start parsing from.\n//\n// to:: ?number\n// The child node index to stop parsing at.\n//\n// topNode:: ?Node\n// By default, the content is parsed into the schema's default\n// [top node type](#model.Schema.topNodeType). You can pass this\n// option to use the type and attributes from a different node\n// as the top container.\n//\n// topMatch:: ?ContentMatch\n// Provide the starting content match that content parsed into the\n// top node is matched against.\n//\n// context:: ?ResolvedPos\n// A set of additional nodes to count as\n// [context](#model.ParseRule.context) when parsing, above the\n// given [top node](#model.ParseOptions.topNode).\n\n// ParseRule:: interface\n// A value that describes how to parse a given DOM node or inline\n// style as a ProseMirror node or mark.\n//\n// tag:: ?string\n// A CSS selector describing the kind of DOM elements to match. A\n// single rule should have _either_ a `tag` or a `style` property.\n//\n// namespace:: ?string\n// The namespace to match. This should be used with `tag`.\n// Nodes are only matched when the namespace matches or this property\n// is null.\n//\n// style:: ?string\n// A CSS property name to match. When given, this rule matches\n// inline styles that list that property. May also have the form\n// `\"property=value\"`, in which case the rule only matches if the\n// property's value exactly matches the given value. (For more\n// complicated filters, use [`getAttrs`](#model.ParseRule.getAttrs)\n// and return false to indicate that the match failed.)\n//\n// priority:: ?number\n// Can be used to change the order in which the parse rules in a\n// schema are tried. Those with higher priority come first. Rules\n// without a priority are counted as having priority 50. This\n// property is only meaningful in a schema—when directly\n// constructing a parser, the order of the rule array is used.\n//\n// context:: ?string\n// When given, restricts this rule to only match when the current\n// context—the parent nodes into which the content is being\n// parsed—matches this expression. Should contain one or more node\n// names or node group names followed by single or double slashes.\n// For example `\"paragraph/\"` means the rule only matches when the\n// parent node is a paragraph, `\"blockquote/paragraph/\"` restricts\n// it to be in a paragraph that is inside a blockquote, and\n// `\"section//\"` matches any position inside a section—a double\n// slash matches any sequence of ancestor nodes. To allow multiple\n// different contexts, they can be separated by a pipe (`|`)\n// character, as in `\"blockquote/|list_item/\"`.\n//\n// node:: ?string\n// The name of the node type to create when this rule matches. Only\n// valid for rules with a `tag` property, not for style rules. Each\n// rule should have one of a `node`, `mark`, or `ignore` property\n// (except when it appears in a [node](#model.NodeSpec.parseDOM) or\n// [mark spec](#model.MarkSpec.parseDOM), in which case the `node`\n// or `mark` property will be derived from its position).\n//\n// mark:: ?string\n// The name of the mark type to wrap the matched content in.\n//\n// ignore:: ?bool\n// When true, ignore content that matches this rule.\n//\n// closeParent:: ?bool\n// When true, finding an element that matches this rule will close\n// the current node.\n//\n// skip:: ?bool\n// When true, ignore the node that matches this rule, but do parse\n// its content.\n//\n// attrs:: ?Object\n// Attributes for the node or mark created by this rule. When\n// `getAttrs` is provided, it takes precedence.\n//\n// getAttrs:: ?(union) → ?union\n// A function used to compute the attributes for the node or mark\n// created by this rule. Can also be used to describe further\n// conditions the DOM element or style must match. When it returns\n// `false`, the rule won't match. When it returns null or undefined,\n// that is interpreted as an empty/default set of attributes.\n//\n// Called with a DOM Element for `tag` rules, and with a string (the\n// style's value) for `style` rules.\n//\n// contentElement:: ?union\n// For `tag` rules that produce non-leaf nodes or marks, by default\n// the content of the DOM element is parsed as content of the mark\n// or node. If the child nodes are in a descendent node, this may be\n// a CSS selector string that the parser must use to find the actual\n// content element, or a function that returns the actual content\n// element to the parser.\n//\n// getContent:: ?(dom.Node, schema: Schema) → Fragment\n// Can be used to override the content of a matched node. When\n// present, instead of parsing the node's child nodes, the result of\n// this function is used.\n//\n// preserveWhitespace:: ?union\n// Controls whether whitespace should be preserved when parsing the\n// content inside the matched element. `false` means whitespace may\n// be collapsed, `true` means that whitespace should be preserved\n// but newlines normalized to spaces, and `\"full\"` means that\n// newlines should also be preserved.\n\n// ::- A DOM parser represents a strategy for parsing DOM content into\n// a ProseMirror document conforming to a given schema. Its behavior\n// is defined by an array of [rules](#model.ParseRule).\nvar DOMParser = function DOMParser(schema, rules) {\n var this$1 = this;\n\n // :: Schema\n // The schema into which the parser parses.\n this.schema = schema;\n // :: [ParseRule]\n // The set of [parse rules](#model.ParseRule) that the parser\n // uses, in order of precedence.\n this.rules = rules;\n this.tags = [];\n this.styles = [];\n\n rules.forEach(function (rule) {\n if (rule.tag) { this$1.tags.push(rule); }\n else if (rule.style) { this$1.styles.push(rule); }\n });\n\n // Only normalize list elements when lists in the schema can't directly contain themselves\n this.normalizeLists = !this.tags.some(function (r) {\n if (!/^(ul|ol)\\b/.test(r.tag) || !r.node) { return false }\n var node = schema.nodes[r.node];\n return node.contentMatch.matchType(node)\n });\n};\n\n// :: (dom.Node, ?ParseOptions) → Node\n// Parse a document from the content of a DOM node.\nDOMParser.prototype.parse = function parse (dom, options) {\n if ( options === void 0 ) options = {};\n\n var context = new ParseContext(this, options, false);\n context.addAll(dom, null, options.from, options.to);\n return context.finish()\n};\n\n// :: (dom.Node, ?ParseOptions) → Slice\n// Parses the content of the given DOM node, like\n// [`parse`](#model.DOMParser.parse), and takes the same set of\n// options. But unlike that method, which produces a whole node,\n// this one returns a slice that is open at the sides, meaning that\n// the schema constraints aren't applied to the start of nodes to\n// the left of the input and the end of nodes at the end.\nDOMParser.prototype.parseSlice = function parseSlice (dom, options) {\n if ( options === void 0 ) options = {};\n\n var context = new ParseContext(this, options, true);\n context.addAll(dom, null, options.from, options.to);\n return Slice.maxOpen(context.finish())\n};\n\nDOMParser.prototype.matchTag = function matchTag (dom, context) {\n for (var i = 0; i < this.tags.length; i++) {\n var rule = this.tags[i];\n if (matches(dom, rule.tag) &&\n (rule.namespace === undefined || dom.namespaceURI == rule.namespace) &&\n (!rule.context || context.matchesContext(rule.context))) {\n if (rule.getAttrs) {\n var result = rule.getAttrs(dom);\n if (result === false) { continue }\n rule.attrs = result;\n }\n return rule\n }\n }\n};\n\nDOMParser.prototype.matchStyle = function matchStyle (prop, value, context) {\n for (var i = 0; i < this.styles.length; i++) {\n var rule = this.styles[i];\n if (rule.style.indexOf(prop) != 0 ||\n rule.context && !context.matchesContext(rule.context) ||\n // Test that the style string either precisely matches the prop,\n // or has an '=' sign after the prop, followed by the given\n // value.\n rule.style.length > prop.length &&\n (rule.style.charCodeAt(prop.length) != 61 || rule.style.slice(prop.length + 1) != value))\n { continue }\n if (rule.getAttrs) {\n var result = rule.getAttrs(value);\n if (result === false) { continue }\n rule.attrs = result;\n }\n return rule\n }\n};\n\n// : (Schema) → [ParseRule]\nDOMParser.schemaRules = function schemaRules (schema) {\n var result = [];\n function insert(rule) {\n var priority = rule.priority == null ? 50 : rule.priority, i = 0;\n for (; i < result.length; i++) {\n var next = result[i], nextPriority = next.priority == null ? 50 : next.priority;\n if (nextPriority < priority) { break }\n }\n result.splice(i, 0, rule);\n }\n\n var loop = function ( name ) {\n var rules = schema.marks[name].spec.parseDOM;\n if (rules) { rules.forEach(function (rule) {\n insert(rule = copy(rule));\n rule.mark = name;\n }); }\n };\n\n for (var name in schema.marks) loop( name );\n var loop$1 = function ( name ) {\n var rules$1 = schema.nodes[name$1].spec.parseDOM;\n if (rules$1) { rules$1.forEach(function (rule) {\n insert(rule = copy(rule));\n rule.node = name$1;\n }); }\n };\n\n for (var name$1 in schema.nodes) loop$1();\n return result\n};\n\n// :: (Schema) → DOMParser\n// Construct a DOM parser using the parsing rules listed in a\n// schema's [node specs](#model.NodeSpec.parseDOM), reordered by\n// [priority](#model.ParseRule.priority).\nDOMParser.fromSchema = function fromSchema (schema) {\n return schema.cached.domParser ||\n (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema)))\n};\n\n// : Object The block-level tags in HTML5\nvar blockTags = {\n address: true, article: true, aside: true, blockquote: true, canvas: true,\n dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true,\n footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true,\n h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true,\n output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true\n};\n\n// : Object The tags that we normally ignore.\nvar ignoreTags = {\n head: true, noscript: true, object: true, script: true, style: true, title: true\n};\n\n// : Object List tags.\nvar listTags = {ol: true, ul: true};\n\n// Using a bitfield for node context options\nvar OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4;\n\nfunction wsOptionsFor(preserveWhitespace) {\n return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === \"full\" ? OPT_PRESERVE_WS_FULL : 0)\n}\n\nvar NodeContext = function NodeContext(type, attrs, marks, pendingMarks, solid, match, options) {\n this.type = type;\n this.attrs = attrs;\n this.solid = solid;\n this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);\n this.options = options;\n this.content = [];\n // Marks applied to this node itself\n this.marks = marks;\n // Marks applied to its children\n this.activeMarks = Mark.none;\n // Marks that can't apply here, but will be used in children if possible\n this.pendingMarks = pendingMarks;\n // Nested Marks with same type\n this.stashMarks = [];\n};\n\nNodeContext.prototype.findWrapping = function findWrapping (node) {\n if (!this.match) {\n if (!this.type) { return [] }\n var fill = this.type.contentMatch.fillBefore(Fragment.from(node));\n if (fill) {\n this.match = this.type.contentMatch.matchFragment(fill);\n } else {\n var start = this.type.contentMatch, wrap;\n if (wrap = start.findWrapping(node.type)) {\n this.match = start;\n return wrap\n } else {\n return null\n }\n }\n }\n return this.match.findWrapping(node.type)\n};\n\nNodeContext.prototype.finish = function finish (openEnd) {\n if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace\n var last = this.content[this.content.length - 1], m;\n if (last && last.isText && (m = /[ \\t\\r\\n\\u000c]+$/.exec(last.text))) {\n if (last.text.length == m[0].length) { this.content.pop(); }\n else { this.content[this.content.length - 1] = last.withText(last.text.slice(0, last.text.length - m[0].length)); }\n }\n }\n var content = Fragment.from(this.content);\n if (!openEnd && this.match)\n { content = content.append(this.match.fillBefore(Fragment.empty, true)); }\n return this.type ? this.type.create(this.attrs, content, this.marks) : content\n};\n\nNodeContext.prototype.popFromStashMark = function popFromStashMark (markType) {\n for (var i = this.stashMarks.length - 1; i >= 0; i--)\n { if (this.stashMarks[i].type == markType) { return this.stashMarks.splice(i, 1)[0] } }\n};\n\nNodeContext.prototype.applyPending = function applyPending (nextType) {\n for (var i = 0, pending = this.pendingMarks; i < pending.length; i++) {\n var mark = pending[i];\n if ((this.type ? this.type.allowsMarkType(mark.type) : markMayApply(mark.type, nextType)) &&\n !mark.isInSet(this.activeMarks)) {\n var found = findSameTypeInSet(mark, this.activeMarks);\n if (found) { this.stashMarks.push(found); }\n this.activeMarks = mark.addToSet(this.activeMarks);\n this.pendingMarks = mark.removeFromSet(this.pendingMarks);\n }\n }\n};\n\nvar ParseContext = function ParseContext(parser, options, open) {\n // : DOMParser The parser we are using.\n this.parser = parser;\n // : Object The options passed to this parse.\n this.options = options;\n this.isOpen = open;\n var topNode = options.topNode, topContext;\n var topOptions = wsOptionsFor(options.preserveWhitespace) | (open ? OPT_OPEN_LEFT : 0);\n if (topNode)\n { topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, Mark.none, true,\n options.topMatch || topNode.type.contentMatch, topOptions); }\n else if (open)\n { topContext = new NodeContext(null, null, Mark.none, Mark.none, true, null, topOptions); }\n else\n { topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, Mark.none, true, null, topOptions); }\n this.nodes = [topContext];\n // : [Mark] The current set of marks\n this.open = 0;\n this.find = options.findPositions;\n this.needsBlock = false;\n};\n\nvar prototypeAccessors$6 = { top: { configurable: true },currentPos: { configurable: true } };\n\nprototypeAccessors$6.top.get = function () {\n return this.nodes[this.open]\n};\n\n// : (dom.Node)\n// Add a DOM node to the content. Text is inserted as text node,\n// otherwise, the node is passed to `addElement` or, if it has a\n// `style` attribute, `addElementWithStyles`.\nParseContext.prototype.addDOM = function addDOM (dom) {\n if (dom.nodeType == 3) {\n this.addTextNode(dom);\n } else if (dom.nodeType == 1) {\n var style = dom.getAttribute(\"style\");\n var marks = style ? this.readStyles(parseStyles(style)) : null, top = this.top;\n if (marks != null) { for (var i = 0; i < marks.length; i++) { this.addPendingMark(marks[i]); } }\n this.addElement(dom);\n if (marks != null) { for (var i$1 = 0; i$1 < marks.length; i$1++) { this.removePendingMark(marks[i$1], top); } }\n }\n};\n\nParseContext.prototype.addTextNode = function addTextNode (dom) {\n var value = dom.nodeValue;\n var top = this.top;\n if ((top.type ? top.type.inlineContent : top.content.length && top.content[0].isInline) || /[^ \\t\\r\\n\\u000c]/.test(value)) {\n if (!(top.options & OPT_PRESERVE_WS)) {\n value = value.replace(/[ \\t\\r\\n\\u000c]+/g, \" \");\n // If this starts with whitespace, and there is no node before it, or\n // a hard break, or a text node that ends with whitespace, strip the\n // leading space.\n if (/^[ \\t\\r\\n\\u000c]/.test(value) && this.open == this.nodes.length - 1) {\n var nodeBefore = top.content[top.content.length - 1];\n var domNodeBefore = dom.previousSibling;\n if (!nodeBefore ||\n (domNodeBefore && domNodeBefore.nodeName == 'BR') ||\n (nodeBefore.isText && /[ \\t\\r\\n\\u000c]$/.test(nodeBefore.text)))\n { value = value.slice(1); }\n }\n } else if (!(top.options & OPT_PRESERVE_WS_FULL)) {\n value = value.replace(/\\r?\\n|\\r/g, \" \");\n }\n if (value) { this.insertNode(this.parser.schema.text(value)); }\n this.findInText(dom);\n } else {\n this.findInside(dom);\n }\n};\n\n// : (dom.Element)\n// Try to find a handler for the given tag and use that to parse. If\n// none is found, the element's content nodes are added directly.\nParseContext.prototype.addElement = function addElement (dom) {\n var name = dom.nodeName.toLowerCase();\n if (listTags.hasOwnProperty(name) && this.parser.normalizeLists) { normalizeList(dom); }\n var rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) || this.parser.matchTag(dom, this);\n if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {\n this.findInside(dom);\n } else if (!rule || rule.skip || rule.closeParent) {\n if (rule && rule.closeParent) { this.open = Math.max(0, this.open - 1); }\n else if (rule && rule.skip.nodeType) { dom = rule.skip; }\n var sync, top = this.top, oldNeedsBlock = this.needsBlock;\n if (blockTags.hasOwnProperty(name)) {\n sync = true;\n if (!top.type) { this.needsBlock = true; }\n } else if (!dom.firstChild) {\n this.leafFallback(dom);\n return\n }\n this.addAll(dom);\n if (sync) { this.sync(top); }\n this.needsBlock = oldNeedsBlock;\n } else {\n this.addElementByRule(dom, rule);\n }\n};\n\n// Called for leaf DOM nodes that would otherwise be ignored\nParseContext.prototype.leafFallback = function leafFallback (dom) {\n if (dom.nodeName == \"BR\" && this.top.type && this.top.type.inlineContent)\n { this.addTextNode(dom.ownerDocument.createTextNode(\"\\n\")); }\n};\n\n// Run any style parser associated with the node's styles. Either\n// return an array of marks, or null to indicate some of the styles\n// had a rule with `ignore` set.\nParseContext.prototype.readStyles = function readStyles (styles) {\n var marks = Mark.none;\n for (var i = 0; i < styles.length; i += 2) {\n var rule = this.parser.matchStyle(styles[i], styles[i + 1], this);\n if (!rule) { continue }\n if (rule.ignore) { return null }\n marks = this.parser.schema.marks[rule.mark].create(rule.attrs).addToSet(marks);\n }\n return marks\n};\n\n// : (dom.Element, ParseRule) → bool\n// Look up a handler for the given node. If none are found, return\n// false. Otherwise, apply it, use its return value to drive the way\n// the node's content is wrapped, and return true.\nParseContext.prototype.addElementByRule = function addElementByRule (dom, rule) {\n var this$1 = this;\n\n var sync, nodeType, markType, mark;\n if (rule.node) {\n nodeType = this.parser.schema.nodes[rule.node];\n if (!nodeType.isLeaf) {\n sync = this.enter(nodeType, rule.attrs, rule.preserveWhitespace);\n } else if (!this.insertNode(nodeType.create(rule.attrs))) {\n this.leafFallback(dom);\n }\n } else {\n markType = this.parser.schema.marks[rule.mark];\n mark = markType.create(rule.attrs);\n this.addPendingMark(mark);\n }\n var startIn = this.top;\n\n if (nodeType && nodeType.isLeaf) {\n this.findInside(dom);\n } else if (rule.getContent) {\n this.findInside(dom);\n rule.getContent(dom, this.parser.schema).forEach(function (node) { return this$1.insertNode(node); });\n } else {\n var contentDOM = rule.contentElement;\n if (typeof contentDOM == \"string\") { contentDOM = dom.querySelector(contentDOM); }\n else if (typeof contentDOM == \"function\") { contentDOM = contentDOM(dom); }\n if (!contentDOM) { contentDOM = dom; }\n this.findAround(dom, contentDOM, true);\n this.addAll(contentDOM, sync);\n }\n if (sync) { this.sync(startIn); this.open--; }\n if (mark) { this.removePendingMark(mark, startIn); }\n};\n\n// : (dom.Node, ?NodeBuilder, ?number, ?number)\n// Add all child nodes between `startIndex` and `endIndex` (or the\n// whole node, if not given). If `sync` is passed, use it to\n// synchronize after every block element.\nParseContext.prototype.addAll = function addAll (parent, sync, startIndex, endIndex) {\n var index = startIndex || 0;\n for (var dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild,\n end = endIndex == null ? null : parent.childNodes[endIndex];\n dom != end; dom = dom.nextSibling, ++index) {\n this.findAtPoint(parent, index);\n this.addDOM(dom);\n if (sync && blockTags.hasOwnProperty(dom.nodeName.toLowerCase()))\n { this.sync(sync); }\n }\n this.findAtPoint(parent, index);\n};\n\n// Try to find a way to fit the given node type into the current\n// context. May add intermediate wrappers and/or leave non-solid\n// nodes that we're in.\nParseContext.prototype.findPlace = function findPlace (node) {\n var route, sync;\n for (var depth = this.open; depth >= 0; depth--) {\n var cx = this.nodes[depth];\n var found = cx.findWrapping(node);\n if (found && (!route || route.length > found.length)) {\n route = found;\n sync = cx;\n if (!found.length) { break }\n }\n if (cx.solid) { break }\n }\n if (!route) { return false }\n this.sync(sync);\n for (var i = 0; i < route.length; i++)\n { this.enterInner(route[i], null, false); }\n return true\n};\n\n// : (Node) → ?Node\n// Try to insert the given node, adjusting the context when needed.\nParseContext.prototype.insertNode = function insertNode (node) {\n if (node.isInline && this.needsBlock && !this.top.type) {\n var block = this.textblockFromContext();\n if (block) { this.enterInner(block); }\n }\n if (this.findPlace(node)) {\n this.closeExtra();\n var top = this.top;\n top.applyPending(node.type);\n if (top.match) { top.match = top.match.matchType(node.type); }\n var marks = top.activeMarks;\n for (var i = 0; i < node.marks.length; i++)\n { if (!top.type || top.type.allowsMarkType(node.marks[i].type))\n { marks = node.marks[i].addToSet(marks); } }\n top.content.push(node.mark(marks));\n return true\n }\n return false\n};\n\n// : (NodeType, ?Object) → bool\n// Try to start a node of the given type, adjusting the context when\n// necessary.\nParseContext.prototype.enter = function enter (type, attrs, preserveWS) {\n var ok = this.findPlace(type.create(attrs));\n if (ok) { this.enterInner(type, attrs, true, preserveWS); }\n return ok\n};\n\n// Open a node of the given type\nParseContext.prototype.enterInner = function enterInner (type, attrs, solid, preserveWS) {\n this.closeExtra();\n var top = this.top;\n top.applyPending(type);\n top.match = top.match && top.match.matchType(type, attrs);\n var options = preserveWS == null ? top.options & ~OPT_OPEN_LEFT : wsOptionsFor(preserveWS);\n if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0) { options |= OPT_OPEN_LEFT; }\n this.nodes.push(new NodeContext(type, attrs, top.activeMarks, top.pendingMarks, solid, null, options));\n this.open++;\n};\n\n// Make sure all nodes above this.open are finished and added to\n// their parents\nParseContext.prototype.closeExtra = function closeExtra (openEnd) {\n var i = this.nodes.length - 1;\n if (i > this.open) {\n for (; i > this.open; i--) { this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd)); }\n this.nodes.length = this.open + 1;\n }\n};\n\nParseContext.prototype.finish = function finish () {\n this.open = 0;\n this.closeExtra(this.isOpen);\n return this.nodes[0].finish(this.isOpen || this.options.topOpen)\n};\n\nParseContext.prototype.sync = function sync (to) {\n for (var i = this.open; i >= 0; i--) { if (this.nodes[i] == to) {\n this.open = i;\n return\n } }\n};\n\nprototypeAccessors$6.currentPos.get = function () {\n this.closeExtra();\n var pos = 0;\n for (var i = this.open; i >= 0; i--) {\n var content = this.nodes[i].content;\n for (var j = content.length - 1; j >= 0; j--)\n { pos += content[j].nodeSize; }\n if (i) { pos++; }\n }\n return pos\n};\n\nParseContext.prototype.findAtPoint = function findAtPoint (parent, offset) {\n if (this.find) { for (var i = 0; i < this.find.length; i++) {\n if (this.find[i].node == parent && this.find[i].offset == offset)\n { this.find[i].pos = this.currentPos; }\n } }\n};\n\nParseContext.prototype.findInside = function findInside (parent) {\n if (this.find) { for (var i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node))\n { this.find[i].pos = this.currentPos; }\n } }\n};\n\nParseContext.prototype.findAround = function findAround (parent, content, before) {\n if (parent != content && this.find) { for (var i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {\n var pos = content.compareDocumentPosition(this.find[i].node);\n if (pos & (before ? 2 : 4))\n { this.find[i].pos = this.currentPos; }\n }\n } }\n};\n\nParseContext.prototype.findInText = function findInText (textNode) {\n if (this.find) { for (var i = 0; i < this.find.length; i++) {\n if (this.find[i].node == textNode)\n { this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset); }\n } }\n};\n\n// : (string) → bool\n// Determines whether the given [context\n// string](#ParseRule.context) matches this context.\nParseContext.prototype.matchesContext = function matchesContext (context) {\n var this$1 = this;\n\n if (context.indexOf(\"|\") > -1)\n { return context.split(/\\s*\\|\\s*/).some(this.matchesContext, this) }\n\n var parts = context.split(\"/\");\n var option = this.options.context;\n var useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);\n var minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);\n var match = function (i, depth) {\n for (; i >= 0; i--) {\n var part = parts[i];\n if (part == \"\") {\n if (i == parts.length - 1 || i == 0) { continue }\n for (; depth >= minDepth; depth--)\n { if (match(i - 1, depth)) { return true } }\n return false\n } else {\n var next = depth > 0 || (depth == 0 && useRoot) ? this$1.nodes[depth].type\n : option && depth >= minDepth ? option.node(depth - minDepth).type\n : null;\n if (!next || (next.name != part && next.groups.indexOf(part) == -1))\n { return false }\n depth--;\n }\n }\n return true\n };\n return match(parts.length - 1, this.open)\n};\n\nParseContext.prototype.textblockFromContext = function textblockFromContext () {\n var $context = this.options.context;\n if ($context) { for (var d = $context.depth; d >= 0; d--) {\n var deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;\n if (deflt && deflt.isTextblock && deflt.defaultAttrs) { return deflt }\n } }\n for (var name in this.parser.schema.nodes) {\n var type = this.parser.schema.nodes[name];\n if (type.isTextblock && type.defaultAttrs) { return type }\n }\n};\n\nParseContext.prototype.addPendingMark = function addPendingMark (mark) {\n var found = findSameTypeInSet(mark, this.top.pendingMarks);\n if (found) { this.top.stashMarks.push(found); }\n this.top.pendingMarks = mark.addToSet(this.top.pendingMarks);\n};\n\nParseContext.prototype.removePendingMark = function removePendingMark (mark, upto) {\n for (var depth = this.open; depth >= 0; depth--) {\n var level = this.nodes[depth];\n var found = level.pendingMarks.lastIndexOf(mark);\n if (found > -1) {\n level.pendingMarks = mark.removeFromSet(level.pendingMarks);\n } else {\n level.activeMarks = mark.removeFromSet(level.activeMarks);\n var stashMark = level.popFromStashMark(mark.type);\n if (stashMark) { level.activeMarks = stashMark.addToSet(level.activeMarks); }\n }\n if (level == upto) { break }\n }\n};\n\nObject.defineProperties( ParseContext.prototype, prototypeAccessors$6 );\n\n// Kludge to work around directly nested list nodes produced by some\n// tools and allowed by browsers to mean that the nested list is\n// actually part of the list item above it.\nfunction normalizeList(dom) {\n for (var child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {\n var name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;\n if (name && listTags.hasOwnProperty(name) && prevItem) {\n prevItem.appendChild(child);\n child = prevItem;\n } else if (name == \"li\") {\n prevItem = child;\n } else if (name) {\n prevItem = null;\n }\n }\n}\n\n// Apply a CSS selector.\nfunction matches(dom, selector) {\n return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector)\n}\n\n// : (string) → [string]\n// Tokenize a style attribute into property/value pairs.\nfunction parseStyles(style) {\n var re = /\\s*([\\w-]+)\\s*:\\s*([^;]+)/g, m, result = [];\n while (m = re.exec(style)) { result.push(m[1], m[2].trim()); }\n return result\n}\n\nfunction copy(obj) {\n var copy = {};\n for (var prop in obj) { copy[prop] = obj[prop]; }\n return copy\n}\n\n// Used when finding a mark at the top level of a fragment parse.\n// Checks whether it would be reasonable to apply a given mark type to\n// a given node, by looking at the way the mark occurs in the schema.\nfunction markMayApply(markType, nodeType) {\n var nodes = nodeType.schema.nodes;\n var loop = function ( name ) {\n var parent = nodes[name];\n if (!parent.allowsMarkType(markType)) { return }\n var seen = [], scan = function (match) {\n seen.push(match);\n for (var i = 0; i < match.edgeCount; i++) {\n var ref = match.edge(i);\n var type = ref.type;\n var next = ref.next;\n if (type == nodeType) { return true }\n if (seen.indexOf(next) < 0 && scan(next)) { return true }\n }\n };\n if (scan(parent.contentMatch)) { return { v: true } }\n };\n\n for (var name in nodes) {\n var returned = loop( name );\n\n if ( returned ) return returned.v;\n }\n}\n\nfunction findSameTypeInSet(mark, set) {\n for (var i = 0; i < set.length; i++) {\n if (mark.type == set[i].type) { return set[i] }\n }\n}\n\n// DOMOutputSpec:: interface\n// A description of a DOM structure. Can be either a string, which is\n// interpreted as a text node, a DOM node, which is interpreted as\n// itself, a `{dom: Node, contentDOM: ?Node}` object, or an array.\n//\n// An array describes a DOM element. The first value in the array\n// should be a string—the name of the DOM element, optionally prefixed\n// by a namespace URL and a space. If the second element is plain\n// object, it is interpreted as a set of attributes for the element.\n// Any elements after that (including the 2nd if it's not an attribute\n// object) are interpreted as children of the DOM elements, and must\n// either be valid `DOMOutputSpec` values, or the number zero.\n//\n// The number zero (pronounced “hole”) is used to indicate the place\n// where a node's child nodes should be inserted. If it occurs in an\n// output spec, it should be the only child element in its parent\n// node.\n\n// ::- A DOM serializer knows how to convert ProseMirror nodes and\n// marks of various types to DOM nodes.\nvar DOMSerializer = function DOMSerializer(nodes, marks) {\n // :: Object<(node: Node) → DOMOutputSpec>\n // The node serialization functions.\n this.nodes = nodes || {};\n // :: Object\n // The mark serialization functions.\n this.marks = marks || {};\n};\n\n// :: (Fragment, ?Object) → dom.DocumentFragment\n// Serialize the content of this fragment to a DOM fragment. When\n// not in the browser, the `document` option, containing a DOM\n// document, should be passed so that the serializer can create\n// nodes.\nDOMSerializer.prototype.serializeFragment = function serializeFragment (fragment, options, target) {\n var this$1 = this;\n if ( options === void 0 ) options = {};\n\n if (!target) { target = doc(options).createDocumentFragment(); }\n\n var top = target, active = null;\n fragment.forEach(function (node) {\n if (active || node.marks.length) {\n if (!active) { active = []; }\n var keep = 0, rendered = 0;\n while (keep < active.length && rendered < node.marks.length) {\n var next = node.marks[rendered];\n if (!this$1.marks[next.type.name]) { rendered++; continue }\n if (!next.eq(active[keep]) || next.type.spec.spanning === false) { break }\n keep += 2; rendered++;\n }\n while (keep < active.length) {\n top = active.pop();\n active.pop();\n }\n while (rendered < node.marks.length) {\n var add = node.marks[rendered++];\n var markDOM = this$1.serializeMark(add, node.isInline, options);\n if (markDOM) {\n active.push(add, top);\n top.appendChild(markDOM.dom);\n top = markDOM.contentDOM || markDOM.dom;\n }\n }\n }\n top.appendChild(this$1.serializeNode(node, options));\n });\n\n return target\n};\n\n// :: (Node, ?Object) → dom.Node\n// Serialize this node to a DOM node. This can be useful when you\n// need to serialize a part of a document, as opposed to the whole\n// document. To serialize a whole document, use\n// [`serializeFragment`](#model.DOMSerializer.serializeFragment) on\n// its [content](#model.Node.content).\nDOMSerializer.prototype.serializeNode = function serializeNode (node, options) {\n if ( options === void 0 ) options = {};\n\n var ref =\n DOMSerializer.renderSpec(doc(options), this.nodes[node.type.name](node));\n var dom = ref.dom;\n var contentDOM = ref.contentDOM;\n if (contentDOM) {\n if (node.isLeaf)\n { throw new RangeError(\"Content hole not allowed in a leaf node spec\") }\n if (options.onContent)\n { options.onContent(node, contentDOM, options); }\n else\n { this.serializeFragment(node.content, options, contentDOM); }\n }\n return dom\n};\n\nDOMSerializer.prototype.serializeNodeAndMarks = function serializeNodeAndMarks (node, options) {\n if ( options === void 0 ) options = {};\n\n var dom = this.serializeNode(node, options);\n for (var i = node.marks.length - 1; i >= 0; i--) {\n var wrap = this.serializeMark(node.marks[i], node.isInline, options);\n if (wrap) {\n(wrap.contentDOM || wrap.dom).appendChild(dom);\n dom = wrap.dom;\n }\n }\n return dom\n};\n\nDOMSerializer.prototype.serializeMark = function serializeMark (mark, inline, options) {\n if ( options === void 0 ) options = {};\n\n var toDOM = this.marks[mark.type.name];\n return toDOM && DOMSerializer.renderSpec(doc(options), toDOM(mark, inline))\n};\n\n// :: (dom.Document, DOMOutputSpec) → {dom: dom.Node, contentDOM: ?dom.Node}\n// Render an [output spec](#model.DOMOutputSpec) to a DOM node. If\n// the spec has a hole (zero) in it, `contentDOM` will point at the\n// node with the hole.\nDOMSerializer.renderSpec = function renderSpec (doc, structure, xmlNS) {\n if ( xmlNS === void 0 ) xmlNS = null;\n\n if (typeof structure == \"string\")\n { return {dom: doc.createTextNode(structure)} }\n if (structure.nodeType != null)\n { return {dom: structure} }\n if (structure.dom && structure.dom.nodeType != null)\n { return structure }\n var tagName = structure[0], space = tagName.indexOf(\" \");\n if (space > 0) {\n xmlNS = tagName.slice(0, space);\n tagName = tagName.slice(space + 1);\n }\n var contentDOM = null, dom = xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName);\n var attrs = structure[1], start = 1;\n if (attrs && typeof attrs == \"object\" && attrs.nodeType == null && !Array.isArray(attrs)) {\n start = 2;\n for (var name in attrs) { if (attrs[name] != null) {\n var space$1 = name.indexOf(\" \");\n if (space$1 > 0) { dom.setAttributeNS(name.slice(0, space$1), name.slice(space$1 + 1), attrs[name]); }\n else { dom.setAttribute(name, attrs[name]); }\n } }\n }\n for (var i = start; i < structure.length; i++) {\n var child = structure[i];\n if (child === 0) {\n if (i < structure.length - 1 || i > start)\n { throw new RangeError(\"Content hole must be the only child of its parent node\") }\n return {dom: dom, contentDOM: dom}\n } else {\n var ref = DOMSerializer.renderSpec(doc, child, xmlNS);\n var inner = ref.dom;\n var innerContent = ref.contentDOM;\n dom.appendChild(inner);\n if (innerContent) {\n if (contentDOM) { throw new RangeError(\"Multiple content holes\") }\n contentDOM = innerContent;\n }\n }\n }\n return {dom: dom, contentDOM: contentDOM}\n};\n\n// :: (Schema) → DOMSerializer\n// Build a serializer using the [`toDOM`](#model.NodeSpec.toDOM)\n// properties in a schema's node and mark specs.\nDOMSerializer.fromSchema = function fromSchema (schema) {\n return schema.cached.domSerializer ||\n (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)))\n};\n\n// : (Schema) → Object<(node: Node) → DOMOutputSpec>\n// Gather the serializers in a schema's node specs into an object.\n// This can be useful as a base to build a custom serializer from.\nDOMSerializer.nodesFromSchema = function nodesFromSchema (schema) {\n var result = gatherToDOM(schema.nodes);\n if (!result.text) { result.text = function (node) { return node.text; }; }\n return result\n};\n\n// : (Schema) → Object<(mark: Mark) → DOMOutputSpec>\n// Gather the serializers in a schema's mark specs into an object.\nDOMSerializer.marksFromSchema = function marksFromSchema (schema) {\n return gatherToDOM(schema.marks)\n};\n\nfunction gatherToDOM(obj) {\n var result = {};\n for (var name in obj) {\n var toDOM = obj[name].spec.toDOM;\n if (toDOM) { result[name] = toDOM; }\n }\n return result\n}\n\nfunction doc(options) {\n // declare global: window\n return options.document || window.document\n}\n\nexport { ContentMatch, DOMParser, DOMSerializer, Fragment, Mark, MarkType, Node, NodeRange, NodeType, ReplaceError, ResolvedPos, Schema, Slice };\n//# sourceMappingURL=index.es.js.map\n","import { ReplaceError, Slice, Fragment, MarkType } from 'prosemirror-model';\n\n// Mappable:: interface\n// There are several things that positions can be mapped through.\n// Such objects conform to this interface.\n//\n// map:: (pos: number, assoc: ?number) → number\n// Map a position through this object. When given, `assoc` (should\n// be -1 or 1, defaults to 1) determines with which side the\n// position is associated, which determines in which direction to\n// move when a chunk of content is inserted at the mapped position.\n//\n// mapResult:: (pos: number, assoc: ?number) → MapResult\n// Map a position, and return an object containing additional\n// information about the mapping. The result's `deleted` field tells\n// you whether the position was deleted (completely enclosed in a\n// replaced range) during the mapping. When content on only one side\n// is deleted, the position itself is only considered deleted when\n// `assoc` points in the direction of the deleted content.\n\n// Recovery values encode a range index and an offset. They are\n// represented as numbers, because tons of them will be created when\n// mapping, for example, a large number of decorations. The number's\n// lower 16 bits provide the index, the remaining bits the offset.\n//\n// Note: We intentionally don't use bit shift operators to en- and\n// decode these, since those clip to 32 bits, which we might in rare\n// cases want to overflow. A 64-bit float can represent 48-bit\n// integers precisely.\n\nvar lower16 = 0xffff;\nvar factor16 = Math.pow(2, 16);\n\nfunction makeRecover(index, offset) { return index + offset * factor16 }\nfunction recoverIndex(value) { return value & lower16 }\nfunction recoverOffset(value) { return (value - (value & lower16)) / factor16 }\n\n// ::- An object representing a mapped position with extra\n// information.\nvar MapResult = function MapResult(pos, deleted, recover) {\n if ( deleted === void 0 ) deleted = false;\n if ( recover === void 0 ) recover = null;\n\n // :: number The mapped version of the position.\n this.pos = pos;\n // :: bool Tells you whether the position was deleted, that is,\n // whether the step removed its surroundings from the document.\n this.deleted = deleted;\n this.recover = recover;\n};\n\n// :: class extends Mappable\n// A map describing the deletions and insertions made by a step, which\n// can be used to find the correspondence between positions in the\n// pre-step version of a document and the same position in the\n// post-step version.\nvar StepMap = function StepMap(ranges, inverted) {\n if ( inverted === void 0 ) inverted = false;\n\n this.ranges = ranges;\n this.inverted = inverted;\n};\n\nStepMap.prototype.recover = function recover (value) {\n var diff = 0, index = recoverIndex(value);\n if (!this.inverted) { for (var i = 0; i < index; i++)\n { diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1]; } }\n return this.ranges[index * 3] + diff + recoverOffset(value)\n};\n\n// : (number, ?number) → MapResult\nStepMap.prototype.mapResult = function mapResult (pos, assoc) {\n if ( assoc === void 0 ) assoc = 1;\n return this._map(pos, assoc, false) };\n\n// : (number, ?number) → number\nStepMap.prototype.map = function map (pos, assoc) {\n if ( assoc === void 0 ) assoc = 1;\n return this._map(pos, assoc, true) };\n\nStepMap.prototype._map = function _map (pos, assoc, simple) {\n var diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (var i = 0; i < this.ranges.length; i += 3) {\n var start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos) { break }\n var oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;\n if (pos <= end) {\n var side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;\n var result = start + diff + (side < 0 ? 0 : newSize);\n if (simple) { return result }\n var recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);\n return new MapResult(result, assoc < 0 ? pos != start : pos != end, recover)\n }\n diff += newSize - oldSize;\n }\n return simple ? pos + diff : new MapResult(pos + diff)\n};\n\nStepMap.prototype.touches = function touches (pos, recover) {\n var diff = 0, index = recoverIndex(recover);\n var oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (var i = 0; i < this.ranges.length; i += 3) {\n var start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos) { break }\n var oldSize = this.ranges[i + oldIndex], end = start + oldSize;\n if (pos <= end && i == index * 3) { return true }\n diff += this.ranges[i + newIndex] - oldSize;\n }\n return false\n};\n\n// :: ((oldStart: number, oldEnd: number, newStart: number, newEnd: number))\n// Calls the given function on each of the changed ranges included in\n// this map.\nStepMap.prototype.forEach = function forEach (f) {\n var oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (var i = 0, diff = 0; i < this.ranges.length; i += 3) {\n var start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);\n var oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];\n f(oldStart, oldStart + oldSize, newStart, newStart + newSize);\n diff += newSize - oldSize;\n }\n};\n\n// :: () → StepMap\n// Create an inverted version of this map. The result can be used to\n// map positions in the post-step document to the pre-step document.\nStepMap.prototype.invert = function invert () {\n return new StepMap(this.ranges, !this.inverted)\n};\n\nStepMap.prototype.toString = function toString () {\n return (this.inverted ? \"-\" : \"\") + JSON.stringify(this.ranges)\n};\n\n// :: (n: number) → StepMap\n// Create a map that moves all positions by offset `n` (which may be\n// negative). This can be useful when applying steps meant for a\n// sub-document to a larger document, or vice-versa.\nStepMap.offset = function offset (n) {\n return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n])\n};\n\nStepMap.empty = new StepMap([]);\n\n// :: class extends Mappable\n// A mapping represents a pipeline of zero or more [step\n// maps](#transform.StepMap). It has special provisions for losslessly\n// handling mapping positions through a series of steps in which some\n// steps are inverted versions of earlier steps. (This comes up when\n// ‘[rebasing](/docs/guide/#transform.rebasing)’ steps for\n// collaboration or history management.)\nvar Mapping = function Mapping(maps, mirror, from, to) {\n // :: [StepMap]\n // The step maps in this mapping.\n this.maps = maps || [];\n // :: number\n // The starting position in the `maps` array, used when `map` or\n // `mapResult` is called.\n this.from = from || 0;\n // :: number\n // The end position in the `maps` array.\n this.to = to == null ? this.maps.length : to;\n this.mirror = mirror;\n};\n\n// :: (?number, ?number) → Mapping\n// Create a mapping that maps only through a part of this one.\nMapping.prototype.slice = function slice (from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.maps.length;\n\n return new Mapping(this.maps, this.mirror, from, to)\n};\n\nMapping.prototype.copy = function copy () {\n return new Mapping(this.maps.slice(), this.mirror && this.mirror.slice(), this.from, this.to)\n};\n\n// :: (StepMap, ?number)\n// Add a step map to the end of this mapping. If `mirrors` is\n// given, it should be the index of the step map that is the mirror\n// image of this one.\nMapping.prototype.appendMap = function appendMap (map, mirrors) {\n this.to = this.maps.push(map);\n if (mirrors != null) { this.setMirror(this.maps.length - 1, mirrors); }\n};\n\n// :: (Mapping)\n// Add all the step maps in a given mapping to this one (preserving\n// mirroring information).\nMapping.prototype.appendMapping = function appendMapping (mapping) {\n for (var i = 0, startSize = this.maps.length; i < mapping.maps.length; i++) {\n var mirr = mapping.getMirror(i);\n this.appendMap(mapping.maps[i], mirr != null && mirr < i ? startSize + mirr : null);\n }\n};\n\n// :: (number) → ?number\n// Finds the offset of the step map that mirrors the map at the\n// given offset, in this mapping (as per the second argument to\n// `appendMap`).\nMapping.prototype.getMirror = function getMirror (n) {\n if (this.mirror) { for (var i = 0; i < this.mirror.length; i++)\n { if (this.mirror[i] == n) { return this.mirror[i + (i % 2 ? -1 : 1)] } } }\n};\n\nMapping.prototype.setMirror = function setMirror (n, m) {\n if (!this.mirror) { this.mirror = []; }\n this.mirror.push(n, m);\n};\n\n// :: (Mapping)\n// Append the inverse of the given mapping to this one.\nMapping.prototype.appendMappingInverted = function appendMappingInverted (mapping) {\n for (var i = mapping.maps.length - 1, totalSize = this.maps.length + mapping.maps.length; i >= 0; i--) {\n var mirr = mapping.getMirror(i);\n this.appendMap(mapping.maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : null);\n }\n};\n\n// :: () → Mapping\n// Create an inverted version of this mapping.\nMapping.prototype.invert = function invert () {\n var inverse = new Mapping;\n inverse.appendMappingInverted(this);\n return inverse\n};\n\n// : (number, ?number) → number\n// Map a position through this mapping.\nMapping.prototype.map = function map (pos, assoc) {\n if ( assoc === void 0 ) assoc = 1;\n\n if (this.mirror) { return this._map(pos, assoc, true) }\n for (var i = this.from; i < this.to; i++)\n { pos = this.maps[i].map(pos, assoc); }\n return pos\n};\n\n// : (number, ?number) → MapResult\n// Map a position through this mapping, returning a mapping\n// result.\nMapping.prototype.mapResult = function mapResult (pos, assoc) {\n if ( assoc === void 0 ) assoc = 1;\n return this._map(pos, assoc, false) };\n\nMapping.prototype._map = function _map (pos, assoc, simple) {\n var deleted = false;\n\n for (var i = this.from; i < this.to; i++) {\n var map = this.maps[i], result = map.mapResult(pos, assoc);\n if (result.recover != null) {\n var corr = this.getMirror(i);\n if (corr != null && corr > i && corr < this.to) {\n i = corr;\n pos = this.maps[corr].recover(result.recover);\n continue\n }\n }\n\n if (result.deleted) { deleted = true; }\n pos = result.pos;\n }\n\n return simple ? pos : new MapResult(pos, deleted)\n};\n\nfunction TransformError(message) {\n var err = Error.call(this, message);\n err.__proto__ = TransformError.prototype;\n return err\n}\n\nTransformError.prototype = Object.create(Error.prototype);\nTransformError.prototype.constructor = TransformError;\nTransformError.prototype.name = \"TransformError\";\n\n// ::- Abstraction to build up and track an array of\n// [steps](#transform.Step) representing a document transformation.\n//\n// Most transforming methods return the `Transform` object itself, so\n// that they can be chained.\nvar Transform = function Transform(doc) {\n // :: Node\n // The current document (the result of applying the steps in the\n // transform).\n this.doc = doc;\n // :: [Step]\n // The steps in this transform.\n this.steps = [];\n // :: [Node]\n // The documents before each of the steps.\n this.docs = [];\n // :: Mapping\n // A mapping with the maps for each of the steps in this transform.\n this.mapping = new Mapping;\n};\n\nvar prototypeAccessors = { before: { configurable: true },docChanged: { configurable: true } };\n\n// :: Node The starting document.\nprototypeAccessors.before.get = function () { return this.docs.length ? this.docs[0] : this.doc };\n\n// :: (step: Step) → this\n// Apply a new step in this transform, saving the result. Throws an\n// error when the step fails.\nTransform.prototype.step = function step (object) {\n var result = this.maybeStep(object);\n if (result.failed) { throw new TransformError(result.failed) }\n return this\n};\n\n// :: (Step) → StepResult\n// Try to apply a step in this transformation, ignoring it if it\n// fails. Returns the step result.\nTransform.prototype.maybeStep = function maybeStep (step) {\n var result = step.apply(this.doc);\n if (!result.failed) { this.addStep(step, result.doc); }\n return result\n};\n\n// :: bool\n// True when the document has been changed (when there are any\n// steps).\nprototypeAccessors.docChanged.get = function () {\n return this.steps.length > 0\n};\n\nTransform.prototype.addStep = function addStep (step, doc) {\n this.docs.push(this.doc);\n this.steps.push(step);\n this.mapping.appendMap(step.getMap());\n this.doc = doc;\n};\n\nObject.defineProperties( Transform.prototype, prototypeAccessors );\n\nfunction mustOverride() { throw new Error(\"Override me\") }\n\nvar stepsByID = Object.create(null);\n\n// ::- A step object represents an atomic change. It generally applies\n// only to the document it was created for, since the positions\n// stored in it will only make sense for that document.\n//\n// New steps are defined by creating classes that extend `Step`,\n// overriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`\n// methods, and registering your class with a unique\n// JSON-serialization identifier using\n// [`Step.jsonID`](#transform.Step^jsonID).\nvar Step = function Step () {};\n\nStep.prototype.apply = function apply (_doc) { return mustOverride() };\n\n// :: () → StepMap\n// Get the step map that represents the changes made by this step,\n// and which can be used to transform between positions in the old\n// and the new document.\nStep.prototype.getMap = function getMap () { return StepMap.empty };\n\n// :: (doc: Node) → Step\n// Create an inverted version of this step. Needs the document as it\n// was before the step as argument.\nStep.prototype.invert = function invert (_doc) { return mustOverride() };\n\n// :: (mapping: Mappable) → ?Step\n// Map this step through a mappable thing, returning either a\n// version of that step with its positions adjusted, or `null` if\n// the step was entirely deleted by the mapping.\nStep.prototype.map = function map (_mapping) { return mustOverride() };\n\n// :: (other: Step) → ?Step\n// Try to merge this step with another one, to be applied directly\n// after it. Returns the merged step when possible, null if the\n// steps can't be merged.\nStep.prototype.merge = function merge (_other) { return null };\n\n// :: () → Object\n// Create a JSON-serializeable representation of this step. When\n// defining this for a custom subclass, make sure the result object\n// includes the step type's [JSON id](#transform.Step^jsonID) under\n// the `stepType` property.\nStep.prototype.toJSON = function toJSON () { return mustOverride() };\n\n// :: (Schema, Object) → Step\n// Deserialize a step from its JSON representation. Will call\n// through to the step class' own implementation of this method.\nStep.fromJSON = function fromJSON (schema, json) {\n if (!json || !json.stepType) { throw new RangeError(\"Invalid input for Step.fromJSON\") }\n var type = stepsByID[json.stepType];\n if (!type) { throw new RangeError((\"No step type \" + (json.stepType) + \" defined\")) }\n return type.fromJSON(schema, json)\n};\n\n// :: (string, constructor)\n// To be able to serialize steps to JSON, each step needs a string\n// ID to attach to its JSON representation. Use this method to\n// register an ID for your step classes. Try to pick something\n// that's unlikely to clash with steps from other modules.\nStep.jsonID = function jsonID (id, stepClass) {\n if (id in stepsByID) { throw new RangeError(\"Duplicate use of step JSON ID \" + id) }\n stepsByID[id] = stepClass;\n stepClass.prototype.jsonID = id;\n return stepClass\n};\n\n// ::- The result of [applying](#transform.Step.apply) a step. Contains either a\n// new document or a failure value.\nvar StepResult = function StepResult(doc, failed) {\n // :: ?Node The transformed document.\n this.doc = doc;\n // :: ?string Text providing information about a failed step.\n this.failed = failed;\n};\n\n// :: (Node) → StepResult\n// Create a successful step result.\nStepResult.ok = function ok (doc) { return new StepResult(doc, null) };\n\n// :: (string) → StepResult\n// Create a failed step result.\nStepResult.fail = function fail (message) { return new StepResult(null, message) };\n\n// :: (Node, number, number, Slice) → StepResult\n// Call [`Node.replace`](#model.Node.replace) with the given\n// arguments. Create a successful result if it succeeds, and a\n// failed one if it throws a `ReplaceError`.\nStepResult.fromReplace = function fromReplace (doc, from, to, slice) {\n try {\n return StepResult.ok(doc.replace(from, to, slice))\n } catch (e) {\n if (e instanceof ReplaceError) { return StepResult.fail(e.message) }\n throw e\n }\n};\n\n// ::- Replace a part of the document with a slice of new content.\nvar ReplaceStep = /*@__PURE__*/(function (Step) {\n function ReplaceStep(from, to, slice, structure) {\n Step.call(this);\n this.from = from;\n this.to = to;\n this.slice = slice;\n this.structure = !!structure;\n }\n\n if ( Step ) ReplaceStep.__proto__ = Step;\n ReplaceStep.prototype = Object.create( Step && Step.prototype );\n ReplaceStep.prototype.constructor = ReplaceStep;\n\n ReplaceStep.prototype.apply = function apply (doc) {\n if (this.structure && contentBetween(doc, this.from, this.to))\n { return StepResult.fail(\"Structure replace would overwrite content\") }\n return StepResult.fromReplace(doc, this.from, this.to, this.slice)\n };\n\n ReplaceStep.prototype.getMap = function getMap () {\n return new StepMap([this.from, this.to - this.from, this.slice.size])\n };\n\n ReplaceStep.prototype.invert = function invert (doc) {\n return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to))\n };\n\n ReplaceStep.prototype.map = function map (mapping) {\n var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted) { return null }\n return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice)\n };\n\n ReplaceStep.prototype.merge = function merge (other) {\n if (!(other instanceof ReplaceStep) || other.structure != this.structure) { return null }\n\n if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {\n var slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);\n return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure)\n } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {\n var slice$1 = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);\n return new ReplaceStep(other.from, this.to, slice$1, this.structure)\n } else {\n return null\n }\n };\n\n ReplaceStep.prototype.toJSON = function toJSON () {\n var json = {stepType: \"replace\", from: this.from, to: this.to};\n if (this.slice.size) { json.slice = this.slice.toJSON(); }\n if (this.structure) { json.structure = true; }\n return json\n };\n\n ReplaceStep.fromJSON = function fromJSON (schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n { throw new RangeError(\"Invalid input for ReplaceStep.fromJSON\") }\n return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure)\n };\n\n return ReplaceStep;\n}(Step));\n\nStep.jsonID(\"replace\", ReplaceStep);\n\n// ::- Replace a part of the document with a slice of content, but\n// preserve a range of the replaced content by moving it into the\n// slice.\nvar ReplaceAroundStep = /*@__PURE__*/(function (Step) {\n function ReplaceAroundStep(from, to, gapFrom, gapTo, slice, insert, structure) {\n Step.call(this);\n this.from = from;\n this.to = to;\n this.gapFrom = gapFrom;\n this.gapTo = gapTo;\n this.slice = slice;\n this.insert = insert;\n this.structure = !!structure;\n }\n\n if ( Step ) ReplaceAroundStep.__proto__ = Step;\n ReplaceAroundStep.prototype = Object.create( Step && Step.prototype );\n ReplaceAroundStep.prototype.constructor = ReplaceAroundStep;\n\n ReplaceAroundStep.prototype.apply = function apply (doc) {\n if (this.structure && (contentBetween(doc, this.from, this.gapFrom) ||\n contentBetween(doc, this.gapTo, this.to)))\n { return StepResult.fail(\"Structure gap-replace would overwrite content\") }\n\n var gap = doc.slice(this.gapFrom, this.gapTo);\n if (gap.openStart || gap.openEnd)\n { return StepResult.fail(\"Gap is not a flat range\") }\n var inserted = this.slice.insertAt(this.insert, gap.content);\n if (!inserted) { return StepResult.fail(\"Content does not fit in gap\") }\n return StepResult.fromReplace(doc, this.from, this.to, inserted)\n };\n\n ReplaceAroundStep.prototype.getMap = function getMap () {\n return new StepMap([this.from, this.gapFrom - this.from, this.insert,\n this.gapTo, this.to - this.gapTo, this.slice.size - this.insert])\n };\n\n ReplaceAroundStep.prototype.invert = function invert (doc) {\n var gap = this.gapTo - this.gapFrom;\n return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap,\n this.from + this.insert, this.from + this.insert + gap,\n doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from),\n this.gapFrom - this.from, this.structure)\n };\n\n ReplaceAroundStep.prototype.map = function map (mapping) {\n var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n var gapFrom = mapping.map(this.gapFrom, -1), gapTo = mapping.map(this.gapTo, 1);\n if ((from.deleted && to.deleted) || gapFrom < from.pos || gapTo > to.pos) { return null }\n return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure)\n };\n\n ReplaceAroundStep.prototype.toJSON = function toJSON () {\n var json = {stepType: \"replaceAround\", from: this.from, to: this.to,\n gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert};\n if (this.slice.size) { json.slice = this.slice.toJSON(); }\n if (this.structure) { json.structure = true; }\n return json\n };\n\n ReplaceAroundStep.fromJSON = function fromJSON (schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\" ||\n typeof json.gapFrom != \"number\" || typeof json.gapTo != \"number\" || typeof json.insert != \"number\")\n { throw new RangeError(\"Invalid input for ReplaceAroundStep.fromJSON\") }\n return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo,\n Slice.fromJSON(schema, json.slice), json.insert, !!json.structure)\n };\n\n return ReplaceAroundStep;\n}(Step));\n\nStep.jsonID(\"replaceAround\", ReplaceAroundStep);\n\nfunction contentBetween(doc, from, to) {\n var $from = doc.resolve(from), dist = to - from, depth = $from.depth;\n while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {\n depth--;\n dist--;\n }\n if (dist > 0) {\n var next = $from.node(depth).maybeChild($from.indexAfter(depth));\n while (dist > 0) {\n if (!next || next.isLeaf) { return true }\n next = next.firstChild;\n dist--;\n }\n }\n return false\n}\n\nfunction canCut(node, start, end) {\n return (start == 0 || node.canReplace(start, node.childCount)) &&\n (end == node.childCount || node.canReplace(0, end))\n}\n\n// :: (NodeRange) → ?number\n// Try to find a target depth to which the content in the given range\n// can be lifted. Will not go across\n// [isolating](#model.NodeSpec.isolating) parent nodes.\nfunction liftTarget(range) {\n var parent = range.parent;\n var content = parent.content.cutByIndex(range.startIndex, range.endIndex);\n for (var depth = range.depth;; --depth) {\n var node = range.$from.node(depth);\n var index = range.$from.index(depth), endIndex = range.$to.indexAfter(depth);\n if (depth < range.depth && node.canReplace(index, endIndex, content))\n { return depth }\n if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex)) { break }\n }\n}\n\n// :: (NodeRange, number) → this\n// Split the content in the given range off from its parent, if there\n// is sibling content before or after it, and move it up the tree to\n// the depth specified by `target`. You'll probably want to use\n// [`liftTarget`](#transform.liftTarget) to compute `target`, to make\n// sure the lift is valid.\nTransform.prototype.lift = function(range, target) {\n var $from = range.$from;\n var $to = range.$to;\n var depth = range.depth;\n\n var gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);\n var start = gapStart, end = gapEnd;\n\n var before = Fragment.empty, openStart = 0;\n for (var d = depth, splitting = false; d > target; d--)\n { if (splitting || $from.index(d) > 0) {\n splitting = true;\n before = Fragment.from($from.node(d).copy(before));\n openStart++;\n } else {\n start--;\n } }\n var after = Fragment.empty, openEnd = 0;\n for (var d$1 = depth, splitting$1 = false; d$1 > target; d$1--)\n { if (splitting$1 || $to.after(d$1 + 1) < $to.end(d$1)) {\n splitting$1 = true;\n after = Fragment.from($to.node(d$1).copy(after));\n openEnd++;\n } else {\n end++;\n } }\n\n return this.step(new ReplaceAroundStep(start, end, gapStart, gapEnd,\n new Slice(before.append(after), openStart, openEnd),\n before.size - openStart, true))\n};\n\n// :: (NodeRange, NodeType, ?Object, ?NodeRange) → ?[{type: NodeType, attrs: ?Object}]\n// Try to find a valid way to wrap the content in the given range in a\n// node of the given type. May introduce extra nodes around and inside\n// the wrapper node, if necessary. Returns null if no valid wrapping\n// could be found. When `innerRange` is given, that range's content is\n// used as the content to fit into the wrapping, instead of the\n// content of `range`.\nfunction findWrapping(range, nodeType, attrs, innerRange) {\n if ( innerRange === void 0 ) innerRange = range;\n\n var around = findWrappingOutside(range, nodeType);\n var inner = around && findWrappingInside(innerRange, nodeType);\n if (!inner) { return null }\n return around.map(withAttrs).concat({type: nodeType, attrs: attrs}).concat(inner.map(withAttrs))\n}\n\nfunction withAttrs(type) { return {type: type, attrs: null} }\n\nfunction findWrappingOutside(range, type) {\n var parent = range.parent;\n var startIndex = range.startIndex;\n var endIndex = range.endIndex;\n var around = parent.contentMatchAt(startIndex).findWrapping(type);\n if (!around) { return null }\n var outer = around.length ? around[0] : type;\n return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null\n}\n\nfunction findWrappingInside(range, type) {\n var parent = range.parent;\n var startIndex = range.startIndex;\n var endIndex = range.endIndex;\n var inner = parent.child(startIndex);\n var inside = type.contentMatch.findWrapping(inner.type);\n if (!inside) { return null }\n var lastType = inside.length ? inside[inside.length - 1] : type;\n var innerMatch = lastType.contentMatch;\n for (var i = startIndex; innerMatch && i < endIndex; i++)\n { innerMatch = innerMatch.matchType(parent.child(i).type); }\n if (!innerMatch || !innerMatch.validEnd) { return null }\n return inside\n}\n\n// :: (NodeRange, [{type: NodeType, attrs: ?Object}]) → this\n// Wrap the given [range](#model.NodeRange) in the given set of wrappers.\n// The wrappers are assumed to be valid in this position, and should\n// probably be computed with [`findWrapping`](#transform.findWrapping).\nTransform.prototype.wrap = function(range, wrappers) {\n var content = Fragment.empty;\n for (var i = wrappers.length - 1; i >= 0; i--)\n { content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content)); }\n\n var start = range.start, end = range.end;\n return this.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true))\n};\n\n// :: (number, ?number, NodeType, ?Object) → this\n// Set the type of all textblocks (partly) between `from` and `to` to\n// the given node type with the given attributes.\nTransform.prototype.setBlockType = function(from, to, type, attrs) {\n var this$1 = this;\n if ( to === void 0 ) to = from;\n\n if (!type.isTextblock) { throw new RangeError(\"Type given to setBlockType should be a textblock\") }\n var mapFrom = this.steps.length;\n this.doc.nodesBetween(from, to, function (node, pos) {\n if (node.isTextblock && !node.hasMarkup(type, attrs) && canChangeType(this$1.doc, this$1.mapping.slice(mapFrom).map(pos), type)) {\n // Ensure all markup that isn't allowed in the new node type is cleared\n this$1.clearIncompatible(this$1.mapping.slice(mapFrom).map(pos, 1), type);\n var mapping = this$1.mapping.slice(mapFrom);\n var startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);\n this$1.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1,\n new Slice(Fragment.from(type.create(attrs, null, node.marks)), 0, 0), 1, true));\n return false\n }\n });\n return this\n};\n\nfunction canChangeType(doc, pos, type) {\n var $pos = doc.resolve(pos), index = $pos.index();\n return $pos.parent.canReplaceWith(index, index + 1, type)\n}\n\n// :: (number, ?NodeType, ?Object, ?[Mark]) → this\n// Change the type, attributes, and/or marks of the node at `pos`.\n// When `type` isn't given, the existing node type is preserved,\nTransform.prototype.setNodeMarkup = function(pos, type, attrs, marks) {\n var node = this.doc.nodeAt(pos);\n if (!node) { throw new RangeError(\"No node at given position\") }\n if (!type) { type = node.type; }\n var newNode = type.create(attrs, null, marks || node.marks);\n if (node.isLeaf)\n { return this.replaceWith(pos, pos + node.nodeSize, newNode) }\n\n if (!type.validContent(node.content))\n { throw new RangeError(\"Invalid content for node type \" + type.name) }\n\n return this.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1,\n new Slice(Fragment.from(newNode), 0, 0), 1, true))\n};\n\n// :: (Node, number, number, ?[?{type: NodeType, attrs: ?Object}]) → bool\n// Check whether splitting at the given position is allowed.\nfunction canSplit(doc, pos, depth, typesAfter) {\n if ( depth === void 0 ) depth = 1;\n\n var $pos = doc.resolve(pos), base = $pos.depth - depth;\n var innerType = (typesAfter && typesAfter[typesAfter.length - 1]) || $pos.parent;\n if (base < 0 || $pos.parent.type.spec.isolating ||\n !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) ||\n !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))\n { return false }\n for (var d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {\n var node = $pos.node(d), index$1 = $pos.index(d);\n if (node.type.spec.isolating) { return false }\n var rest = node.content.cutByIndex(index$1, node.childCount);\n var after = (typesAfter && typesAfter[i]) || node;\n if (after != node) { rest = rest.replaceChild(0, after.type.create(after.attrs)); }\n if (!node.canReplace(index$1 + 1, node.childCount) || !after.type.validContent(rest))\n { return false }\n }\n var index = $pos.indexAfter(base);\n var baseType = typesAfter && typesAfter[0];\n return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type)\n}\n\n// :: (number, ?number, ?[?{type: NodeType, attrs: ?Object}]) → this\n// Split the node at the given position, and optionally, if `depth` is\n// greater than one, any number of nodes above that. By default, the\n// parts split off will inherit the node type of the original node.\n// This can be changed by passing an array of types and attributes to\n// use after the split.\nTransform.prototype.split = function(pos, depth, typesAfter) {\n if ( depth === void 0 ) depth = 1;\n\n var $pos = this.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;\n for (var d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {\n before = Fragment.from($pos.node(d).copy(before));\n var typeAfter = typesAfter && typesAfter[i];\n after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));\n }\n return this.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true))\n};\n\n// :: (Node, number) → bool\n// Test whether the blocks before and after a given position can be\n// joined.\nfunction canJoin(doc, pos) {\n var $pos = doc.resolve(pos), index = $pos.index();\n return joinable($pos.nodeBefore, $pos.nodeAfter) &&\n $pos.parent.canReplace(index, index + 1)\n}\n\nfunction joinable(a, b) {\n return a && b && !a.isLeaf && a.canAppend(b)\n}\n\n// :: (Node, number, ?number) → ?number\n// Find an ancestor of the given position that can be joined to the\n// block before (or after if `dir` is positive). Returns the joinable\n// point, if any.\nfunction joinPoint(doc, pos, dir) {\n if ( dir === void 0 ) dir = -1;\n\n var $pos = doc.resolve(pos);\n for (var d = $pos.depth;; d--) {\n var before = (void 0), after = (void 0), index = $pos.index(d);\n if (d == $pos.depth) {\n before = $pos.nodeBefore;\n after = $pos.nodeAfter;\n } else if (dir > 0) {\n before = $pos.node(d + 1);\n index++;\n after = $pos.node(d).maybeChild(index);\n } else {\n before = $pos.node(d).maybeChild(index - 1);\n after = $pos.node(d + 1);\n }\n if (before && !before.isTextblock && joinable(before, after) &&\n $pos.node(d).canReplace(index, index + 1)) { return pos }\n if (d == 0) { break }\n pos = dir < 0 ? $pos.before(d) : $pos.after(d);\n }\n}\n\n// :: (number, ?number) → this\n// Join the blocks around the given position. If depth is 2, their\n// last and first siblings are also joined, and so on.\nTransform.prototype.join = function(pos, depth) {\n if ( depth === void 0 ) depth = 1;\n\n var step = new ReplaceStep(pos - depth, pos + depth, Slice.empty, true);\n return this.step(step)\n};\n\n// :: (Node, number, NodeType) → ?number\n// Try to find a point where a node of the given type can be inserted\n// near `pos`, by searching up the node hierarchy when `pos` itself\n// isn't a valid place but is at the start or end of a node. Return\n// null if no position was found.\nfunction insertPoint(doc, pos, nodeType) {\n var $pos = doc.resolve(pos);\n if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType)) { return pos }\n\n if ($pos.parentOffset == 0)\n { for (var d = $pos.depth - 1; d >= 0; d--) {\n var index = $pos.index(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType)) { return $pos.before(d + 1) }\n if (index > 0) { return null }\n } }\n if ($pos.parentOffset == $pos.parent.content.size)\n { for (var d$1 = $pos.depth - 1; d$1 >= 0; d$1--) {\n var index$1 = $pos.indexAfter(d$1);\n if ($pos.node(d$1).canReplaceWith(index$1, index$1, nodeType)) { return $pos.after(d$1 + 1) }\n if (index$1 < $pos.node(d$1).childCount) { return null }\n } }\n}\n\n// :: (Node, number, Slice) → ?number\n// Finds a position at or around the given position where the given\n// slice can be inserted. Will look at parent nodes' nearest boundary\n// and try there, even if the original position wasn't directly at the\n// start or end of that node. Returns null when no position was found.\nfunction dropPoint(doc, pos, slice) {\n var $pos = doc.resolve(pos);\n if (!slice.content.size) { return pos }\n var content = slice.content;\n for (var i = 0; i < slice.openStart; i++) { content = content.firstChild.content; }\n for (var pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {\n for (var d = $pos.depth; d >= 0; d--) {\n var bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;\n var insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);\n if (pass == 1\n ? $pos.node(d).canReplace(insertPos, insertPos, content)\n : $pos.node(d).contentMatchAt(insertPos).findWrapping(content.firstChild.type))\n { return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1) }\n }\n }\n return null\n}\n\nfunction mapFragment(fragment, f, parent) {\n var mapped = [];\n for (var i = 0; i < fragment.childCount; i++) {\n var child = fragment.child(i);\n if (child.content.size) { child = child.copy(mapFragment(child.content, f, child)); }\n if (child.isInline) { child = f(child, parent, i); }\n mapped.push(child);\n }\n return Fragment.fromArray(mapped)\n}\n\n// ::- Add a mark to all inline content between two positions.\nvar AddMarkStep = /*@__PURE__*/(function (Step) {\n function AddMarkStep(from, to, mark) {\n Step.call(this);\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n\n if ( Step ) AddMarkStep.__proto__ = Step;\n AddMarkStep.prototype = Object.create( Step && Step.prototype );\n AddMarkStep.prototype.constructor = AddMarkStep;\n\n AddMarkStep.prototype.apply = function apply (doc) {\n var this$1 = this;\n\n var oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from);\n var parent = $from.node($from.sharedDepth(this.to));\n var slice = new Slice(mapFragment(oldSlice.content, function (node, parent) {\n if (!parent.type.allowsMarkType(this$1.mark.type)) { return node }\n return node.mark(this$1.mark.addToSet(node.marks))\n }, parent), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice)\n };\n\n AddMarkStep.prototype.invert = function invert () {\n return new RemoveMarkStep(this.from, this.to, this.mark)\n };\n\n AddMarkStep.prototype.map = function map (mapping) {\n var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos) { return null }\n return new AddMarkStep(from.pos, to.pos, this.mark)\n };\n\n AddMarkStep.prototype.merge = function merge (other) {\n if (other instanceof AddMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n { return new AddMarkStep(Math.min(this.from, other.from),\n Math.max(this.to, other.to), this.mark) }\n };\n\n AddMarkStep.prototype.toJSON = function toJSON () {\n return {stepType: \"addMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to}\n };\n\n AddMarkStep.fromJSON = function fromJSON (schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n { throw new RangeError(\"Invalid input for AddMarkStep.fromJSON\") }\n return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark))\n };\n\n return AddMarkStep;\n}(Step));\n\nStep.jsonID(\"addMark\", AddMarkStep);\n\n// ::- Remove a mark from all inline content between two positions.\nvar RemoveMarkStep = /*@__PURE__*/(function (Step) {\n function RemoveMarkStep(from, to, mark) {\n Step.call(this);\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n\n if ( Step ) RemoveMarkStep.__proto__ = Step;\n RemoveMarkStep.prototype = Object.create( Step && Step.prototype );\n RemoveMarkStep.prototype.constructor = RemoveMarkStep;\n\n RemoveMarkStep.prototype.apply = function apply (doc) {\n var this$1 = this;\n\n var oldSlice = doc.slice(this.from, this.to);\n var slice = new Slice(mapFragment(oldSlice.content, function (node) {\n return node.mark(this$1.mark.removeFromSet(node.marks))\n }), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice)\n };\n\n RemoveMarkStep.prototype.invert = function invert () {\n return new AddMarkStep(this.from, this.to, this.mark)\n };\n\n RemoveMarkStep.prototype.map = function map (mapping) {\n var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos) { return null }\n return new RemoveMarkStep(from.pos, to.pos, this.mark)\n };\n\n RemoveMarkStep.prototype.merge = function merge (other) {\n if (other instanceof RemoveMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n { return new RemoveMarkStep(Math.min(this.from, other.from),\n Math.max(this.to, other.to), this.mark) }\n };\n\n RemoveMarkStep.prototype.toJSON = function toJSON () {\n return {stepType: \"removeMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to}\n };\n\n RemoveMarkStep.fromJSON = function fromJSON (schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n { throw new RangeError(\"Invalid input for RemoveMarkStep.fromJSON\") }\n return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark))\n };\n\n return RemoveMarkStep;\n}(Step));\n\nStep.jsonID(\"removeMark\", RemoveMarkStep);\n\n// :: (number, number, Mark) → this\n// Add the given mark to the inline content between `from` and `to`.\nTransform.prototype.addMark = function(from, to, mark) {\n var this$1 = this;\n\n var removed = [], added = [], removing = null, adding = null;\n this.doc.nodesBetween(from, to, function (node, pos, parent) {\n if (!node.isInline) { return }\n var marks = node.marks;\n if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {\n var start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to);\n var newSet = mark.addToSet(marks);\n\n for (var i = 0; i < marks.length; i++) {\n if (!marks[i].isInSet(newSet)) {\n if (removing && removing.to == start && removing.mark.eq(marks[i]))\n { removing.to = end; }\n else\n { removed.push(removing = new RemoveMarkStep(start, end, marks[i])); }\n }\n }\n\n if (adding && adding.to == start)\n { adding.to = end; }\n else\n { added.push(adding = new AddMarkStep(start, end, mark)); }\n }\n });\n\n removed.forEach(function (s) { return this$1.step(s); });\n added.forEach(function (s) { return this$1.step(s); });\n return this\n};\n\n// :: (number, number, ?union) → this\n// Remove marks from inline nodes between `from` and `to`. When `mark`\n// is a single mark, remove precisely that mark. When it is a mark type,\n// remove all marks of that type. When it is null, remove all marks of\n// any type.\nTransform.prototype.removeMark = function(from, to, mark) {\n var this$1 = this;\n if ( mark === void 0 ) mark = null;\n\n var matched = [], step = 0;\n this.doc.nodesBetween(from, to, function (node, pos) {\n if (!node.isInline) { return }\n step++;\n var toRemove = null;\n if (mark instanceof MarkType) {\n var found = mark.isInSet(node.marks);\n if (found) { toRemove = [found]; }\n } else if (mark) {\n if (mark.isInSet(node.marks)) { toRemove = [mark]; }\n } else {\n toRemove = node.marks;\n }\n if (toRemove && toRemove.length) {\n var end = Math.min(pos + node.nodeSize, to);\n for (var i = 0; i < toRemove.length; i++) {\n var style = toRemove[i], found$1 = (void 0);\n for (var j = 0; j < matched.length; j++) {\n var m = matched[j];\n if (m.step == step - 1 && style.eq(matched[j].style)) { found$1 = m; }\n }\n if (found$1) {\n found$1.to = end;\n found$1.step = step;\n } else {\n matched.push({style: style, from: Math.max(pos, from), to: end, step: step});\n }\n }\n }\n });\n matched.forEach(function (m) { return this$1.step(new RemoveMarkStep(m.from, m.to, m.style)); });\n return this\n};\n\n// :: (number, NodeType, ?ContentMatch) → this\n// Removes all marks and nodes from the content of the node at `pos`\n// that don't match the given new parent node type. Accepts an\n// optional starting [content match](#model.ContentMatch) as third\n// argument.\nTransform.prototype.clearIncompatible = function(pos, parentType, match) {\n if ( match === void 0 ) match = parentType.contentMatch;\n\n var node = this.doc.nodeAt(pos);\n var delSteps = [], cur = pos + 1;\n for (var i = 0; i < node.childCount; i++) {\n var child = node.child(i), end = cur + child.nodeSize;\n var allowed = match.matchType(child.type, child.attrs);\n if (!allowed) {\n delSteps.push(new ReplaceStep(cur, end, Slice.empty));\n } else {\n match = allowed;\n for (var j = 0; j < child.marks.length; j++) { if (!parentType.allowsMarkType(child.marks[j].type))\n { this.step(new RemoveMarkStep(cur, end, child.marks[j])); } }\n }\n cur = end;\n }\n if (!match.validEnd) {\n var fill = match.fillBefore(Fragment.empty, true);\n this.replace(cur, cur, new Slice(fill, 0, 0));\n }\n for (var i$1 = delSteps.length - 1; i$1 >= 0; i$1--) { this.step(delSteps[i$1]); }\n return this\n};\n\n// :: (Node, number, ?number, ?Slice) → ?Step\n// ‘Fit’ a slice into a given position in the document, producing a\n// [step](#transform.Step) that inserts it. Will return null if\n// there's no meaningful way to insert the slice here, or inserting it\n// would be a no-op (an empty slice over an empty range).\nfunction replaceStep(doc, from, to, slice) {\n if ( to === void 0 ) to = from;\n if ( slice === void 0 ) slice = Slice.empty;\n\n if (from == to && !slice.size) { return null }\n\n var $from = doc.resolve(from), $to = doc.resolve(to);\n // Optimization -- avoid work if it's obvious that it's not needed.\n if (fitsTrivially($from, $to, slice)) { return new ReplaceStep(from, to, slice) }\n return new Fitter($from, $to, slice).fit()\n}\n\n// :: (number, ?number, ?Slice) → this\n// Replace the part of the document between `from` and `to` with the\n// given `slice`.\nTransform.prototype.replace = function(from, to, slice) {\n if ( to === void 0 ) to = from;\n if ( slice === void 0 ) slice = Slice.empty;\n\n var step = replaceStep(this.doc, from, to, slice);\n if (step) { this.step(step); }\n return this\n};\n\n// :: (number, number, union) → this\n// Replace the given range with the given content, which may be a\n// fragment, node, or array of nodes.\nTransform.prototype.replaceWith = function(from, to, content) {\n return this.replace(from, to, new Slice(Fragment.from(content), 0, 0))\n};\n\n// :: (number, number) → this\n// Delete the content between the given positions.\nTransform.prototype.delete = function(from, to) {\n return this.replace(from, to, Slice.empty)\n};\n\n// :: (number, union) → this\n// Insert the given content at the given position.\nTransform.prototype.insert = function(pos, content) {\n return this.replaceWith(pos, pos, content)\n};\n\nfunction fitsTrivially($from, $to, slice) {\n return !slice.openStart && !slice.openEnd && $from.start() == $to.start() &&\n $from.parent.canReplace($from.index(), $to.index(), slice.content)\n}\n\n// Algorithm for 'placing' the elements of a slice into a gap:\n//\n// We consider the content of each node that is open to the left to be\n// independently placeable. I.e. in , when the\n// paragraph on the left is open, \"foo\" can be placed (somewhere on\n// the left side of the replacement gap) independently from p(\"bar\").\n//\n// This class tracks the state of the placement progress in the\n// following properties:\n//\n// - `frontier` holds a stack of `{type, match}` objects that\n// represent the open side of the replacement. It starts at\n// `$from`, then moves forward as content is placed, and is finally\n// reconciled with `$to`.\n//\n// - `unplaced` is a slice that represents the content that hasn't\n// been placed yet.\n//\n// - `placed` is a fragment of placed content. Its open-start value\n// is implicit in `$from`, and its open-end value in `frontier`.\nvar Fitter = function Fitter($from, $to, slice) {\n this.$to = $to;\n this.$from = $from;\n this.unplaced = slice;\n\n this.frontier = [];\n for (var i = 0; i <= $from.depth; i++) {\n var node = $from.node(i);\n this.frontier.push({\n type: node.type,\n match: node.contentMatchAt($from.indexAfter(i))\n });\n }\n\n this.placed = Fragment.empty;\n for (var i$1 = $from.depth; i$1 > 0; i$1--)\n { this.placed = Fragment.from($from.node(i$1).copy(this.placed)); }\n};\n\nvar prototypeAccessors$1 = { depth: { configurable: true } };\n\nprototypeAccessors$1.depth.get = function () { return this.frontier.length - 1 };\n\nFitter.prototype.fit = function fit () {\n // As long as there's unplaced content, try to place some of it.\n // If that fails, either increase the open score of the unplaced\n // slice, or drop nodes from it, and then try again.\n while (this.unplaced.size) {\n var fit = this.findFittable();\n if (fit) { this.placeNodes(fit); }\n else { this.openMore() || this.dropNode(); }\n }\n // When there's inline content directly after the frontier _and_\n // directly after `this.$to`, we must generate a `ReplaceAround`\n // step that pulls that content into the node after the frontier.\n // That means the fitting must be done to the end of the textblock\n // node after `this.$to`, not `this.$to` itself.\n var moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;\n var $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));\n if (!$to) { return null }\n\n // If closing to `$to` succeeded, create a step\n var content = this.placed, openStart = $from.depth, openEnd = $to.depth;\n while (openStart && openEnd && content.childCount == 1) { // Normalize by dropping open parent nodes\n content = content.firstChild.content;\n openStart--; openEnd--;\n }\n var slice = new Slice(content, openStart, openEnd);\n if (moveInline > -1)\n { return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize) }\n if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps\n { return new ReplaceStep($from.pos, $to.pos, slice) }\n};\n\n// Find a position on the start spine of `this.unplaced` that has\n// content that can be moved somewhere on the frontier. Returns two\n// depths, one for the slice and one for the frontier.\nFitter.prototype.findFittable = function findFittable () {\n // Only try wrapping nodes (pass 2) after finding a place without\n // wrapping failed.\n for (var pass = 1; pass <= 2; pass++) {\n for (var sliceDepth = this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {\n var fragment = (void 0), parent = (void 0);\n if (sliceDepth) {\n parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;\n fragment = parent.content;\n } else {\n fragment = this.unplaced.content;\n }\n var first = fragment.firstChild;\n for (var frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {\n var ref = this.frontier[frontierDepth];\n var type = ref.type;\n var match = ref.match;\n var wrap = (void 0), inject = (void 0);\n // In pass 1, if the next node matches, or there is no next\n // node but the parents look compatible, we've found a\n // place.\n if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false))\n : type.compatibleContent(parent.type)))\n { return {sliceDepth: sliceDepth, frontierDepth: frontierDepth, parent: parent, inject: inject} }\n // In pass 2, look for a set of wrapping nodes that make\n // `first` fit here.\n else if (pass == 2 && first && (wrap = match.findWrapping(first.type)))\n { return {sliceDepth: sliceDepth, frontierDepth: frontierDepth, parent: parent, wrap: wrap} }\n // Don't continue looking further up if the parent node\n // would fit here.\n if (parent && match.matchType(parent.type)) { break }\n }\n }\n }\n};\n\nFitter.prototype.openMore = function openMore () {\n var ref = this.unplaced;\n var content = ref.content;\n var openStart = ref.openStart;\n var openEnd = ref.openEnd;\n var inner = contentAt(content, openStart);\n if (!inner.childCount || inner.firstChild.isLeaf) { return false }\n this.unplaced = new Slice(content, openStart + 1,\n Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0));\n return true\n};\n\nFitter.prototype.dropNode = function dropNode () {\n var ref = this.unplaced;\n var content = ref.content;\n var openStart = ref.openStart;\n var openEnd = ref.openEnd;\n var inner = contentAt(content, openStart);\n if (inner.childCount <= 1 && openStart > 0) {\n var openAtEnd = content.size - openStart <= openStart + inner.size;\n this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1,\n openAtEnd ? openStart - 1 : openEnd);\n } else {\n this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);\n }\n};\n\n// : ({sliceDepth: number, frontierDepth: number, parent: ?Node, wrap: ?[NodeType], inject: ?Fragment})\n// Move content from the unplaced slice at `sliceDepth` to the\n// frontier node at `frontierDepth`. Close that frontier node when\n// applicable.\nFitter.prototype.placeNodes = function placeNodes (ref) {\n var sliceDepth = ref.sliceDepth;\n var frontierDepth = ref.frontierDepth;\n var parent = ref.parent;\n var inject = ref.inject;\n var wrap = ref.wrap;\n\n while (this.depth > frontierDepth) { this.closeFrontierNode(); }\n if (wrap) { for (var i = 0; i < wrap.length; i++) { this.openFrontierNode(wrap[i]); } }\n\n var slice = this.unplaced, fragment = parent ? parent.content : slice.content;\n var openStart = slice.openStart - sliceDepth;\n var taken = 0, add = [];\n var ref$1 = this.frontier[frontierDepth];\n var match = ref$1.match;\n var type = ref$1.type;\n if (inject) {\n for (var i$1 = 0; i$1 < inject.childCount; i$1++) { add.push(inject.child(i$1)); }\n match = match.matchFragment(inject);\n }\n // Computes the amount of (end) open nodes at the end of the\n // fragment. When 0, the parent is open, but no more. When\n // negative, nothing is open.\n var openEndCount = (fragment.size + sliceDepth) - (slice.content.size - slice.openEnd);\n // Scan over the fragment, fitting as many child nodes as\n // possible.\n while (taken < fragment.childCount) {\n var next = fragment.child(taken), matches = match.matchType(next.type);\n if (!matches) { break }\n taken++;\n if (taken > 1 || openStart == 0 || next.content.size) { // Drop empty open nodes\n match = matches;\n add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0,\n taken == fragment.childCount ? openEndCount : -1));\n }\n }\n var toEnd = taken == fragment.childCount;\n if (!toEnd) { openEndCount = -1; }\n\n this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));\n this.frontier[frontierDepth].match = match;\n\n // If the parent types match, and the entire node was moved, and\n // it's not open, close this frontier node right away.\n if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type) { this.closeFrontierNode(); }\n\n // Add new frontier nodes for any open nodes at the end.\n for (var i$2 = 0, cur = fragment; i$2 < openEndCount; i$2++) {\n var node = cur.lastChild;\n this.frontier.push({type: node.type, match: node.contentMatchAt(node.childCount)});\n cur = node.content;\n }\n\n // Update `this.unplaced`. Drop the entire node from which we\n // placed it we got to its end, otherwise just drop the placed\n // nodes.\n this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd)\n : sliceDepth == 0 ? Slice.empty\n : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1),\n sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);\n};\n\nFitter.prototype.mustMoveInline = function mustMoveInline () {\n if (!this.$to.parent.isTextblock || this.$to.end() == this.$to.pos) { return -1 }\n var top = this.frontier[this.depth], level;\n if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) ||\n (this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth)) { return -1 }\n\n var ref = this.$to;\n var depth = ref.depth;\n var after = this.$to.after(depth);\n while (depth > 1 && after == this.$to.end(--depth)) { ++after; }\n return after\n};\n\nFitter.prototype.findCloseLevel = function findCloseLevel ($to) {\n scan: for (var i = Math.min(this.depth, $to.depth); i >= 0; i--) {\n var ref = this.frontier[i];\n var match = ref.match;\n var type = ref.type;\n var dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));\n var fit = contentAfterFits($to, i, type, match, dropInner);\n if (!fit) { continue }\n for (var d = i - 1; d >= 0; d--) {\n var ref$1 = this.frontier[d];\n var match$1 = ref$1.match;\n var type$1 = ref$1.type;\n var matches = contentAfterFits($to, d, type$1, match$1, true);\n if (!matches || matches.childCount) { continue scan }\n }\n return {depth: i, fit: fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to}\n }\n};\n\nFitter.prototype.close = function close ($to) {\n var close = this.findCloseLevel($to);\n if (!close) { return null }\n\n while (this.depth > close.depth) { this.closeFrontierNode(); }\n if (close.fit.childCount) { this.placed = addToFragment(this.placed, close.depth, close.fit); }\n $to = close.move;\n for (var d = close.depth + 1; d <= $to.depth; d++) {\n var node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));\n this.openFrontierNode(node.type, node.attrs, add);\n }\n return $to\n};\n\nFitter.prototype.openFrontierNode = function openFrontierNode (type, attrs, content) {\n var top = this.frontier[this.depth];\n top.match = top.match.matchType(type);\n this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));\n this.frontier.push({type: type, match: type.contentMatch});\n};\n\nFitter.prototype.closeFrontierNode = function closeFrontierNode () {\n var open = this.frontier.pop();\n var add = open.match.fillBefore(Fragment.empty, true);\n if (add.childCount) { this.placed = addToFragment(this.placed, this.frontier.length, add); }\n};\n\nObject.defineProperties( Fitter.prototype, prototypeAccessors$1 );\n\nfunction dropFromFragment(fragment, depth, count) {\n if (depth == 0) { return fragment.cutByIndex(count) }\n return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)))\n}\n\nfunction addToFragment(fragment, depth, content) {\n if (depth == 0) { return fragment.append(content) }\n return fragment.replaceChild(fragment.childCount - 1,\n fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)))\n}\n\nfunction contentAt(fragment, depth) {\n for (var i = 0; i < depth; i++) { fragment = fragment.firstChild.content; }\n return fragment\n}\n\nfunction closeNodeStart(node, openStart, openEnd) {\n if (openStart <= 0) { return node }\n var frag = node.content;\n if (openStart > 1)\n { frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0)); }\n if (openStart > 0) {\n frag = node.type.contentMatch.fillBefore(frag).append(frag);\n if (openEnd <= 0) { frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true)); }\n }\n return node.copy(frag)\n}\n\nfunction contentAfterFits($to, depth, type, match, open) {\n var node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);\n if (index == node.childCount && !type.compatibleContent(node.type)) { return null }\n var fit = match.fillBefore(node.content, true, index);\n return fit && !invalidMarks(type, node.content, index) ? fit : null\n}\n\nfunction invalidMarks(type, fragment, start) {\n for (var i = start; i < fragment.childCount; i++)\n { if (!type.allowsMarks(fragment.child(i).marks)) { return true } }\n return false\n}\n\n// :: (number, number, Slice) → this\n// Replace a range of the document with a given slice, using `from`,\n// `to`, and the slice's [`openStart`](#model.Slice.openStart) property\n// as hints, rather than fixed start and end points. This method may\n// grow the replaced area or close open nodes in the slice in order to\n// get a fit that is more in line with WYSIWYG expectations, by\n// dropping fully covered parent nodes of the replaced region when\n// they are marked [non-defining](#model.NodeSpec.defining), or\n// including an open parent node from the slice that _is_ marked as\n// [defining](#model.NodeSpec.defining).\n//\n// This is the method, for example, to handle paste. The similar\n// [`replace`](#transform.Transform.replace) method is a more\n// primitive tool which will _not_ move the start and end of its given\n// range, and is useful in situations where you need more precise\n// control over what happens.\nTransform.prototype.replaceRange = function(from, to, slice) {\n if (!slice.size) { return this.deleteRange(from, to) }\n\n var $from = this.doc.resolve(from), $to = this.doc.resolve(to);\n if (fitsTrivially($from, $to, slice))\n { return this.step(new ReplaceStep(from, to, slice)) }\n\n var targetDepths = coveredDepths($from, this.doc.resolve(to));\n // Can't replace the whole document, so remove 0 if it's present\n if (targetDepths[targetDepths.length - 1] == 0) { targetDepths.pop(); }\n // Negative numbers represent not expansion over the whole node at\n // that depth, but replacing from $from.before(-D) to $to.pos.\n var preferredTarget = -($from.depth + 1);\n targetDepths.unshift(preferredTarget);\n // This loop picks a preferred target depth, if one of the covering\n // depths is not outside of a defining node, and adds negative\n // depths for any depth that has $from at its start and does not\n // cross a defining node.\n for (var d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {\n var spec = $from.node(d).type.spec;\n if (spec.defining || spec.isolating) { break }\n if (targetDepths.indexOf(d) > -1) { preferredTarget = d; }\n else if ($from.before(d) == pos) { targetDepths.splice(1, 0, -d); }\n }\n // Try to fit each possible depth of the slice into each possible\n // target depth, starting with the preferred depths.\n var preferredTargetIndex = targetDepths.indexOf(preferredTarget);\n\n var leftNodes = [], preferredDepth = slice.openStart;\n for (var content = slice.content, i = 0;; i++) {\n var node = content.firstChild;\n leftNodes.push(node);\n if (i == slice.openStart) { break }\n content = node.content;\n }\n // Back up if the node directly above openStart, or the node above\n // that separated only by a non-defining textblock node, is defining.\n if (preferredDepth > 0 && leftNodes[preferredDepth - 1].type.spec.defining &&\n $from.node(preferredTargetIndex).type != leftNodes[preferredDepth - 1].type)\n { preferredDepth -= 1; }\n else if (preferredDepth >= 2 && leftNodes[preferredDepth - 1].isTextblock && leftNodes[preferredDepth - 2].type.spec.defining &&\n $from.node(preferredTargetIndex).type != leftNodes[preferredDepth - 2].type)\n { preferredDepth -= 2; }\n\n for (var j = slice.openStart; j >= 0; j--) {\n var openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);\n var insert = leftNodes[openDepth];\n if (!insert) { continue }\n for (var i$1 = 0; i$1 < targetDepths.length; i$1++) {\n // Loop over possible expansion levels, starting with the\n // preferred one\n var targetDepth = targetDepths[(i$1 + preferredTargetIndex) % targetDepths.length], expand = true;\n if (targetDepth < 0) { expand = false; targetDepth = -targetDepth; }\n var parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);\n if (parent.canReplaceWith(index, index, insert.type, insert.marks))\n { return this.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to,\n new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth),\n openDepth, slice.openEnd)) }\n }\n }\n\n var startSteps = this.steps.length;\n for (var i$2 = targetDepths.length - 1; i$2 >= 0; i$2--) {\n this.replace(from, to, slice);\n if (this.steps.length > startSteps) { break }\n var depth = targetDepths[i$2];\n if (i$2 < 0) { continue }\n from = $from.before(depth); to = $to.after(depth);\n }\n return this\n};\n\nfunction closeFragment(fragment, depth, oldOpen, newOpen, parent) {\n if (depth < oldOpen) {\n var first = fragment.firstChild;\n fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));\n }\n if (depth > newOpen) {\n var match = parent.contentMatchAt(0);\n var start = match.fillBefore(fragment).append(fragment);\n fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));\n }\n return fragment\n}\n\n// :: (number, number, Node) → this\n// Replace the given range with a node, but use `from` and `to` as\n// hints, rather than precise positions. When from and to are the same\n// and are at the start or end of a parent node in which the given\n// node doesn't fit, this method may _move_ them out towards a parent\n// that does allow the given node to be placed. When the given range\n// completely covers a parent node, this method may completely replace\n// that parent node.\nTransform.prototype.replaceRangeWith = function(from, to, node) {\n if (!node.isInline && from == to && this.doc.resolve(from).parent.content.size) {\n var point = insertPoint(this.doc, from, node.type);\n if (point != null) { from = to = point; }\n }\n return this.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0))\n};\n\n// :: (number, number) → this\n// Delete the given range, expanding it to cover fully covered\n// parent nodes until a valid replace is found.\nTransform.prototype.deleteRange = function(from, to) {\n var $from = this.doc.resolve(from), $to = this.doc.resolve(to);\n var covered = coveredDepths($from, $to);\n for (var i = 0; i < covered.length; i++) {\n var depth = covered[i], last = i == covered.length - 1;\n if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd)\n { return this.delete($from.start(depth), $to.end(depth)) }\n if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))\n { return this.delete($from.before(depth), $to.after(depth)) }\n }\n for (var d = 1; d <= $from.depth && d <= $to.depth; d++) {\n if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d)\n { return this.delete($from.before(d), to) }\n }\n return this.delete(from, to)\n};\n\n// : (ResolvedPos, ResolvedPos) → [number]\n// Returns an array of all depths for which $from - $to spans the\n// whole content of the nodes at that depth.\nfunction coveredDepths($from, $to) {\n var result = [], minDepth = Math.min($from.depth, $to.depth);\n for (var d = minDepth; d >= 0; d--) {\n var start = $from.start(d);\n if (start < $from.pos - ($from.depth - d) ||\n $to.end(d) > $to.pos + ($to.depth - d) ||\n $from.node(d).type.spec.isolating ||\n $to.node(d).type.spec.isolating) { break }\n if (start == $to.start(d)) { result.push(d); }\n }\n return result\n}\n\nexport { AddMarkStep, MapResult, Mapping, RemoveMarkStep, ReplaceAroundStep, ReplaceStep, Step, StepMap, StepResult, Transform, TransformError, canJoin, canSplit, dropPoint, findWrapping, insertPoint, joinPoint, liftTarget, replaceStep };\n//# sourceMappingURL=index.es.js.map\n","import { Slice, Fragment, Mark, Node } from 'prosemirror-model';\nimport { ReplaceStep, ReplaceAroundStep, Transform } from 'prosemirror-transform';\n\nvar classesById = Object.create(null);\n\n// ::- Superclass for editor selections. Every selection type should\n// extend this. Should not be instantiated directly.\nvar Selection = function Selection($anchor, $head, ranges) {\n // :: [SelectionRange]\n // The ranges covered by the selection.\n this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];\n // :: ResolvedPos\n // The resolved anchor of the selection (the side that stays in\n // place when the selection is modified).\n this.$anchor = $anchor;\n // :: ResolvedPos\n // The resolved head of the selection (the side that moves when\n // the selection is modified).\n this.$head = $head;\n};\n\nvar prototypeAccessors = { anchor: { configurable: true },head: { configurable: true },from: { configurable: true },to: { configurable: true },$from: { configurable: true },$to: { configurable: true },empty: { configurable: true } };\n\n// :: number\n// The selection's anchor, as an unresolved position.\nprototypeAccessors.anchor.get = function () { return this.$anchor.pos };\n\n// :: number\n// The selection's head.\nprototypeAccessors.head.get = function () { return this.$head.pos };\n\n// :: number\n// The lower bound of the selection's main range.\nprototypeAccessors.from.get = function () { return this.$from.pos };\n\n// :: number\n// The upper bound of the selection's main range.\nprototypeAccessors.to.get = function () { return this.$to.pos };\n\n// :: ResolvedPos\n// The resolved lowerbound of the selection's main range.\nprototypeAccessors.$from.get = function () {\n return this.ranges[0].$from\n};\n\n// :: ResolvedPos\n// The resolved upper bound of the selection's main range.\nprototypeAccessors.$to.get = function () {\n return this.ranges[0].$to\n};\n\n// :: bool\n// Indicates whether the selection contains any content.\nprototypeAccessors.empty.get = function () {\n var ranges = this.ranges;\n for (var i = 0; i < ranges.length; i++)\n { if (ranges[i].$from.pos != ranges[i].$to.pos) { return false } }\n return true\n};\n\n// eq:: (Selection) → bool\n// Test whether the selection is the same as another selection.\n\n// map:: (doc: Node, mapping: Mappable) → Selection\n// Map this selection through a [mappable](#transform.Mappable) thing. `doc`\n// should be the new document to which we are mapping.\n\n// :: () → Slice\n// Get the content of this selection as a slice.\nSelection.prototype.content = function content () {\n return this.$from.node(0).slice(this.from, this.to, true)\n};\n\n// :: (Transaction, ?Slice)\n// Replace the selection with a slice or, if no slice is given,\n// delete the selection. Will append to the given transaction.\nSelection.prototype.replace = function replace (tr, content) {\n if ( content === void 0 ) content = Slice.empty;\n\n // Put the new selection at the position after the inserted\n // content. When that ended in an inline node, search backwards,\n // to get the position after that node. If not, search forward.\n var lastNode = content.content.lastChild, lastParent = null;\n for (var i = 0; i < content.openEnd; i++) {\n lastParent = lastNode;\n lastNode = lastNode.lastChild;\n }\n\n var mapFrom = tr.steps.length, ranges = this.ranges;\n for (var i$1 = 0; i$1 < ranges.length; i$1++) {\n var ref = ranges[i$1];\n var $from = ref.$from;\n var $to = ref.$to;\n var mapping = tr.mapping.slice(mapFrom);\n tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i$1 ? Slice.empty : content);\n if (i$1 == 0)\n { selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1); }\n }\n};\n\n// :: (Transaction, Node)\n// Replace the selection with the given node, appending the changes\n// to the given transaction.\nSelection.prototype.replaceWith = function replaceWith (tr, node) {\n var mapFrom = tr.steps.length, ranges = this.ranges;\n for (var i = 0; i < ranges.length; i++) {\n var ref = ranges[i];\n var $from = ref.$from;\n var $to = ref.$to;\n var mapping = tr.mapping.slice(mapFrom);\n var from = mapping.map($from.pos), to = mapping.map($to.pos);\n if (i) {\n tr.deleteRange(from, to);\n } else {\n tr.replaceRangeWith(from, to, node);\n selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);\n }\n }\n};\n\n// toJSON:: () → Object\n// Convert the selection to a JSON representation. When implementing\n// this for a custom selection class, make sure to give the object a\n// `type` property whose value matches the ID under which you\n// [registered](#state.Selection^jsonID) your class.\n\n// :: (ResolvedPos, number, ?bool) → ?Selection\n// Find a valid cursor or leaf node selection starting at the given\n// position and searching back if `dir` is negative, and forward if\n// positive. When `textOnly` is true, only consider cursor\n// selections. Will return null when no valid selection position is\n// found.\nSelection.findFrom = function findFrom ($pos, dir, textOnly) {\n var inner = $pos.parent.inlineContent ? new TextSelection($pos)\n : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);\n if (inner) { return inner }\n\n for (var depth = $pos.depth - 1; depth >= 0; depth--) {\n var found = dir < 0\n ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly)\n : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);\n if (found) { return found }\n }\n};\n\n// :: (ResolvedPos, ?number) → Selection\n// Find a valid cursor or leaf node selection near the given\n// position. Searches forward first by default, but if `bias` is\n// negative, it will search backwards first.\nSelection.near = function near ($pos, bias) {\n if ( bias === void 0 ) bias = 1;\n\n return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0))\n};\n\n// :: (Node) → Selection\n// Find the cursor or leaf node selection closest to the start of\n// the given document. Will return an\n// [`AllSelection`](#state.AllSelection) if no valid position\n// exists.\nSelection.atStart = function atStart (doc) {\n return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc)\n};\n\n// :: (Node) → Selection\n// Find the cursor or leaf node selection closest to the end of the\n// given document.\nSelection.atEnd = function atEnd (doc) {\n return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc)\n};\n\n// :: (Node, Object) → Selection\n// Deserialize the JSON representation of a selection. Must be\n// implemented for custom classes (as a static class method).\nSelection.fromJSON = function fromJSON (doc, json) {\n if (!json || !json.type) { throw new RangeError(\"Invalid input for Selection.fromJSON\") }\n var cls = classesById[json.type];\n if (!cls) { throw new RangeError((\"No selection type \" + (json.type) + \" defined\")) }\n return cls.fromJSON(doc, json)\n};\n\n// :: (string, constructor)\n// To be able to deserialize selections from JSON, custom selection\n// classes must register themselves with an ID string, so that they\n// can be disambiguated. Try to pick something that's unlikely to\n// clash with classes from other modules.\nSelection.jsonID = function jsonID (id, selectionClass) {\n if (id in classesById) { throw new RangeError(\"Duplicate use of selection JSON ID \" + id) }\n classesById[id] = selectionClass;\n selectionClass.prototype.jsonID = id;\n return selectionClass\n};\n\n// :: () → SelectionBookmark\n// Get a [bookmark](#state.SelectionBookmark) for this selection,\n// which is a value that can be mapped without having access to a\n// current document, and later resolved to a real selection for a\n// given document again. (This is used mostly by the history to\n// track and restore old selections.) The default implementation of\n// this method just converts the selection to a text selection and\n// returns the bookmark for that.\nSelection.prototype.getBookmark = function getBookmark () {\n return TextSelection.between(this.$anchor, this.$head).getBookmark()\n};\n\nObject.defineProperties( Selection.prototype, prototypeAccessors );\n\n// :: bool\n// Controls whether, when a selection of this type is active in the\n// browser, the selected range should be visible to the user. Defaults\n// to `true`.\nSelection.prototype.visible = true;\n\n// SelectionBookmark:: interface\n// A lightweight, document-independent representation of a selection.\n// You can define a custom bookmark type for a custom selection class\n// to make the history handle it well.\n//\n// map:: (mapping: Mapping) → SelectionBookmark\n// Map the bookmark through a set of changes.\n//\n// resolve:: (doc: Node) → Selection\n// Resolve the bookmark to a real selection again. This may need to\n// do some error checking and may fall back to a default (usually\n// [`TextSelection.between`](#state.TextSelection^between)) if\n// mapping made the bookmark invalid.\n\n// ::- Represents a selected range in a document.\nvar SelectionRange = function SelectionRange($from, $to) {\n // :: ResolvedPos\n // The lower bound of the range.\n this.$from = $from;\n // :: ResolvedPos\n // The upper bound of the range.\n this.$to = $to;\n};\n\n// ::- A text selection represents a classical editor selection, with\n// a head (the moving side) and anchor (immobile side), both of which\n// point into textblock nodes. It can be empty (a regular cursor\n// position).\nvar TextSelection = /*@__PURE__*/(function (Selection) {\n function TextSelection($anchor, $head) {\n if ( $head === void 0 ) $head = $anchor;\n\n Selection.call(this, $anchor, $head);\n }\n\n if ( Selection ) TextSelection.__proto__ = Selection;\n TextSelection.prototype = Object.create( Selection && Selection.prototype );\n TextSelection.prototype.constructor = TextSelection;\n\n var prototypeAccessors$1 = { $cursor: { configurable: true } };\n\n // :: ?ResolvedPos\n // Returns a resolved position if this is a cursor selection (an\n // empty text selection), and null otherwise.\n prototypeAccessors$1.$cursor.get = function () { return this.$anchor.pos == this.$head.pos ? this.$head : null };\n\n TextSelection.prototype.map = function map (doc, mapping) {\n var $head = doc.resolve(mapping.map(this.head));\n if (!$head.parent.inlineContent) { return Selection.near($head) }\n var $anchor = doc.resolve(mapping.map(this.anchor));\n return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head)\n };\n\n TextSelection.prototype.replace = function replace (tr, content) {\n if ( content === void 0 ) content = Slice.empty;\n\n Selection.prototype.replace.call(this, tr, content);\n if (content == Slice.empty) {\n var marks = this.$from.marksAcross(this.$to);\n if (marks) { tr.ensureMarks(marks); }\n }\n };\n\n TextSelection.prototype.eq = function eq (other) {\n return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head\n };\n\n TextSelection.prototype.getBookmark = function getBookmark () {\n return new TextBookmark(this.anchor, this.head)\n };\n\n TextSelection.prototype.toJSON = function toJSON () {\n return {type: \"text\", anchor: this.anchor, head: this.head}\n };\n\n TextSelection.fromJSON = function fromJSON (doc, json) {\n if (typeof json.anchor != \"number\" || typeof json.head != \"number\")\n { throw new RangeError(\"Invalid input for TextSelection.fromJSON\") }\n return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head))\n };\n\n // :: (Node, number, ?number) → TextSelection\n // Create a text selection from non-resolved positions.\n TextSelection.create = function create (doc, anchor, head) {\n if ( head === void 0 ) head = anchor;\n\n var $anchor = doc.resolve(anchor);\n return new this($anchor, head == anchor ? $anchor : doc.resolve(head))\n };\n\n // :: (ResolvedPos, ResolvedPos, ?number) → Selection\n // Return a text selection that spans the given positions or, if\n // they aren't text positions, find a text selection near them.\n // `bias` determines whether the method searches forward (default)\n // or backwards (negative number) first. Will fall back to calling\n // [`Selection.near`](#state.Selection^near) when the document\n // doesn't contain a valid text position.\n TextSelection.between = function between ($anchor, $head, bias) {\n var dPos = $anchor.pos - $head.pos;\n if (!bias || dPos) { bias = dPos >= 0 ? 1 : -1; }\n if (!$head.parent.inlineContent) {\n var found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);\n if (found) { $head = found.$head; }\n else { return Selection.near($head, bias) }\n }\n if (!$anchor.parent.inlineContent) {\n if (dPos == 0) {\n $anchor = $head;\n } else {\n $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;\n if (($anchor.pos < $head.pos) != (dPos < 0)) { $anchor = $head; }\n }\n }\n return new TextSelection($anchor, $head)\n };\n\n Object.defineProperties( TextSelection.prototype, prototypeAccessors$1 );\n\n return TextSelection;\n}(Selection));\n\nSelection.jsonID(\"text\", TextSelection);\n\nvar TextBookmark = function TextBookmark(anchor, head) {\n this.anchor = anchor;\n this.head = head;\n};\nTextBookmark.prototype.map = function map (mapping) {\n return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head))\n};\nTextBookmark.prototype.resolve = function resolve (doc) {\n return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head))\n};\n\n// ::- A node selection is a selection that points at a single node.\n// All nodes marked [selectable](#model.NodeSpec.selectable) can be\n// the target of a node selection. In such a selection, `from` and\n// `to` point directly before and after the selected node, `anchor`\n// equals `from`, and `head` equals `to`..\nvar NodeSelection = /*@__PURE__*/(function (Selection) {\n function NodeSelection($pos) {\n var node = $pos.nodeAfter;\n var $end = $pos.node(0).resolve($pos.pos + node.nodeSize);\n Selection.call(this, $pos, $end);\n // :: Node The selected node.\n this.node = node;\n }\n\n if ( Selection ) NodeSelection.__proto__ = Selection;\n NodeSelection.prototype = Object.create( Selection && Selection.prototype );\n NodeSelection.prototype.constructor = NodeSelection;\n\n NodeSelection.prototype.map = function map (doc, mapping) {\n var ref = mapping.mapResult(this.anchor);\n var deleted = ref.deleted;\n var pos = ref.pos;\n var $pos = doc.resolve(pos);\n if (deleted) { return Selection.near($pos) }\n return new NodeSelection($pos)\n };\n\n NodeSelection.prototype.content = function content () {\n return new Slice(Fragment.from(this.node), 0, 0)\n };\n\n NodeSelection.prototype.eq = function eq (other) {\n return other instanceof NodeSelection && other.anchor == this.anchor\n };\n\n NodeSelection.prototype.toJSON = function toJSON () {\n return {type: \"node\", anchor: this.anchor}\n };\n\n NodeSelection.prototype.getBookmark = function getBookmark () { return new NodeBookmark(this.anchor) };\n\n NodeSelection.fromJSON = function fromJSON (doc, json) {\n if (typeof json.anchor != \"number\")\n { throw new RangeError(\"Invalid input for NodeSelection.fromJSON\") }\n return new NodeSelection(doc.resolve(json.anchor))\n };\n\n // :: (Node, number) → NodeSelection\n // Create a node selection from non-resolved positions.\n NodeSelection.create = function create (doc, from) {\n return new this(doc.resolve(from))\n };\n\n // :: (Node) → bool\n // Determines whether the given node may be selected as a node\n // selection.\n NodeSelection.isSelectable = function isSelectable (node) {\n return !node.isText && node.type.spec.selectable !== false\n };\n\n return NodeSelection;\n}(Selection));\n\nNodeSelection.prototype.visible = false;\n\nSelection.jsonID(\"node\", NodeSelection);\n\nvar NodeBookmark = function NodeBookmark(anchor) {\n this.anchor = anchor;\n};\nNodeBookmark.prototype.map = function map (mapping) {\n var ref = mapping.mapResult(this.anchor);\n var deleted = ref.deleted;\n var pos = ref.pos;\n return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos)\n};\nNodeBookmark.prototype.resolve = function resolve (doc) {\n var $pos = doc.resolve(this.anchor), node = $pos.nodeAfter;\n if (node && NodeSelection.isSelectable(node)) { return new NodeSelection($pos) }\n return Selection.near($pos)\n};\n\n// ::- A selection type that represents selecting the whole document\n// (which can not necessarily be expressed with a text selection, when\n// there are for example leaf block nodes at the start or end of the\n// document).\nvar AllSelection = /*@__PURE__*/(function (Selection) {\n function AllSelection(doc) {\n Selection.call(this, doc.resolve(0), doc.resolve(doc.content.size));\n }\n\n if ( Selection ) AllSelection.__proto__ = Selection;\n AllSelection.prototype = Object.create( Selection && Selection.prototype );\n AllSelection.prototype.constructor = AllSelection;\n\n AllSelection.prototype.replace = function replace (tr, content) {\n if ( content === void 0 ) content = Slice.empty;\n\n if (content == Slice.empty) {\n tr.delete(0, tr.doc.content.size);\n var sel = Selection.atStart(tr.doc);\n if (!sel.eq(tr.selection)) { tr.setSelection(sel); }\n } else {\n Selection.prototype.replace.call(this, tr, content);\n }\n };\n\n AllSelection.prototype.toJSON = function toJSON () { return {type: \"all\"} };\n\n AllSelection.fromJSON = function fromJSON (doc) { return new AllSelection(doc) };\n\n AllSelection.prototype.map = function map (doc) { return new AllSelection(doc) };\n\n AllSelection.prototype.eq = function eq (other) { return other instanceof AllSelection };\n\n AllSelection.prototype.getBookmark = function getBookmark () { return AllBookmark };\n\n return AllSelection;\n}(Selection));\n\nSelection.jsonID(\"all\", AllSelection);\n\nvar AllBookmark = {\n map: function map() { return this },\n resolve: function resolve(doc) { return new AllSelection(doc) }\n};\n\n// FIXME we'll need some awareness of text direction when scanning for selections\n\n// Try to find a selection inside the given node. `pos` points at the\n// position where the search starts. When `text` is true, only return\n// text selections.\nfunction findSelectionIn(doc, node, pos, index, dir, text) {\n if (node.inlineContent) { return TextSelection.create(doc, pos) }\n for (var i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {\n var child = node.child(i);\n if (!child.isAtom) {\n var inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);\n if (inner) { return inner }\n } else if (!text && NodeSelection.isSelectable(child)) {\n return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0))\n }\n pos += child.nodeSize * dir;\n }\n}\n\nfunction selectionToInsertionEnd(tr, startLen, bias) {\n var last = tr.steps.length - 1;\n if (last < startLen) { return }\n var step = tr.steps[last];\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) { return }\n var map = tr.mapping.maps[last], end;\n map.forEach(function (_from, _to, _newFrom, newTo) { if (end == null) { end = newTo; } });\n tr.setSelection(Selection.near(tr.doc.resolve(end), bias));\n}\n\nvar UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;\n\n// ::- An editor state transaction, which can be applied to a state to\n// create an updated state. Use\n// [`EditorState.tr`](#state.EditorState.tr) to create an instance.\n//\n// Transactions track changes to the document (they are a subclass of\n// [`Transform`](#transform.Transform)), but also other state changes,\n// like selection updates and adjustments of the set of [stored\n// marks](#state.EditorState.storedMarks). In addition, you can store\n// metadata properties in a transaction, which are extra pieces of\n// information that client code or plugins can use to describe what a\n// transacion represents, so that they can update their [own\n// state](#state.StateField) accordingly.\n//\n// The [editor view](#view.EditorView) uses a few metadata properties:\n// it will attach a property `\"pointer\"` with the value `true` to\n// selection transactions directly caused by mouse or touch input, and\n// a `\"uiEvent\"` property of that may be `\"paste\"`, `\"cut\"`, or `\"drop\"`.\nvar Transaction = /*@__PURE__*/(function (Transform) {\n function Transaction(state) {\n Transform.call(this, state.doc);\n // :: number\n // The timestamp associated with this transaction, in the same\n // format as `Date.now()`.\n this.time = Date.now();\n this.curSelection = state.selection;\n // The step count for which the current selection is valid.\n this.curSelectionFor = 0;\n // :: ?[Mark]\n // The stored marks set by this transaction, if any.\n this.storedMarks = state.storedMarks;\n // Bitfield to track which aspects of the state were updated by\n // this transaction.\n this.updated = 0;\n // Object used to store metadata properties for the transaction.\n this.meta = Object.create(null);\n }\n\n if ( Transform ) Transaction.__proto__ = Transform;\n Transaction.prototype = Object.create( Transform && Transform.prototype );\n Transaction.prototype.constructor = Transaction;\n\n var prototypeAccessors = { selection: { configurable: true },selectionSet: { configurable: true },storedMarksSet: { configurable: true },isGeneric: { configurable: true },scrolledIntoView: { configurable: true } };\n\n // :: Selection\n // The transaction's current selection. This defaults to the editor\n // selection [mapped](#state.Selection.map) through the steps in the\n // transaction, but can be overwritten with\n // [`setSelection`](#state.Transaction.setSelection).\n prototypeAccessors.selection.get = function () {\n if (this.curSelectionFor < this.steps.length) {\n this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));\n this.curSelectionFor = this.steps.length;\n }\n return this.curSelection\n };\n\n // :: (Selection) → Transaction\n // Update the transaction's current selection. Will determine the\n // selection that the editor gets when the transaction is applied.\n Transaction.prototype.setSelection = function setSelection (selection) {\n if (selection.$from.doc != this.doc)\n { throw new RangeError(\"Selection passed to setSelection must point at the current document\") }\n this.curSelection = selection;\n this.curSelectionFor = this.steps.length;\n this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;\n this.storedMarks = null;\n return this\n };\n\n // :: bool\n // Whether the selection was explicitly updated by this transaction.\n prototypeAccessors.selectionSet.get = function () {\n return (this.updated & UPDATED_SEL) > 0\n };\n\n // :: (?[Mark]) → Transaction\n // Set the current stored marks.\n Transaction.prototype.setStoredMarks = function setStoredMarks (marks) {\n this.storedMarks = marks;\n this.updated |= UPDATED_MARKS;\n return this\n };\n\n // :: ([Mark]) → Transaction\n // Make sure the current stored marks or, if that is null, the marks\n // at the selection, match the given set of marks. Does nothing if\n // this is already the case.\n Transaction.prototype.ensureMarks = function ensureMarks (marks) {\n if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))\n { this.setStoredMarks(marks); }\n return this\n };\n\n // :: (Mark) → Transaction\n // Add a mark to the set of stored marks.\n Transaction.prototype.addStoredMark = function addStoredMark (mark) {\n return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()))\n };\n\n // :: (union) → Transaction\n // Remove a mark or mark type from the set of stored marks.\n Transaction.prototype.removeStoredMark = function removeStoredMark (mark) {\n return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()))\n };\n\n // :: bool\n // Whether the stored marks were explicitly set for this transaction.\n prototypeAccessors.storedMarksSet.get = function () {\n return (this.updated & UPDATED_MARKS) > 0\n };\n\n Transaction.prototype.addStep = function addStep (step, doc) {\n Transform.prototype.addStep.call(this, step, doc);\n this.updated = this.updated & ~UPDATED_MARKS;\n this.storedMarks = null;\n };\n\n // :: (number) → Transaction\n // Update the timestamp for the transaction.\n Transaction.prototype.setTime = function setTime (time) {\n this.time = time;\n return this\n };\n\n // :: (Slice) → Transaction\n // Replace the current selection with the given slice.\n Transaction.prototype.replaceSelection = function replaceSelection (slice) {\n this.selection.replace(this, slice);\n return this\n };\n\n // :: (Node, ?bool) → Transaction\n // Replace the selection with the given node. When `inheritMarks` is\n // true and the content is inline, it inherits the marks from the\n // place where it is inserted.\n Transaction.prototype.replaceSelectionWith = function replaceSelectionWith (node, inheritMarks) {\n var selection = this.selection;\n if (inheritMarks !== false)\n { node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : (selection.$from.marksAcross(selection.$to) || Mark.none))); }\n selection.replaceWith(this, node);\n return this\n };\n\n // :: () → Transaction\n // Delete the selection.\n Transaction.prototype.deleteSelection = function deleteSelection () {\n this.selection.replace(this);\n return this\n };\n\n // :: (string, from: ?number, to: ?number) → Transaction\n // Replace the given range, or the selection if no range is given,\n // with a text node containing the given string.\n Transaction.prototype.insertText = function insertText (text, from, to) {\n if ( to === void 0 ) to = from;\n\n var schema = this.doc.type.schema;\n if (from == null) {\n if (!text) { return this.deleteSelection() }\n return this.replaceSelectionWith(schema.text(text), true)\n } else {\n if (!text) { return this.deleteRange(from, to) }\n var marks = this.storedMarks;\n if (!marks) {\n var $from = this.doc.resolve(from);\n marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));\n }\n this.replaceRangeWith(from, to, schema.text(text, marks));\n if (!this.selection.empty) { this.setSelection(Selection.near(this.selection.$to)); }\n return this\n }\n };\n\n // :: (union, any) → Transaction\n // Store a metadata property in this transaction, keyed either by\n // name or by plugin.\n Transaction.prototype.setMeta = function setMeta (key, value) {\n this.meta[typeof key == \"string\" ? key : key.key] = value;\n return this\n };\n\n // :: (union) → any\n // Retrieve a metadata property for a given name or plugin.\n Transaction.prototype.getMeta = function getMeta (key) {\n return this.meta[typeof key == \"string\" ? key : key.key]\n };\n\n // :: bool\n // Returns true if this transaction doesn't contain any metadata,\n // and can thus safely be extended.\n prototypeAccessors.isGeneric.get = function () {\n for (var _ in this.meta) { return false }\n return true\n };\n\n // :: () → Transaction\n // Indicate that the editor should scroll the selection into view\n // when updated to the state produced by this transaction.\n Transaction.prototype.scrollIntoView = function scrollIntoView () {\n this.updated |= UPDATED_SCROLL;\n return this\n };\n\n prototypeAccessors.scrolledIntoView.get = function () {\n return (this.updated & UPDATED_SCROLL) > 0\n };\n\n Object.defineProperties( Transaction.prototype, prototypeAccessors );\n\n return Transaction;\n}(Transform));\n\nfunction bind(f, self) {\n return !self || !f ? f : f.bind(self)\n}\n\nvar FieldDesc = function FieldDesc(name, desc, self) {\n this.name = name;\n this.init = bind(desc.init, self);\n this.apply = bind(desc.apply, self);\n};\n\nvar baseFields = [\n new FieldDesc(\"doc\", {\n init: function init(config) { return config.doc || config.schema.topNodeType.createAndFill() },\n apply: function apply(tr) { return tr.doc }\n }),\n\n new FieldDesc(\"selection\", {\n init: function init(config, instance) { return config.selection || Selection.atStart(instance.doc) },\n apply: function apply(tr) { return tr.selection }\n }),\n\n new FieldDesc(\"storedMarks\", {\n init: function init(config) { return config.storedMarks || null },\n apply: function apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null }\n }),\n\n new FieldDesc(\"scrollToSelection\", {\n init: function init() { return 0 },\n apply: function apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev }\n })\n];\n\n// Object wrapping the part of a state object that stays the same\n// across transactions. Stored in the state's `config` property.\nvar Configuration = function Configuration(schema, plugins) {\n var this$1 = this;\n\n this.schema = schema;\n this.fields = baseFields.concat();\n this.plugins = [];\n this.pluginsByKey = Object.create(null);\n if (plugins) { plugins.forEach(function (plugin) {\n if (this$1.pluginsByKey[plugin.key])\n { throw new RangeError(\"Adding different instances of a keyed plugin (\" + plugin.key + \")\") }\n this$1.plugins.push(plugin);\n this$1.pluginsByKey[plugin.key] = plugin;\n if (plugin.spec.state)\n { this$1.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin)); }\n }); }\n};\n\n// ::- The state of a ProseMirror editor is represented by an object\n// of this type. A state is a persistent data structure—it isn't\n// updated, but rather a new state value is computed from an old one\n// using the [`apply`](#state.EditorState.apply) method.\n//\n// A state holds a number of built-in fields, and plugins can\n// [define](#state.PluginSpec.state) additional fields.\nvar EditorState = function EditorState(config) {\n this.config = config;\n};\n\nvar prototypeAccessors$1 = { schema: { configurable: true },plugins: { configurable: true },tr: { configurable: true } };\n\n// doc:: Node\n// The current document.\n\n// selection:: Selection\n// The selection.\n\n// storedMarks:: ?[Mark]\n// A set of marks to apply to the next input. Will be null when\n// no explicit marks have been set.\n\n// :: Schema\n// The schema of the state's document.\nprototypeAccessors$1.schema.get = function () {\n return this.config.schema\n};\n\n// :: [Plugin]\n// The plugins that are active in this state.\nprototypeAccessors$1.plugins.get = function () {\n return this.config.plugins\n};\n\n// :: (Transaction) → EditorState\n// Apply the given transaction to produce a new state.\nEditorState.prototype.apply = function apply (tr) {\n return this.applyTransaction(tr).state\n};\n\n// : (Transaction) → bool\nEditorState.prototype.filterTransaction = function filterTransaction (tr, ignore) {\n if ( ignore === void 0 ) ignore = -1;\n\n for (var i = 0; i < this.config.plugins.length; i++) { if (i != ignore) {\n var plugin = this.config.plugins[i];\n if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this))\n { return false }\n } }\n return true\n};\n\n// :: (Transaction) → {state: EditorState, transactions: [Transaction]}\n// Verbose variant of [`apply`](#state.EditorState.apply) that\n// returns the precise transactions that were applied (which might\n// be influenced by the [transaction\n// hooks](#state.PluginSpec.filterTransaction) of\n// plugins) along with the new state.\nEditorState.prototype.applyTransaction = function applyTransaction (rootTr) {\n if (!this.filterTransaction(rootTr)) { return {state: this, transactions: []} }\n\n var trs = [rootTr], newState = this.applyInner(rootTr), seen = null;\n // This loop repeatedly gives plugins a chance to respond to\n // transactions as new transactions are added, making sure to only\n // pass the transactions the plugin did not see before.\n for (;;) {\n var haveNew = false;\n for (var i = 0; i < this.config.plugins.length; i++) {\n var plugin = this.config.plugins[i];\n if (plugin.spec.appendTransaction) {\n var n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;\n var tr = n < trs.length &&\n plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);\n if (tr && newState.filterTransaction(tr, i)) {\n tr.setMeta(\"appendedTransaction\", rootTr);\n if (!seen) {\n seen = [];\n for (var j = 0; j < this.config.plugins.length; j++)\n { seen.push(j < i ? {state: newState, n: trs.length} : {state: this, n: 0}); }\n }\n trs.push(tr);\n newState = newState.applyInner(tr);\n haveNew = true;\n }\n if (seen) { seen[i] = {state: newState, n: trs.length}; }\n }\n }\n if (!haveNew) { return {state: newState, transactions: trs} }\n }\n};\n\n// : (Transaction) → EditorState\nEditorState.prototype.applyInner = function applyInner (tr) {\n if (!tr.before.eq(this.doc)) { throw new RangeError(\"Applying a mismatched transaction\") }\n var newInstance = new EditorState(this.config), fields = this.config.fields;\n for (var i = 0; i < fields.length; i++) {\n var field = fields[i];\n newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);\n }\n for (var i$1 = 0; i$1 < applyListeners.length; i$1++) { applyListeners[i$1](this, tr, newInstance); }\n return newInstance\n};\n\n// :: Transaction\n// Start a [transaction](#state.Transaction) from this state.\nprototypeAccessors$1.tr.get = function () { return new Transaction(this) };\n\n// :: (Object) → EditorState\n// Create a new state.\n//\n// config::- Configuration options. Must contain `schema` or `doc` (or both).\n//\n// schema:: ?Schema\n// The schema to use.\n//\n// doc:: ?Node\n// The starting document.\n//\n// selection:: ?Selection\n// A valid selection in the document.\n//\n// storedMarks:: ?[Mark]\n// The initial set of [stored marks](#state.EditorState.storedMarks).\n//\n// plugins:: ?[Plugin]\n// The plugins that should be active in this state.\nEditorState.create = function create (config) {\n var $config = new Configuration(config.schema || config.doc.type.schema, config.plugins);\n var instance = new EditorState($config);\n for (var i = 0; i < $config.fields.length; i++)\n { instance[$config.fields[i].name] = $config.fields[i].init(config, instance); }\n return instance\n};\n\n// :: (Object) → EditorState\n// Create a new state based on this one, but with an adjusted set of\n// active plugins. State fields that exist in both sets of plugins\n// are kept unchanged. Those that no longer exist are dropped, and\n// those that are new are initialized using their\n// [`init`](#state.StateField.init) method, passing in the new\n// configuration object..\n//\n// config::- configuration options\n//\n// schema:: ?Schema\n// New schema to use.\n//\n// plugins:: ?[Plugin]\n// New set of active plugins.\nEditorState.prototype.reconfigure = function reconfigure (config) {\n var $config = new Configuration(config.schema || this.schema, config.plugins);\n var fields = $config.fields, instance = new EditorState($config);\n for (var i = 0; i < fields.length; i++) {\n var name = fields[i].name;\n instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);\n }\n return instance\n};\n\n// :: (?union, string, number>) → Object\n// Serialize this state to JSON. If you want to serialize the state\n// of plugins, pass an object mapping property names to use in the\n// resulting JSON object to plugin objects. The argument may also be\n// a string or number, in which case it is ignored, to support the\n// way `JSON.stringify` calls `toString` methods.\nEditorState.prototype.toJSON = function toJSON (pluginFields) {\n var result = {doc: this.doc.toJSON(), selection: this.selection.toJSON()};\n if (this.storedMarks) { result.storedMarks = this.storedMarks.map(function (m) { return m.toJSON(); }); }\n if (pluginFields && typeof pluginFields == 'object') { for (var prop in pluginFields) {\n if (prop == \"doc\" || prop == \"selection\")\n { throw new RangeError(\"The JSON fields `doc` and `selection` are reserved\") }\n var plugin = pluginFields[prop], state = plugin.spec.state;\n if (state && state.toJSON) { result[prop] = state.toJSON.call(plugin, this[plugin.key]); }\n } }\n return result\n};\n\n// :: (Object, Object, ?Object) → EditorState\n// Deserialize a JSON representation of a state. `config` should\n// have at least a `schema` field, and should contain array of\n// plugins to initialize the state with. `pluginFields` can be used\n// to deserialize the state of plugins, by associating plugin\n// instances with the property names they use in the JSON object.\n//\n// config::- configuration options\n//\n// schema:: Schema\n// The schema to use.\n//\n// plugins:: ?[Plugin]\n// The set of active plugins.\nEditorState.fromJSON = function fromJSON (config, json, pluginFields) {\n if (!json) { throw new RangeError(\"Invalid input for EditorState.fromJSON\") }\n if (!config.schema) { throw new RangeError(\"Required config field 'schema' missing\") }\n var $config = new Configuration(config.schema, config.plugins);\n var instance = new EditorState($config);\n $config.fields.forEach(function (field) {\n if (field.name == \"doc\") {\n instance.doc = Node.fromJSON(config.schema, json.doc);\n } else if (field.name == \"selection\") {\n instance.selection = Selection.fromJSON(instance.doc, json.selection);\n } else if (field.name == \"storedMarks\") {\n if (json.storedMarks) { instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON); }\n } else {\n if (pluginFields) { for (var prop in pluginFields) {\n var plugin = pluginFields[prop], state = plugin.spec.state;\n if (plugin.key == field.name && state && state.fromJSON &&\n Object.prototype.hasOwnProperty.call(json, prop)) {\n // This field belongs to a plugin mapped to a JSON field, read it from there.\n instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);\n return\n }\n } }\n instance[field.name] = field.init(config, instance);\n }\n });\n return instance\n};\n\n// Kludge to allow the view to track mappings between different\n// instances of a state.\n//\n// FIXME this is no longer needed as of prosemirror-view 1.9.0,\n// though due to backwards-compat we should probably keep it around\n// for a while (if only as a no-op)\nEditorState.addApplyListener = function addApplyListener (f) {\n applyListeners.push(f);\n};\nEditorState.removeApplyListener = function removeApplyListener (f) {\n var found = applyListeners.indexOf(f);\n if (found > -1) { applyListeners.splice(found, 1); }\n};\n\nObject.defineProperties( EditorState.prototype, prototypeAccessors$1 );\n\nvar applyListeners = [];\n\n// PluginSpec:: interface\n//\n// This is the type passed to the [`Plugin`](#state.Plugin)\n// constructor. It provides a definition for a plugin.\n//\n// props:: ?EditorProps\n// The [view props](#view.EditorProps) added by this plugin. Props\n// that are functions will be bound to have the plugin instance as\n// their `this` binding.\n//\n// state:: ?StateField\n// Allows a plugin to define a [state field](#state.StateField), an\n// extra slot in the state object in which it can keep its own data.\n//\n// key:: ?PluginKey\n// Can be used to make this a keyed plugin. You can have only one\n// plugin with a given key in a given state, but it is possible to\n// access the plugin's configuration and state through the key,\n// without having access to the plugin instance object.\n//\n// view:: ?(EditorView) → Object\n// When the plugin needs to interact with the editor view, or\n// set something up in the DOM, use this field. The function\n// will be called when the plugin's state is associated with an\n// editor view.\n//\n// return::-\n// Should return an object with the following optional\n// properties:\n//\n// update:: ?(view: EditorView, prevState: EditorState)\n// Called whenever the view's state is updated.\n//\n// destroy:: ?()\n// Called when the view is destroyed or receives a state\n// with different plugins.\n//\n// filterTransaction:: ?(Transaction, EditorState) → bool\n// When present, this will be called before a transaction is\n// applied by the state, allowing the plugin to cancel it (by\n// returning false).\n//\n// appendTransaction:: ?(transactions: [Transaction], oldState: EditorState, newState: EditorState) → ?Transaction\n// Allows the plugin to append another transaction to be applied\n// after the given array of transactions. When another plugin\n// appends a transaction after this was called, it is called again\n// with the new state and new transactions—but only the new\n// transactions, i.e. it won't be passed transactions that it\n// already saw.\n\nfunction bindProps(obj, self, target) {\n for (var prop in obj) {\n var val = obj[prop];\n if (val instanceof Function) { val = val.bind(self); }\n else if (prop == \"handleDOMEvents\") { val = bindProps(val, self, {}); }\n target[prop] = val;\n }\n return target\n}\n\n// ::- Plugins bundle functionality that can be added to an editor.\n// They are part of the [editor state](#state.EditorState) and\n// may influence that state and the view that contains it.\nvar Plugin = function Plugin(spec) {\n // :: EditorProps\n // The [props](#view.EditorProps) exported by this plugin.\n this.props = {};\n if (spec.props) { bindProps(spec.props, this, this.props); }\n // :: Object\n // The plugin's [spec object](#state.PluginSpec).\n this.spec = spec;\n this.key = spec.key ? spec.key.key : createKey(\"plugin\");\n};\n\n// :: (EditorState) → any\n// Extract the plugin's state field from an editor state.\nPlugin.prototype.getState = function getState (state) { return state[this.key] };\n\n// StateField:: interface\n// A plugin spec may provide a state field (under its\n// [`state`](#state.PluginSpec.state) property) of this type, which\n// describes the state it wants to keep. Functions provided here are\n// always called with the plugin instance as their `this` binding.\n//\n// init:: (config: Object, instance: EditorState) → T\n// Initialize the value of the field. `config` will be the object\n// passed to [`EditorState.create`](#state.EditorState^create). Note\n// that `instance` is a half-initialized state instance, and will\n// not have values for plugin fields initialized after this one.\n//\n// apply:: (tr: Transaction, value: T, oldState: EditorState, newState: EditorState) → T\n// Apply the given transaction to this state field, producing a new\n// field value. Note that the `newState` argument is again a partially\n// constructed state does not yet contain the state from plugins\n// coming after this one.\n//\n// toJSON:: ?(value: T) → *\n// Convert this field to JSON. Optional, can be left off to disable\n// JSON serialization for the field.\n//\n// fromJSON:: ?(config: Object, value: *, state: EditorState) → T\n// Deserialize the JSON representation of this field. Note that the\n// `state` argument is again a half-initialized state.\n\nvar keys = Object.create(null);\n\nfunction createKey(name) {\n if (name in keys) { return name + \"$\" + ++keys[name] }\n keys[name] = 0;\n return name + \"$\"\n}\n\n// ::- A key is used to [tag](#state.PluginSpec.key)\n// plugins in a way that makes it possible to find them, given an\n// editor state. Assigning a key does mean only one plugin of that\n// type can be active in a state.\nvar PluginKey = function PluginKey(name) {\nif ( name === void 0 ) name = \"key\";\n this.key = createKey(name); };\n\n// :: (EditorState) → ?Plugin\n// Get the active plugin with this key, if any, from an editor\n// state.\nPluginKey.prototype.get = function get (state) { return state.config.pluginsByKey[this.key] };\n\n// :: (EditorState) → ?any\n// Get the plugin's state from an editor state.\nPluginKey.prototype.getState = function getState (state) { return state[this.key] };\n\nexport { AllSelection, EditorState, NodeSelection, Plugin, PluginKey, Selection, SelectionRange, TextSelection, Transaction };\n//# sourceMappingURL=index.es.js.map\n","import { TextSelection, NodeSelection, Selection } from 'prosemirror-state';\nimport { DOMSerializer, Fragment, Mark, DOMParser, Slice } from 'prosemirror-model';\nimport { dropPoint } from 'prosemirror-transform';\n\nvar result = {};\n\nif (typeof navigator != \"undefined\" && typeof document != \"undefined\") {\n var ie_edge = /Edge\\/(\\d+)/.exec(navigator.userAgent);\n var ie_upto10 = /MSIE \\d/.test(navigator.userAgent);\n var ie_11up = /Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(navigator.userAgent);\n\n result.mac = /Mac/.test(navigator.platform);\n var ie = result.ie = !!(ie_upto10 || ie_11up || ie_edge);\n result.ie_version = ie_upto10 ? document.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : null;\n result.gecko = !ie && /gecko\\/(\\d+)/i.test(navigator.userAgent);\n result.gecko_version = result.gecko && +(/Firefox\\/(\\d+)/.exec(navigator.userAgent) || [0, 0])[1];\n var chrome = !ie && /Chrome\\/(\\d+)/.exec(navigator.userAgent);\n result.chrome = !!chrome;\n result.chrome_version = chrome && +chrome[1];\n result.ios = !ie && /AppleWebKit/.test(navigator.userAgent) && /Mobile\\/\\w+/.test(navigator.userAgent);\n result.android = /Android \\d/.test(navigator.userAgent);\n result.webkit = \"webkitFontSmoothing\" in document.documentElement.style;\n result.safari = /Apple Computer/.test(navigator.vendor);\n result.webkit_version = result.webkit && +(/\\bAppleWebKit\\/(\\d+)/.exec(navigator.userAgent) || [0, 0])[1];\n}\n\nvar domIndex = function(node) {\n for (var index = 0;; index++) {\n node = node.previousSibling;\n if (!node) { return index }\n }\n};\n\nvar parentNode = function(node) {\n var parent = node.parentNode;\n return parent && parent.nodeType == 11 ? parent.host : parent\n};\n\nvar reusedRange = null;\n\n// Note that this will always return the same range, because DOM range\n// objects are every expensive, and keep slowing down subsequent DOM\n// updates, for some reason.\nvar textRange = function(node, from, to) {\n var range = reusedRange || (reusedRange = document.createRange());\n range.setEnd(node, to == null ? node.nodeValue.length : to);\n range.setStart(node, from || 0);\n return range\n};\n\n// Scans forward and backward through DOM positions equivalent to the\n// given one to see if the two are in the same place (i.e. after a\n// text node vs at the end of that text node)\nvar isEquivalentPosition = function(node, off, targetNode, targetOff) {\n return targetNode && (scanFor(node, off, targetNode, targetOff, -1) ||\n scanFor(node, off, targetNode, targetOff, 1))\n};\n\nvar atomElements = /^(img|br|input|textarea|hr)$/i;\n\nfunction scanFor(node, off, targetNode, targetOff, dir) {\n for (;;) {\n if (node == targetNode && off == targetOff) { return true }\n if (off == (dir < 0 ? 0 : nodeSize(node))) {\n var parent = node.parentNode;\n if (parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == \"false\")\n { return false }\n off = domIndex(node) + (dir < 0 ? 0 : 1);\n node = parent;\n } else if (node.nodeType == 1) {\n node = node.childNodes[off + (dir < 0 ? -1 : 0)];\n if (node.contentEditable == \"false\") { return false }\n off = dir < 0 ? nodeSize(node) : 0;\n } else {\n return false\n }\n }\n}\n\nfunction nodeSize(node) {\n return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length\n}\n\nfunction isOnEdge(node, offset, parent) {\n for (var atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd;) {\n if (node == parent) { return true }\n var index = domIndex(node);\n node = node.parentNode;\n if (!node) { return false }\n atStart = atStart && index == 0;\n atEnd = atEnd && index == nodeSize(node);\n }\n}\n\nfunction hasBlockDesc(dom) {\n var desc;\n for (var cur = dom; cur; cur = cur.parentNode) { if (desc = cur.pmViewDesc) { break } }\n return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom)\n}\n\n// Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523\n// (isCollapsed inappropriately returns true in shadow dom)\nvar selectionCollapsed = function(domSel) {\n var collapsed = domSel.isCollapsed;\n if (collapsed && result.chrome && domSel.rangeCount && !domSel.getRangeAt(0).collapsed)\n { collapsed = false; }\n return collapsed\n};\n\nfunction keyEvent(keyCode, key) {\n var event = document.createEvent(\"Event\");\n event.initEvent(\"keydown\", true, true);\n event.keyCode = keyCode;\n event.key = event.code = key;\n return event\n}\n\nfunction windowRect(doc) {\n return {left: 0, right: doc.documentElement.clientWidth,\n top: 0, bottom: doc.documentElement.clientHeight}\n}\n\nfunction getSide(value, side) {\n return typeof value == \"number\" ? value : value[side]\n}\n\nfunction clientRect(node) {\n var rect = node.getBoundingClientRect();\n // Make sure scrollbar width isn't included in the rectangle\n return {left: rect.left, right: rect.left + node.clientWidth,\n top: rect.top, bottom: rect.top + node.clientHeight}\n}\n\nfunction scrollRectIntoView(view, rect, startDOM) {\n var scrollThreshold = view.someProp(\"scrollThreshold\") || 0, scrollMargin = view.someProp(\"scrollMargin\") || 5;\n var doc = view.dom.ownerDocument;\n for (var parent = startDOM || view.dom;; parent = parentNode(parent)) {\n if (!parent) { break }\n if (parent.nodeType != 1) { continue }\n var atTop = parent == doc.body || parent.nodeType != 1;\n var bounding = atTop ? windowRect(doc) : clientRect(parent);\n var moveX = 0, moveY = 0;\n if (rect.top < bounding.top + getSide(scrollThreshold, \"top\"))\n { moveY = -(bounding.top - rect.top + getSide(scrollMargin, \"top\")); }\n else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, \"bottom\"))\n { moveY = rect.bottom - bounding.bottom + getSide(scrollMargin, \"bottom\"); }\n if (rect.left < bounding.left + getSide(scrollThreshold, \"left\"))\n { moveX = -(bounding.left - rect.left + getSide(scrollMargin, \"left\")); }\n else if (rect.right > bounding.right - getSide(scrollThreshold, \"right\"))\n { moveX = rect.right - bounding.right + getSide(scrollMargin, \"right\"); }\n if (moveX || moveY) {\n if (atTop) {\n doc.defaultView.scrollBy(moveX, moveY);\n } else {\n var startX = parent.scrollLeft, startY = parent.scrollTop;\n if (moveY) { parent.scrollTop += moveY; }\n if (moveX) { parent.scrollLeft += moveX; }\n var dX = parent.scrollLeft - startX, dY = parent.scrollTop - startY;\n rect = {left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY};\n }\n }\n if (atTop) { break }\n }\n}\n\n// Store the scroll position of the editor's parent nodes, along with\n// the top position of an element near the top of the editor, which\n// will be used to make sure the visible viewport remains stable even\n// when the size of the content above changes.\nfunction storeScrollPos(view) {\n var rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top);\n var refDOM, refTop;\n for (var x = (rect.left + rect.right) / 2, y = startY + 1;\n y < Math.min(innerHeight, rect.bottom); y += 5) {\n var dom = view.root.elementFromPoint(x, y);\n if (dom == view.dom || !view.dom.contains(dom)) { continue }\n var localRect = dom.getBoundingClientRect();\n if (localRect.top >= startY - 20) {\n refDOM = dom;\n refTop = localRect.top;\n break\n }\n }\n return {refDOM: refDOM, refTop: refTop, stack: scrollStack(view.dom)}\n}\n\nfunction scrollStack(dom) {\n var stack = [], doc = dom.ownerDocument;\n for (; dom; dom = parentNode(dom)) {\n stack.push({dom: dom, top: dom.scrollTop, left: dom.scrollLeft});\n if (dom == doc) { break }\n }\n return stack\n}\n\n// Reset the scroll position of the editor's parent nodes to that what\n// it was before, when storeScrollPos was called.\nfunction resetScrollPos(ref) {\n var refDOM = ref.refDOM;\n var refTop = ref.refTop;\n var stack = ref.stack;\n\n var newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;\n restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);\n}\n\nfunction restoreScrollStack(stack, dTop) {\n for (var i = 0; i < stack.length; i++) {\n var ref = stack[i];\n var dom = ref.dom;\n var top = ref.top;\n var left = ref.left;\n if (dom.scrollTop != top + dTop) { dom.scrollTop = top + dTop; }\n if (dom.scrollLeft != left) { dom.scrollLeft = left; }\n }\n}\n\nvar preventScrollSupported = null;\n// Feature-detects support for .focus({preventScroll: true}), and uses\n// a fallback kludge when not supported.\nfunction focusPreventScroll(dom) {\n if (dom.setActive) { return dom.setActive() } // in IE\n if (preventScrollSupported) { return dom.focus(preventScrollSupported) }\n\n var stored = scrollStack(dom);\n dom.focus(preventScrollSupported == null ? {\n get preventScroll() {\n preventScrollSupported = {preventScroll: true};\n return true\n }\n } : undefined);\n if (!preventScrollSupported) {\n preventScrollSupported = false;\n restoreScrollStack(stored, 0);\n }\n}\n\nfunction findOffsetInNode(node, coords) {\n var closest, dxClosest = 2e8, coordsClosest, offset = 0;\n var rowBot = coords.top, rowTop = coords.top;\n for (var child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {\n var rects = (void 0);\n if (child.nodeType == 1) { rects = child.getClientRects(); }\n else if (child.nodeType == 3) { rects = textRange(child).getClientRects(); }\n else { continue }\n\n for (var i = 0; i < rects.length; i++) {\n var rect = rects[i];\n if (rect.top <= rowBot && rect.bottom >= rowTop) {\n rowBot = Math.max(rect.bottom, rowBot);\n rowTop = Math.min(rect.top, rowTop);\n var dx = rect.left > coords.left ? rect.left - coords.left\n : rect.right < coords.left ? coords.left - rect.right : 0;\n if (dx < dxClosest) {\n closest = child;\n dxClosest = dx;\n coordsClosest = dx && closest.nodeType == 3 ? {left: rect.right < coords.left ? rect.right : rect.left, top: coords.top} : coords;\n if (child.nodeType == 1 && dx)\n { offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0); }\n continue\n }\n }\n if (!closest && (coords.left >= rect.right && coords.top >= rect.top ||\n coords.left >= rect.left && coords.top >= rect.bottom))\n { offset = childIndex + 1; }\n }\n }\n if (closest && closest.nodeType == 3) { return findOffsetInText(closest, coordsClosest) }\n if (!closest || (dxClosest && closest.nodeType == 1)) { return {node: node, offset: offset} }\n return findOffsetInNode(closest, coordsClosest)\n}\n\nfunction findOffsetInText(node, coords) {\n var len = node.nodeValue.length;\n var range = document.createRange();\n for (var i = 0; i < len; i++) {\n range.setEnd(node, i + 1);\n range.setStart(node, i);\n var rect = singleRect(range, 1);\n if (rect.top == rect.bottom) { continue }\n if (inRect(coords, rect))\n { return {node: node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0)} }\n }\n return {node: node, offset: 0}\n}\n\nfunction inRect(coords, rect) {\n return coords.left >= rect.left - 1 && coords.left <= rect.right + 1&&\n coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1\n}\n\nfunction targetKludge(dom, coords) {\n var parent = dom.parentNode;\n if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left)\n { return parent }\n return dom\n}\n\nfunction posFromElement(view, elt, coords) {\n var ref = findOffsetInNode(elt, coords);\n var node = ref.node;\n var offset = ref.offset;\n var bias = -1;\n if (node.nodeType == 1 && !node.firstChild) {\n var rect = node.getBoundingClientRect();\n bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1;\n }\n return view.docView.posFromDOM(node, offset, bias)\n}\n\nfunction posFromCaret(view, node, offset, coords) {\n // Browser (in caretPosition/RangeFromPoint) will agressively\n // normalize towards nearby inline nodes. Since we are interested in\n // positions between block nodes too, we first walk up the hierarchy\n // of nodes to see if there are block nodes that the coordinates\n // fall outside of. If so, we take the position before/after that\n // block. If not, we call `posFromDOM` on the raw node/offset.\n var outside = -1;\n for (var cur = node;;) {\n if (cur == view.dom) { break }\n var desc = view.docView.nearestDesc(cur, true);\n if (!desc) { return null }\n if (desc.node.isBlock && desc.parent) {\n var rect = desc.dom.getBoundingClientRect();\n if (rect.left > coords.left || rect.top > coords.top) { outside = desc.posBefore; }\n else if (rect.right < coords.left || rect.bottom < coords.top) { outside = desc.posAfter; }\n else { break }\n }\n cur = desc.dom.parentNode;\n }\n return outside > -1 ? outside : view.docView.posFromDOM(node, offset)\n}\n\nfunction elementFromPoint(element, coords, box) {\n var len = element.childNodes.length;\n if (len && box.top < box.bottom) {\n for (var startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI;;) {\n var child = element.childNodes[i];\n if (child.nodeType == 1) {\n var rects = child.getClientRects();\n for (var j = 0; j < rects.length; j++) {\n var rect = rects[j];\n if (inRect(coords, rect)) { return elementFromPoint(child, coords, rect) }\n }\n }\n if ((i = (i + 1) % len) == startI) { break }\n }\n }\n return element\n}\n\n// Given an x,y position on the editor, get the position in the document.\nfunction posAtCoords(view, coords) {\n var assign, assign$1;\n\n var root = view.root, node, offset;\n if (root.caretPositionFromPoint) {\n try { // Firefox throws for this call in hard-to-predict circumstances (#994)\n var pos$1 = root.caretPositionFromPoint(coords.left, coords.top);\n if (pos$1) { ((assign = pos$1, node = assign.offsetNode, offset = assign.offset)); }\n } catch (_) {}\n }\n if (!node && root.caretRangeFromPoint) {\n var range = root.caretRangeFromPoint(coords.left, coords.top);\n if (range) { ((assign$1 = range, node = assign$1.startContainer, offset = assign$1.startOffset)); }\n }\n\n var elt = root.elementFromPoint(coords.left, coords.top + 1), pos;\n if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) {\n var box = view.dom.getBoundingClientRect();\n if (!inRect(coords, box)) { return null }\n elt = elementFromPoint(view.dom, coords, box);\n if (!elt) { return null }\n }\n // Safari's caretRangeFromPoint returns nonsense when on a draggable element\n if (result.safari && elt.draggable) { node = offset = null; }\n elt = targetKludge(elt, coords);\n if (node) {\n if (result.gecko && node.nodeType == 1) {\n // Firefox will sometimes return offsets into nodes, which\n // have no actual children, from caretPositionFromPoint (#953)\n offset = Math.min(offset, node.childNodes.length);\n // It'll also move the returned position before image nodes,\n // even if those are behind it.\n if (offset < node.childNodes.length) {\n var next = node.childNodes[offset], box$1;\n if (next.nodeName == \"IMG\" && (box$1 = next.getBoundingClientRect()).right <= coords.left &&\n box$1.bottom > coords.top)\n { offset++; }\n }\n }\n // Suspiciously specific kludge to work around caret*FromPoint\n // never returning a position at the end of the document\n if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 &&\n coords.top > node.lastChild.getBoundingClientRect().bottom)\n { pos = view.state.doc.content.size; }\n // Ignore positions directly after a BR, since caret*FromPoint\n // 'round up' positions that would be more accurately placed\n // before the BR node.\n else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != \"BR\")\n { pos = posFromCaret(view, node, offset, coords); }\n }\n if (pos == null) { pos = posFromElement(view, elt, coords); }\n\n var desc = view.docView.nearestDesc(elt, true);\n return {pos: pos, inside: desc ? desc.posAtStart - desc.border : -1}\n}\n\nfunction singleRect(object, bias) {\n var rects = object.getClientRects();\n return !rects.length ? object.getBoundingClientRect() : rects[bias < 0 ? 0 : rects.length - 1]\n}\n\nvar BIDI = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/;\n\n// : (EditorView, number, number) → {left: number, top: number, right: number, bottom: number}\n// Given a position in the document model, get a bounding box of the\n// character at that position, relative to the window.\nfunction coordsAtPos(view, pos, side) {\n var ref = view.docView.domFromPos(pos);\n var node = ref.node;\n var offset = ref.offset;\n var $pos = view.state.doc.resolve(pos), inline = $pos.parent.inlineContent;\n\n // These browsers support querying empty text ranges. Prefer that in\n // bidi context.\n var supportEmptyRange = result.webkit || result.gecko;\n if (node.nodeType == 3 && supportEmptyRange && BIDI.test(node.nodeValue)) {\n var rect = singleRect(textRange(node, offset, offset), side);\n // Firefox returns bad results (the position before the space)\n // when querying a position directly after line-broken\n // whitespace. Detect this situation and and kludge around it\n if (result.gecko && offset && /\\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) {\n var rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1);\n if (rectBefore.top == rect.top) {\n var rectAfter = singleRect(textRange(node, offset, offset + 1), -1);\n if (rectAfter.top != rect.top)\n { return flattenV(rectAfter, rectAfter.left < rectBefore.left) }\n }\n }\n return rect\n }\n\n // Move up the DOM as far as possible when in inline context.\n if (inline) {\n var parent = $pos.depth ? view.docView.domAfterPos($pos.before()) : view.dom;\n while (side < 0 && !offset && node != parent) {\n offset = domIndex(node);\n node = node.parentNode;\n }\n while (side >= 0 && offset == nodeSize(node) && node != parent) {\n offset = domIndex(node) + 1;\n node = node.parentNode;\n }\n }\n\n if (node.nodeType == 3) {\n if (side < 0) { return flattenV(singleRect(textRange(node, offset - 1, offset), 1), false) }\n return flattenV(singleRect(textRange(node, offset, offset + 1), -1), true)\n }\n\n // Return a horizontal line in block context\n if (!inline) {\n if (offset && (side < 0 || offset == nodeSize(node))) {\n var before = node.childNodes[offset - 1];\n if (before.nodeType == 1) { return flattenH(before.getBoundingClientRect(), false) }\n }\n if (offset < nodeSize(node)) {\n var after = node.childNodes[offset];\n if (after.nodeType == 1) { return flattenH(after.getBoundingClientRect(), true) }\n }\n return flattenH(node.getBoundingClientRect(), side >= 0)\n }\n\n // Inline, not in text node (this is not Bidi-safe)\n if (offset && (side < 0 || offset == nodeSize(node))) {\n var before$1 = node.childNodes[offset - 1];\n var target = before$1.nodeType == 3 ? textRange(before$1, nodeSize(before$1) - (supportEmptyRange ? 0 : 1))\n // BR nodes tend to only return the rectangle before them\n : before$1.nodeType == 1 && before$1.nodeName != \"BR\" ? before$1 : null;\n if (target) { return flattenV(singleRect(target, 1), false) }\n }\n if (offset < nodeSize(node)) {\n var after$1 = node.childNodes[offset];\n var target$1 = after$1.nodeType == 3 ? textRange(after$1, 0, (supportEmptyRange ? 0 : 1))\n : after$1.nodeType == 1 ? after$1 : null;\n if (target$1) { return flattenV(singleRect(target$1, -1), true) }\n }\n // All else failed, just try to get a rectangle for the target node\n return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, -side), side >= 0)\n}\n\nfunction flattenV(rect, left) {\n if (rect.width == 0) { return rect }\n var x = left ? rect.left : rect.right;\n return {top: rect.top, bottom: rect.bottom, left: x, right: x}\n}\n\nfunction flattenH(rect, top) {\n if (rect.height == 0) { return rect }\n var y = top ? rect.top : rect.bottom;\n return {top: y, bottom: y, left: rect.left, right: rect.right}\n}\n\nfunction withFlushedState(view, state, f) {\n var viewState = view.state, active = view.root.activeElement;\n if (viewState != state) { view.updateState(state); }\n if (active != view.dom) { view.focus(); }\n try {\n return f()\n } finally {\n if (viewState != state) { view.updateState(viewState); }\n if (active != view.dom && active) { active.focus(); }\n }\n}\n\n// : (EditorView, number, number)\n// Whether vertical position motion in a given direction\n// from a position would leave a text block.\nfunction endOfTextblockVertical(view, state, dir) {\n var sel = state.selection;\n var $pos = dir == \"up\" ? sel.$anchor.min(sel.$head) : sel.$anchor.max(sel.$head);\n return withFlushedState(view, state, function () {\n var ref = view.docView.domFromPos($pos.pos);\n var dom = ref.node;\n for (;;) {\n var nearest = view.docView.nearestDesc(dom, true);\n if (!nearest) { break }\n if (nearest.node.isBlock) { dom = nearest.dom; break }\n dom = nearest.dom.parentNode;\n }\n var coords = coordsAtPos(view, $pos.pos, 1);\n for (var child = dom.firstChild; child; child = child.nextSibling) {\n var boxes = (void 0);\n if (child.nodeType == 1) { boxes = child.getClientRects(); }\n else if (child.nodeType == 3) { boxes = textRange(child, 0, child.nodeValue.length).getClientRects(); }\n else { continue }\n for (var i = 0; i < boxes.length; i++) {\n var box = boxes[i];\n if (box.bottom > box.top && (dir == \"up\" ? box.bottom < coords.top + 1 : box.top > coords.bottom - 1))\n { return false }\n }\n }\n return true\n })\n}\n\nvar maybeRTL = /[\\u0590-\\u08ac]/;\n\nfunction endOfTextblockHorizontal(view, state, dir) {\n var ref = state.selection;\n var $head = ref.$head;\n if (!$head.parent.isTextblock) { return false }\n var offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size;\n var sel = getSelection();\n // If the textblock is all LTR, or the browser doesn't support\n // Selection.modify (Edge), fall back to a primitive approach\n if (!maybeRTL.test($head.parent.textContent) || !sel.modify)\n { return dir == \"left\" || dir == \"backward\" ? atStart : atEnd }\n\n return withFlushedState(view, state, function () {\n // This is a huge hack, but appears to be the best we can\n // currently do: use `Selection.modify` to move the selection by\n // one character, and see if that moves the cursor out of the\n // textblock (or doesn't move it at all, when at the start/end of\n // the document).\n var oldRange = sel.getRangeAt(0), oldNode = sel.focusNode, oldOff = sel.focusOffset;\n var oldBidiLevel = sel.caretBidiLevel; // Only for Firefox\n sel.modify(\"move\", dir, \"character\");\n var parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;\n var result = !parentDOM.contains(sel.focusNode.nodeType == 1 ? sel.focusNode : sel.focusNode.parentNode) ||\n (oldNode == sel.focusNode && oldOff == sel.focusOffset);\n // Restore the previous selection\n sel.removeAllRanges();\n sel.addRange(oldRange);\n if (oldBidiLevel != null) { sel.caretBidiLevel = oldBidiLevel; }\n return result\n })\n}\n\nvar cachedState = null, cachedDir = null, cachedResult = false;\nfunction endOfTextblock(view, state, dir) {\n if (cachedState == state && cachedDir == dir) { return cachedResult }\n cachedState = state; cachedDir = dir;\n return cachedResult = dir == \"up\" || dir == \"down\"\n ? endOfTextblockVertical(view, state, dir)\n : endOfTextblockHorizontal(view, state, dir)\n}\n\n// NodeView:: interface\n//\n// By default, document nodes are rendered using the result of the\n// [`toDOM`](#model.NodeSpec.toDOM) method of their spec, and managed\n// entirely by the editor. For some use cases, such as embedded\n// node-specific editing interfaces, you want more control over\n// the behavior of a node's in-editor representation, and need to\n// [define](#view.EditorProps.nodeViews) a custom node view.\n//\n// Mark views only support `dom` and `contentDOM`, and don't support\n// any of the node view methods.\n//\n// Objects returned as node views must conform to this interface.\n//\n// dom:: ?dom.Node\n// The outer DOM node that represents the document node. When not\n// given, the default strategy is used to create a DOM node.\n//\n// contentDOM:: ?dom.Node\n// The DOM node that should hold the node's content. Only meaningful\n// if the node view also defines a `dom` property and if its node\n// type is not a leaf node type. When this is present, ProseMirror\n// will take care of rendering the node's children into it. When it\n// is not present, the node view itself is responsible for rendering\n// (or deciding not to render) its child nodes.\n//\n// update:: ?(node: Node, decorations: [Decoration]) → bool\n// When given, this will be called when the view is updating itself.\n// It will be given a node (possibly of a different type), and an\n// array of active decorations (which are automatically drawn, and\n// the node view may ignore if it isn't interested in them), and\n// should return true if it was able to update to that node, and\n// false otherwise. If the node view has a `contentDOM` property (or\n// no `dom` property), updating its child nodes will be handled by\n// ProseMirror.\n//\n// selectNode:: ?()\n// Can be used to override the way the node's selected status (as a\n// node selection) is displayed.\n//\n// deselectNode:: ?()\n// When defining a `selectNode` method, you should also provide a\n// `deselectNode` method to remove the effect again.\n//\n// setSelection:: ?(anchor: number, head: number, root: dom.Document)\n// This will be called to handle setting the selection inside the\n// node. The `anchor` and `head` positions are relative to the start\n// of the node. By default, a DOM selection will be created between\n// the DOM positions corresponding to those positions, but if you\n// override it you can do something else.\n//\n// stopEvent:: ?(event: dom.Event) → bool\n// Can be used to prevent the editor view from trying to handle some\n// or all DOM events that bubble up from the node view. Events for\n// which this returns true are not handled by the editor.\n//\n// ignoreMutation:: ?(dom.MutationRecord) → bool\n// Called when a DOM\n// [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)\n// or a selection change happens within the view. When the change is\n// a selection change, the record will have a `type` property of\n// `\"selection\"` (which doesn't occur for native mutation records).\n// Return false if the editor should re-read the selection or\n// re-parse the range around the mutation, true if it can safely be\n// ignored.\n//\n// destroy:: ?()\n// Called when the node view is removed from the editor or the whole\n// editor is destroyed.\n\n// View descriptions are data structures that describe the DOM that is\n// used to represent the editor's content. They are used for:\n//\n// - Incremental redrawing when the document changes\n//\n// - Figuring out what part of the document a given DOM position\n// corresponds to\n//\n// - Wiring in custom implementations of the editing interface for a\n// given node\n//\n// They form a doubly-linked mutable tree, starting at `view.docView`.\n\nvar NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3;\n\n// Superclass for the various kinds of descriptions. Defines their\n// basic structure and shared methods.\nvar ViewDesc = function ViewDesc(parent, children, dom, contentDOM) {\n this.parent = parent;\n this.children = children;\n this.dom = dom;\n // An expando property on the DOM node provides a link back to its\n // description.\n dom.pmViewDesc = this;\n // This is the node that holds the child views. It may be null for\n // descs that don't have children.\n this.contentDOM = contentDOM;\n this.dirty = NOT_DIRTY;\n};\n\nvar prototypeAccessors = { beforePosition: { configurable: true },size: { configurable: true },border: { configurable: true },posBefore: { configurable: true },posAtStart: { configurable: true },posAfter: { configurable: true },posAtEnd: { configurable: true },contentLost: { configurable: true } };\n\n// Used to check whether a given description corresponds to a\n// widget/mark/node.\nViewDesc.prototype.matchesWidget = function matchesWidget () { return false };\nViewDesc.prototype.matchesMark = function matchesMark () { return false };\nViewDesc.prototype.matchesNode = function matchesNode () { return false };\nViewDesc.prototype.matchesHack = function matchesHack () { return false };\n\nprototypeAccessors.beforePosition.get = function () { return false };\n\n// : () → ?ParseRule\n// When parsing in-editor content (in domchange.js), we allow\n// descriptions to determine the parse rules that should be used to\n// parse them.\nViewDesc.prototype.parseRule = function parseRule () { return null };\n\n// : (dom.Event) → bool\n// Used by the editor's event handler to ignore events that come\n// from certain descs.\nViewDesc.prototype.stopEvent = function stopEvent () { return false };\n\n// The size of the content represented by this desc.\nprototypeAccessors.size.get = function () {\n var size = 0;\n for (var i = 0; i < this.children.length; i++) { size += this.children[i].size; }\n return size\n};\n\n// For block nodes, this represents the space taken up by their\n// start/end tokens.\nprototypeAccessors.border.get = function () { return 0 };\n\nViewDesc.prototype.destroy = function destroy () {\n this.parent = null;\n if (this.dom.pmViewDesc == this) { this.dom.pmViewDesc = null; }\n for (var i = 0; i < this.children.length; i++)\n { this.children[i].destroy(); }\n};\n\nViewDesc.prototype.posBeforeChild = function posBeforeChild (child) {\n for (var i = 0, pos = this.posAtStart; i < this.children.length; i++) {\n var cur = this.children[i];\n if (cur == child) { return pos }\n pos += cur.size;\n }\n};\n\nprototypeAccessors.posBefore.get = function () {\n return this.parent.posBeforeChild(this)\n};\n\nprototypeAccessors.posAtStart.get = function () {\n return this.parent ? this.parent.posBeforeChild(this) + this.border : 0\n};\n\nprototypeAccessors.posAfter.get = function () {\n return this.posBefore + this.size\n};\n\nprototypeAccessors.posAtEnd.get = function () {\n return this.posAtStart + this.size - 2 * this.border\n};\n\n// : (dom.Node, number, ?number) → number\nViewDesc.prototype.localPosFromDOM = function localPosFromDOM (dom, offset, bias) {\n // If the DOM position is in the content, use the child desc after\n // it to figure out a position.\n if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) {\n if (bias < 0) {\n var domBefore, desc;\n if (dom == this.contentDOM) {\n domBefore = dom.childNodes[offset - 1];\n } else {\n while (dom.parentNode != this.contentDOM) { dom = dom.parentNode; }\n domBefore = dom.previousSibling;\n }\n while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this)) { domBefore = domBefore.previousSibling; }\n return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart\n } else {\n var domAfter, desc$1;\n if (dom == this.contentDOM) {\n domAfter = dom.childNodes[offset];\n } else {\n while (dom.parentNode != this.contentDOM) { dom = dom.parentNode; }\n domAfter = dom.nextSibling;\n }\n while (domAfter && !((desc$1 = domAfter.pmViewDesc) && desc$1.parent == this)) { domAfter = domAfter.nextSibling; }\n return domAfter ? this.posBeforeChild(desc$1) : this.posAtEnd\n }\n }\n // Otherwise, use various heuristics, falling back on the bias\n // parameter, to determine whether to return the position at the\n // start or at the end of this view desc.\n var atEnd;\n if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {\n atEnd = dom.compareDocumentPosition(this.contentDOM) & 2;\n } else if (this.dom.firstChild) {\n if (offset == 0) { for (var search = dom;; search = search.parentNode) {\n if (search == this.dom) { atEnd = false; break }\n if (search.parentNode.firstChild != search) { break }\n } }\n if (atEnd == null && offset == dom.childNodes.length) { for (var search$1 = dom;; search$1 = search$1.parentNode) {\n if (search$1 == this.dom) { atEnd = true; break }\n if (search$1.parentNode.lastChild != search$1) { break }\n } }\n }\n return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart\n};\n\n// Scan up the dom finding the first desc that is a descendant of\n// this one.\nViewDesc.prototype.nearestDesc = function nearestDesc (dom, onlyNodes) {\n for (var first = true, cur = dom; cur; cur = cur.parentNode) {\n var desc = this.getDesc(cur);\n if (desc && (!onlyNodes || desc.node)) {\n // If dom is outside of this desc's nodeDOM, don't count it.\n if (first && desc.nodeDOM &&\n !(desc.nodeDOM.nodeType == 1 ? desc.nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : desc.nodeDOM == dom))\n { first = false; }\n else\n { return desc }\n }\n }\n};\n\nViewDesc.prototype.getDesc = function getDesc (dom) {\n var desc = dom.pmViewDesc;\n for (var cur = desc; cur; cur = cur.parent) { if (cur == this) { return desc } }\n};\n\nViewDesc.prototype.posFromDOM = function posFromDOM (dom, offset, bias) {\n for (var scan = dom; scan; scan = scan.parentNode) {\n var desc = this.getDesc(scan);\n if (desc) { return desc.localPosFromDOM(dom, offset, bias) }\n }\n return -1\n};\n\n// : (number) → ?NodeViewDesc\n// Find the desc for the node after the given pos, if any. (When a\n// parent node overrode rendering, there might not be one.)\nViewDesc.prototype.descAt = function descAt (pos) {\n for (var i = 0, offset = 0; i < this.children.length; i++) {\n var child = this.children[i], end = offset + child.size;\n if (offset == pos && end != offset) {\n while (!child.border && child.children.length) { child = child.children[0]; }\n return child\n }\n if (pos < end) { return child.descAt(pos - offset - child.border) }\n offset = end;\n }\n};\n\n// : (number) → {node: dom.Node, offset: number}\nViewDesc.prototype.domFromPos = function domFromPos (pos) {\n if (!this.contentDOM) { return {node: this.dom, offset: 0} }\n for (var offset = 0, i = 0;; i++) {\n if (offset == pos) {\n while (i < this.children.length && (this.children[i].beforePosition || this.children[i].dom.parentNode != this.contentDOM)) { i++; }\n return {node: this.contentDOM,\n offset: i == this.children.length ? this.contentDOM.childNodes.length : domIndex(this.children[i].dom)}\n }\n if (i == this.children.length) { throw new Error(\"Invalid position \" + pos) }\n var child = this.children[i], end = offset + child.size;\n if (pos < end) { return child.domFromPos(pos - offset - child.border) }\n offset = end;\n }\n};\n\n// Used to find a DOM range in a single parent for a given changed\n// range.\nViewDesc.prototype.parseRange = function parseRange (from, to, base) {\n if ( base === void 0 ) base = 0;\n\n if (this.children.length == 0)\n { return {node: this.contentDOM, from: from, to: to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length} }\n\n var fromOffset = -1, toOffset = -1;\n for (var offset = base, i = 0;; i++) {\n var child = this.children[i], end = offset + child.size;\n if (fromOffset == -1 && from <= end) {\n var childBase = offset + child.border;\n // FIXME maybe descend mark views to parse a narrower range?\n if (from >= childBase && to <= end - child.border && child.node &&\n child.contentDOM && this.contentDOM.contains(child.contentDOM))\n { return child.parseRange(from, to, childBase) }\n\n from = offset;\n for (var j = i; j > 0; j--) {\n var prev = this.children[j - 1];\n if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {\n fromOffset = domIndex(prev.dom) + 1;\n break\n }\n from -= prev.size;\n }\n if (fromOffset == -1) { fromOffset = 0; }\n }\n if (fromOffset > -1 && (end > to || i == this.children.length - 1)) {\n to = end;\n for (var j$1 = i + 1; j$1 < this.children.length; j$1++) {\n var next = this.children[j$1];\n if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {\n toOffset = domIndex(next.dom);\n break\n }\n to += next.size;\n }\n if (toOffset == -1) { toOffset = this.contentDOM.childNodes.length; }\n break\n }\n offset = end;\n }\n return {node: this.contentDOM, from: from, to: to, fromOffset: fromOffset, toOffset: toOffset}\n};\n\nViewDesc.prototype.emptyChildAt = function emptyChildAt (side) {\n if (this.border || !this.contentDOM || !this.children.length) { return false }\n var child = this.children[side < 0 ? 0 : this.children.length - 1];\n return child.size == 0 || child.emptyChildAt(side)\n};\n\n// : (number) → dom.Node\nViewDesc.prototype.domAfterPos = function domAfterPos (pos) {\n var ref = this.domFromPos(pos);\n var node = ref.node;\n var offset = ref.offset;\n if (node.nodeType != 1 || offset == node.childNodes.length)\n { throw new RangeError(\"No node after pos \" + pos) }\n return node.childNodes[offset]\n};\n\n// : (number, number, dom.Document)\n// View descs are responsible for setting any selection that falls\n// entirely inside of them, so that custom implementations can do\n// custom things with the selection. Note that this falls apart when\n// a selection starts in such a node and ends in another, in which\n// case we just use whatever domFromPos produces as a best effort.\nViewDesc.prototype.setSelection = function setSelection (anchor, head, root, force) {\n // If the selection falls entirely in a child, give it to that child\n var from = Math.min(anchor, head), to = Math.max(anchor, head);\n for (var i = 0, offset = 0; i < this.children.length; i++) {\n var child = this.children[i], end = offset + child.size;\n if (from > offset && to < end)\n { return child.setSelection(anchor - offset - child.border, head - offset - child.border, root, force) }\n offset = end;\n }\n\n var anchorDOM = this.domFromPos(anchor), headDOM = this.domFromPos(head);\n var domSel = root.getSelection();\n\n var brKludge = false;\n // On Firefox, using Selection.collapse to put the cursor after a\n // BR node for some reason doesn't always work (#1073). On Safari,\n // the cursor sometimes inexplicable visually lags behind its\n // reported position in such situations (#1092).\n if ((result.gecko || result.safari) && anchor == head) {\n var prev = anchorDOM.node.childNodes[anchorDOM.offset - 1];\n brKludge = prev && (prev.nodeName == \"BR\" || prev.contentEditable == \"false\");\n }\n\n if (!(force || brKludge && result.safari) &&\n isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset) &&\n isEquivalentPosition(headDOM.node, headDOM.offset, domSel.focusNode, domSel.focusOffset))\n { return }\n\n // Selection.extend can be used to create an 'inverted' selection\n // (one where the focus is before the anchor), but not all\n // browsers support it yet.\n var domSelExtended = false;\n if ((domSel.extend || anchor == head) && !brKludge) {\n domSel.collapse(anchorDOM.node, anchorDOM.offset);\n try {\n if (anchor != head) { domSel.extend(headDOM.node, headDOM.offset); }\n domSelExtended = true;\n } catch (err) {\n // In some cases with Chrome the selection is empty after calling\n // collapse, even when it should be valid. This appears to be a bug, but\n // it is difficult to isolate. If this happens fallback to the old path\n // without using extend.\n if (!(err instanceof DOMException)) { throw err }\n // declare global: DOMException\n }\n }\n if (!domSelExtended) {\n if (anchor > head) { var tmp = anchorDOM; anchorDOM = headDOM; headDOM = tmp; }\n var range = document.createRange();\n range.setEnd(headDOM.node, headDOM.offset);\n range.setStart(anchorDOM.node, anchorDOM.offset);\n domSel.removeAllRanges();\n domSel.addRange(range);\n }\n};\n\n// : (dom.MutationRecord) → bool\nViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) {\n return !this.contentDOM && mutation.type != \"selection\"\n};\n\nprototypeAccessors.contentLost.get = function () {\n return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM)\n};\n\n// Remove a subtree of the element tree that has been touched\n// by a DOM change, so that the next update will redraw it.\nViewDesc.prototype.markDirty = function markDirty (from, to) {\n for (var offset = 0, i = 0; i < this.children.length; i++) {\n var child = this.children[i], end = offset + child.size;\n if (offset == end ? from <= end && to >= offset : from < end && to > offset) {\n var startInside = offset + child.border, endInside = end - child.border;\n if (from >= startInside && to <= endInside) {\n this.dirty = from == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY;\n if (from == startInside && to == endInside &&\n (child.contentLost || child.dom.parentNode != this.contentDOM)) { child.dirty = NODE_DIRTY; }\n else { child.markDirty(from - startInside, to - startInside); }\n return\n } else {\n child.dirty = NODE_DIRTY;\n }\n }\n offset = end;\n }\n this.dirty = CONTENT_DIRTY;\n};\n\nViewDesc.prototype.markParentsDirty = function markParentsDirty () {\n var level = 1;\n for (var node = this.parent; node; node = node.parent, level++) {\n var dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;\n if (node.dirty < dirty) { node.dirty = dirty; }\n }\n};\n\nObject.defineProperties( ViewDesc.prototype, prototypeAccessors );\n\n// Reused array to avoid allocating fresh arrays for things that will\n// stay empty anyway.\nvar nothing = [];\n\n// A widget desc represents a widget decoration, which is a DOM node\n// drawn between the document nodes.\nvar WidgetViewDesc = /*@__PURE__*/(function (ViewDesc) {\n function WidgetViewDesc(parent, widget, view, pos) {\n var self, dom = widget.type.toDOM;\n if (typeof dom == \"function\") { dom = dom(view, function () {\n if (!self) { return pos }\n if (self.parent) { return self.parent.posBeforeChild(self) }\n }); }\n if (!widget.type.spec.raw) {\n if (dom.nodeType != 1) {\n var wrap = document.createElement(\"span\");\n wrap.appendChild(dom);\n dom = wrap;\n }\n dom.contentEditable = false;\n dom.classList.add(\"ProseMirror-widget\");\n }\n ViewDesc.call(this, parent, nothing, dom, null);\n this.widget = widget;\n self = this;\n }\n\n if ( ViewDesc ) WidgetViewDesc.__proto__ = ViewDesc;\n WidgetViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype );\n WidgetViewDesc.prototype.constructor = WidgetViewDesc;\n\n var prototypeAccessors$1 = { beforePosition: { configurable: true } };\n\n prototypeAccessors$1.beforePosition.get = function () {\n return this.widget.type.side < 0\n };\n\n WidgetViewDesc.prototype.matchesWidget = function matchesWidget (widget) {\n return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type)\n };\n\n WidgetViewDesc.prototype.parseRule = function parseRule () { return {ignore: true} };\n\n WidgetViewDesc.prototype.stopEvent = function stopEvent (event) {\n var stop = this.widget.spec.stopEvent;\n return stop ? stop(event) : false\n };\n\n WidgetViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) {\n return mutation.type != \"selection\" || this.widget.spec.ignoreSelection\n };\n\n Object.defineProperties( WidgetViewDesc.prototype, prototypeAccessors$1 );\n\n return WidgetViewDesc;\n}(ViewDesc));\n\nvar CompositionViewDesc = /*@__PURE__*/(function (ViewDesc) {\n function CompositionViewDesc(parent, dom, textDOM, text) {\n ViewDesc.call(this, parent, nothing, dom, null);\n this.textDOM = textDOM;\n this.text = text;\n }\n\n if ( ViewDesc ) CompositionViewDesc.__proto__ = ViewDesc;\n CompositionViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype );\n CompositionViewDesc.prototype.constructor = CompositionViewDesc;\n\n var prototypeAccessors$2 = { size: { configurable: true } };\n\n prototypeAccessors$2.size.get = function () { return this.text.length };\n\n CompositionViewDesc.prototype.localPosFromDOM = function localPosFromDOM (dom, offset) {\n if (dom != this.textDOM) { return this.posAtStart + (offset ? this.size : 0) }\n return this.posAtStart + offset\n };\n\n CompositionViewDesc.prototype.domFromPos = function domFromPos (pos) {\n return {node: this.textDOM, offset: pos}\n };\n\n CompositionViewDesc.prototype.ignoreMutation = function ignoreMutation (mut) {\n return mut.type === 'characterData' && mut.target.nodeValue == mut.oldValue\n };\n\n Object.defineProperties( CompositionViewDesc.prototype, prototypeAccessors$2 );\n\n return CompositionViewDesc;\n}(ViewDesc));\n\n// A mark desc represents a mark. May have multiple children,\n// depending on how the mark is split. Note that marks are drawn using\n// a fixed nesting order, for simplicity and predictability, so in\n// some cases they will be split more often than would appear\n// necessary.\nvar MarkViewDesc = /*@__PURE__*/(function (ViewDesc) {\n function MarkViewDesc(parent, mark, dom, contentDOM) {\n ViewDesc.call(this, parent, [], dom, contentDOM);\n this.mark = mark;\n }\n\n if ( ViewDesc ) MarkViewDesc.__proto__ = ViewDesc;\n MarkViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype );\n MarkViewDesc.prototype.constructor = MarkViewDesc;\n\n MarkViewDesc.create = function create (parent, mark, inline, view) {\n var custom = view.nodeViews[mark.type.name];\n var spec = custom && custom(mark, view, inline);\n if (!spec || !spec.dom)\n { spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline)); }\n return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom)\n };\n\n MarkViewDesc.prototype.parseRule = function parseRule () { return {mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM} };\n\n MarkViewDesc.prototype.matchesMark = function matchesMark (mark) { return this.dirty != NODE_DIRTY && this.mark.eq(mark) };\n\n MarkViewDesc.prototype.markDirty = function markDirty (from, to) {\n ViewDesc.prototype.markDirty.call(this, from, to);\n // Move dirty info to nearest node view\n if (this.dirty != NOT_DIRTY) {\n var parent = this.parent;\n while (!parent.node) { parent = parent.parent; }\n if (parent.dirty < this.dirty) { parent.dirty = this.dirty; }\n this.dirty = NOT_DIRTY;\n }\n };\n\n MarkViewDesc.prototype.slice = function slice (from, to, view) {\n var copy = MarkViewDesc.create(this.parent, this.mark, true, view);\n var nodes = this.children, size = this.size;\n if (to < size) { nodes = replaceNodes(nodes, to, size, view); }\n if (from > 0) { nodes = replaceNodes(nodes, 0, from, view); }\n for (var i = 0; i < nodes.length; i++) { nodes[i].parent = copy; }\n copy.children = nodes;\n return copy\n };\n\n return MarkViewDesc;\n}(ViewDesc));\n\n// Node view descs are the main, most common type of view desc, and\n// correspond to an actual node in the document. Unlike mark descs,\n// they populate their child array themselves.\nvar NodeViewDesc = /*@__PURE__*/(function (ViewDesc) {\n function NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) {\n ViewDesc.call(this, parent, node.isLeaf ? nothing : [], dom, contentDOM);\n this.nodeDOM = nodeDOM;\n this.node = node;\n this.outerDeco = outerDeco;\n this.innerDeco = innerDeco;\n if (contentDOM) { this.updateChildren(view, pos); }\n }\n\n if ( ViewDesc ) NodeViewDesc.__proto__ = ViewDesc;\n NodeViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype );\n NodeViewDesc.prototype.constructor = NodeViewDesc;\n\n var prototypeAccessors$3 = { size: { configurable: true },border: { configurable: true } };\n\n // By default, a node is rendered using the `toDOM` method from the\n // node type spec. But client code can use the `nodeViews` spec to\n // supply a custom node view, which can influence various aspects of\n // the way the node works.\n //\n // (Using subclassing for this was intentionally decided against,\n // since it'd require exposing a whole slew of finnicky\n // implementation details to the user code that they probably will\n // never need.)\n NodeViewDesc.create = function create (parent, node, outerDeco, innerDeco, view, pos) {\n var assign;\n\n var custom = view.nodeViews[node.type.name], descObj;\n var spec = custom && custom(node, view, function () {\n // (This is a function that allows the custom view to find its\n // own position)\n if (!descObj) { return pos }\n if (descObj.parent) { return descObj.parent.posBeforeChild(descObj) }\n }, outerDeco);\n\n var dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;\n if (node.isText) {\n if (!dom) { dom = document.createTextNode(node.text); }\n else if (dom.nodeType != 3) { throw new RangeError(\"Text must be rendered as a DOM text node\") }\n } else if (!dom) {\n((assign = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node)), dom = assign.dom, contentDOM = assign.contentDOM));\n }\n if (!contentDOM && !node.isText && dom.nodeName != \"BR\") { // Chrome gets confused by
\n if (!dom.hasAttribute(\"contenteditable\")) { dom.contentEditable = false; }\n if (node.type.spec.draggable) { dom.draggable = true; }\n }\n\n var nodeDOM = dom;\n dom = applyOuterDeco(dom, outerDeco, node);\n\n if (spec)\n { return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM,\n spec, view, pos + 1) }\n else if (node.isText)\n { return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) }\n else\n { return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos + 1) }\n };\n\n NodeViewDesc.prototype.parseRule = function parseRule () {\n var this$1 = this;\n\n // Experimental kludge to allow opt-in re-parsing of nodes\n if (this.node.type.spec.reparseInView) { return null }\n // FIXME the assumption that this can always return the current\n // attrs means that if the user somehow manages to change the\n // attrs in the dom, that won't be picked up. Not entirely sure\n // whether this is a problem\n var rule = {node: this.node.type.name, attrs: this.node.attrs};\n if (this.node.type.spec.code) { rule.preserveWhitespace = \"full\"; }\n if (this.contentDOM && !this.contentLost) { rule.contentElement = this.contentDOM; }\n else { rule.getContent = function () { return this$1.contentDOM ? Fragment.empty : this$1.node.content; }; }\n return rule\n };\n\n NodeViewDesc.prototype.matchesNode = function matchesNode (node, outerDeco, innerDeco) {\n return this.dirty == NOT_DIRTY && node.eq(this.node) &&\n sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco)\n };\n\n prototypeAccessors$3.size.get = function () { return this.node.nodeSize };\n\n prototypeAccessors$3.border.get = function () { return this.node.isLeaf ? 0 : 1 };\n\n // Syncs `this.children` to match `this.node.content` and the local\n // decorations, possibly introducing nesting for marks. Then, in a\n // separate step, syncs the DOM inside `this.contentDOM` to\n // `this.children`.\n NodeViewDesc.prototype.updateChildren = function updateChildren (view, pos) {\n var this$1 = this;\n\n var inline = this.node.inlineContent, off = pos;\n var composition = inline && view.composing && this.localCompositionNode(view, pos);\n var updater = new ViewTreeUpdater(this, composition && composition.node);\n iterDeco(this.node, this.innerDeco, function (widget, i, insideNode) {\n if (widget.spec.marks)\n { updater.syncToMarks(widget.spec.marks, inline, view); }\n else if (widget.type.side >= 0 && !insideNode)\n { updater.syncToMarks(i == this$1.node.childCount ? Mark.none : this$1.node.child(i).marks, inline, view); }\n // If the next node is a desc matching this widget, reuse it,\n // otherwise insert the widget as a new view desc.\n updater.placeWidget(widget, view, off);\n }, function (child, outerDeco, innerDeco, i) {\n // Make sure the wrapping mark descs match the node's marks.\n updater.syncToMarks(child.marks, inline, view);\n // Either find an existing desc that exactly matches this node,\n // and drop the descs before it.\n updater.findNodeMatch(child, outerDeco, innerDeco, i) ||\n // Or try updating the next desc to reflect this node.\n updater.updateNextNode(child, outerDeco, innerDeco, view, i) ||\n // Or just add it as a new desc.\n updater.addNode(child, outerDeco, innerDeco, view, off);\n off += child.nodeSize;\n });\n // Drop all remaining descs after the current position.\n updater.syncToMarks(nothing, inline, view);\n if (this.node.isTextblock) { updater.addTextblockHacks(); }\n updater.destroyRest();\n\n // Sync the DOM if anything changed\n if (updater.changed || this.dirty == CONTENT_DIRTY) {\n // May have to protect focused DOM from being changed if a composition is active\n if (composition) { this.protectLocalComposition(view, composition); }\n renderDescs(this.contentDOM, this.children, view);\n if (result.ios) { iosHacks(this.dom); }\n }\n };\n\n NodeViewDesc.prototype.localCompositionNode = function localCompositionNode (view, pos) {\n // Only do something if both the selection and a focused text node\n // are inside of this node, and the node isn't already part of a\n // view that's a child of this view\n var ref = view.state.selection;\n var from = ref.from;\n var to = ref.to;\n if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size) { return }\n var sel = view.root.getSelection();\n var textNode = nearbyTextNode(sel.focusNode, sel.focusOffset);\n if (!textNode || !this.dom.contains(textNode.parentNode)) { return }\n\n // Find the text in the focused node in the node, stop if it's not\n // there (may have been modified through other means, in which\n // case it should overwritten)\n var text = textNode.nodeValue;\n var textPos = findTextInFragment(this.node.content, text, from - pos, to - pos);\n\n return textPos < 0 ? null : {node: textNode, pos: textPos, text: text}\n };\n\n NodeViewDesc.prototype.protectLocalComposition = function protectLocalComposition (view, ref) {\n var node = ref.node;\n var pos = ref.pos;\n var text = ref.text;\n\n // The node is already part of a local view desc, leave it there\n if (this.getDesc(node)) { return }\n\n // Create a composition view for the orphaned nodes\n var topNode = node;\n for (;; topNode = topNode.parentNode) {\n if (topNode.parentNode == this.contentDOM) { break }\n while (topNode.previousSibling) { topNode.parentNode.removeChild(topNode.previousSibling); }\n while (topNode.nextSibling) { topNode.parentNode.removeChild(topNode.nextSibling); }\n if (topNode.pmViewDesc) { topNode.pmViewDesc = null; }\n }\n var desc = new CompositionViewDesc(this, topNode, node, text);\n view.compositionNodes.push(desc);\n\n // Patch up this.children to contain the composition view\n this.children = replaceNodes(this.children, pos, pos + text.length, view, desc);\n };\n\n // : (Node, [Decoration], DecorationSet, EditorView) → bool\n // If this desc be updated to match the given node decoration,\n // do so and return true.\n NodeViewDesc.prototype.update = function update (node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY ||\n !node.sameMarkup(this.node)) { return false }\n this.updateInner(node, outerDeco, innerDeco, view);\n return true\n };\n\n NodeViewDesc.prototype.updateInner = function updateInner (node, outerDeco, innerDeco, view) {\n this.updateOuterDeco(outerDeco);\n this.node = node;\n this.innerDeco = innerDeco;\n if (this.contentDOM) { this.updateChildren(view, this.posAtStart); }\n this.dirty = NOT_DIRTY;\n };\n\n NodeViewDesc.prototype.updateOuterDeco = function updateOuterDeco (outerDeco) {\n if (sameOuterDeco(outerDeco, this.outerDeco)) { return }\n var needsWrap = this.nodeDOM.nodeType != 1;\n var oldDOM = this.dom;\n this.dom = patchOuterDeco(this.dom, this.nodeDOM,\n computeOuterDeco(this.outerDeco, this.node, needsWrap),\n computeOuterDeco(outerDeco, this.node, needsWrap));\n if (this.dom != oldDOM) {\n oldDOM.pmViewDesc = null;\n this.dom.pmViewDesc = this;\n }\n this.outerDeco = outerDeco;\n };\n\n // Mark this node as being the selected node.\n NodeViewDesc.prototype.selectNode = function selectNode () {\n this.nodeDOM.classList.add(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable) { this.dom.draggable = true; }\n };\n\n // Remove selected node marking from this node.\n NodeViewDesc.prototype.deselectNode = function deselectNode () {\n this.nodeDOM.classList.remove(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable) { this.dom.removeAttribute(\"draggable\"); }\n };\n\n Object.defineProperties( NodeViewDesc.prototype, prototypeAccessors$3 );\n\n return NodeViewDesc;\n}(ViewDesc));\n\n// Create a view desc for the top-level document node, to be exported\n// and used by the view class.\nfunction docViewDesc(doc, outerDeco, innerDeco, dom, view) {\n applyOuterDeco(dom, outerDeco, doc);\n return new NodeViewDesc(null, doc, outerDeco, innerDeco, dom, dom, dom, view, 0)\n}\n\nvar TextViewDesc = /*@__PURE__*/(function (NodeViewDesc) {\n function TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) {\n NodeViewDesc.call(this, parent, node, outerDeco, innerDeco, dom, null, nodeDOM, view);\n }\n\n if ( NodeViewDesc ) TextViewDesc.__proto__ = NodeViewDesc;\n TextViewDesc.prototype = Object.create( NodeViewDesc && NodeViewDesc.prototype );\n TextViewDesc.prototype.constructor = TextViewDesc;\n\n TextViewDesc.prototype.parseRule = function parseRule () {\n var skip = this.nodeDOM.parentNode;\n while (skip && skip != this.dom && !skip.pmIsDeco) { skip = skip.parentNode; }\n return {skip: skip || true}\n };\n\n TextViewDesc.prototype.update = function update (node, outerDeco, _, view) {\n if (this.dirty == NODE_DIRTY || (this.dirty != NOT_DIRTY && !this.inParent()) ||\n !node.sameMarkup(this.node)) { return false }\n this.updateOuterDeco(outerDeco);\n if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {\n this.nodeDOM.nodeValue = node.text;\n if (view.trackWrites == this.nodeDOM) { view.trackWrites = null; }\n }\n this.node = node;\n this.dirty = NOT_DIRTY;\n return true\n };\n\n TextViewDesc.prototype.inParent = function inParent () {\n var parentDOM = this.parent.contentDOM;\n for (var n = this.nodeDOM; n; n = n.parentNode) { if (n == parentDOM) { return true } }\n return false\n };\n\n TextViewDesc.prototype.domFromPos = function domFromPos (pos) {\n return {node: this.nodeDOM, offset: pos}\n };\n\n TextViewDesc.prototype.localPosFromDOM = function localPosFromDOM (dom, offset, bias) {\n if (dom == this.nodeDOM) { return this.posAtStart + Math.min(offset, this.node.text.length) }\n return NodeViewDesc.prototype.localPosFromDOM.call(this, dom, offset, bias)\n };\n\n TextViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) {\n return mutation.type != \"characterData\" && mutation.type != \"selection\"\n };\n\n TextViewDesc.prototype.slice = function slice (from, to, view) {\n var node = this.node.cut(from, to), dom = document.createTextNode(node.text);\n return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view)\n };\n\n return TextViewDesc;\n}(NodeViewDesc));\n\n// A dummy desc used to tag trailing BR or span nodes created to work\n// around contentEditable terribleness.\nvar BRHackViewDesc = /*@__PURE__*/(function (ViewDesc) {\n function BRHackViewDesc () {\n ViewDesc.apply(this, arguments);\n }\n\n if ( ViewDesc ) BRHackViewDesc.__proto__ = ViewDesc;\n BRHackViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype );\n BRHackViewDesc.prototype.constructor = BRHackViewDesc;\n\n BRHackViewDesc.prototype.parseRule = function parseRule () { return {ignore: true} };\n BRHackViewDesc.prototype.matchesHack = function matchesHack () { return this.dirty == NOT_DIRTY };\n\n return BRHackViewDesc;\n}(ViewDesc));\n\n// A separate subclass is used for customized node views, so that the\n// extra checks only have to be made for nodes that are actually\n// customized.\nvar CustomNodeViewDesc = /*@__PURE__*/(function (NodeViewDesc) {\n function CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) {\n NodeViewDesc.call(this, parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos);\n this.spec = spec;\n }\n\n if ( NodeViewDesc ) CustomNodeViewDesc.__proto__ = NodeViewDesc;\n CustomNodeViewDesc.prototype = Object.create( NodeViewDesc && NodeViewDesc.prototype );\n CustomNodeViewDesc.prototype.constructor = CustomNodeViewDesc;\n\n // A custom `update` method gets to decide whether the update goes\n // through. If it does, and there's a `contentDOM` node, our logic\n // updates the children.\n CustomNodeViewDesc.prototype.update = function update (node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY) { return false }\n if (this.spec.update) {\n var result = this.spec.update(node, outerDeco);\n if (result) { this.updateInner(node, outerDeco, innerDeco, view); }\n return result\n } else if (!this.contentDOM && !node.isLeaf) {\n return false\n } else {\n return NodeViewDesc.prototype.update.call(this, node, outerDeco, innerDeco, view)\n }\n };\n\n CustomNodeViewDesc.prototype.selectNode = function selectNode () {\n this.spec.selectNode ? this.spec.selectNode() : NodeViewDesc.prototype.selectNode.call(this);\n };\n\n CustomNodeViewDesc.prototype.deselectNode = function deselectNode () {\n this.spec.deselectNode ? this.spec.deselectNode() : NodeViewDesc.prototype.deselectNode.call(this);\n };\n\n CustomNodeViewDesc.prototype.setSelection = function setSelection (anchor, head, root, force) {\n this.spec.setSelection ? this.spec.setSelection(anchor, head, root)\n : NodeViewDesc.prototype.setSelection.call(this, anchor, head, root, force);\n };\n\n CustomNodeViewDesc.prototype.destroy = function destroy () {\n if (this.spec.destroy) { this.spec.destroy(); }\n NodeViewDesc.prototype.destroy.call(this);\n };\n\n CustomNodeViewDesc.prototype.stopEvent = function stopEvent (event) {\n return this.spec.stopEvent ? this.spec.stopEvent(event) : false\n };\n\n CustomNodeViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) {\n return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : NodeViewDesc.prototype.ignoreMutation.call(this, mutation)\n };\n\n return CustomNodeViewDesc;\n}(NodeViewDesc));\n\n// : (dom.Node, [ViewDesc])\n// Sync the content of the given DOM node with the nodes associated\n// with the given array of view descs, recursing into mark descs\n// because this should sync the subtree for a whole node at a time.\nfunction renderDescs(parentDOM, descs, view) {\n var dom = parentDOM.firstChild, written = false;\n for (var i = 0; i < descs.length; i++) {\n var desc = descs[i], childDOM = desc.dom;\n if (childDOM.parentNode == parentDOM) {\n while (childDOM != dom) { dom = rm(dom); written = true; }\n dom = dom.nextSibling;\n } else {\n written = true;\n parentDOM.insertBefore(childDOM, dom);\n }\n if (desc instanceof MarkViewDesc) {\n var pos = dom ? dom.previousSibling : parentDOM.lastChild;\n renderDescs(desc.contentDOM, desc.children, view);\n dom = pos ? pos.nextSibling : parentDOM.firstChild;\n }\n }\n while (dom) { dom = rm(dom); written = true; }\n if (written && view.trackWrites == parentDOM) { view.trackWrites = null; }\n}\n\nfunction OuterDecoLevel(nodeName) {\n if (nodeName) { this.nodeName = nodeName; }\n}\nOuterDecoLevel.prototype = Object.create(null);\n\nvar noDeco = [new OuterDecoLevel];\n\nfunction computeOuterDeco(outerDeco, node, needsWrap) {\n if (outerDeco.length == 0) { return noDeco }\n\n var top = needsWrap ? noDeco[0] : new OuterDecoLevel, result = [top];\n\n for (var i = 0; i < outerDeco.length; i++) {\n var attrs = outerDeco[i].type.attrs, cur = top;\n if (!attrs) { continue }\n if (attrs.nodeName)\n { result.push(cur = new OuterDecoLevel(attrs.nodeName)); }\n\n for (var name in attrs) {\n var val = attrs[name];\n if (val == null) { continue }\n if (needsWrap && result.length == 1)\n { result.push(cur = top = new OuterDecoLevel(node.isInline ? \"span\" : \"div\")); }\n if (name == \"class\") { cur.class = (cur.class ? cur.class + \" \" : \"\") + val; }\n else if (name == \"style\") { cur.style = (cur.style ? cur.style + \";\" : \"\") + val; }\n else if (name != \"nodeName\") { cur[name] = val; }\n }\n }\n\n return result\n}\n\nfunction patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {\n // Shortcut for trivial case\n if (prevComputed == noDeco && curComputed == noDeco) { return nodeDOM }\n\n var curDOM = nodeDOM;\n for (var i = 0; i < curComputed.length; i++) {\n var deco = curComputed[i], prev = prevComputed[i];\n if (i) {\n var parent = (void 0);\n if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM &&\n (parent = curDOM.parentNode) && parent.tagName.toLowerCase() == deco.nodeName) {\n curDOM = parent;\n } else {\n parent = document.createElement(deco.nodeName);\n parent.pmIsDeco = true;\n parent.appendChild(curDOM);\n prev = noDeco[0];\n curDOM = parent;\n }\n }\n patchAttributes(curDOM, prev || noDeco[0], deco);\n }\n return curDOM\n}\n\nfunction patchAttributes(dom, prev, cur) {\n for (var name in prev)\n { if (name != \"class\" && name != \"style\" && name != \"nodeName\" && !(name in cur))\n { dom.removeAttribute(name); } }\n for (var name$1 in cur)\n { if (name$1 != \"class\" && name$1 != \"style\" && name$1 != \"nodeName\" && cur[name$1] != prev[name$1])\n { dom.setAttribute(name$1, cur[name$1]); } }\n if (prev.class != cur.class) {\n var prevList = prev.class ? prev.class.split(\" \") : nothing;\n var curList = cur.class ? cur.class.split(\" \") : nothing;\n for (var i = 0; i < prevList.length; i++) { if (curList.indexOf(prevList[i]) == -1)\n { dom.classList.remove(prevList[i]); } }\n for (var i$1 = 0; i$1 < curList.length; i$1++) { if (prevList.indexOf(curList[i$1]) == -1)\n { dom.classList.add(curList[i$1]); } }\n }\n if (prev.style != cur.style) {\n if (prev.style) {\n var prop = /\\s*([\\w\\-\\xa1-\\uffff]+)\\s*:(?:\"(?:\\\\.|[^\"])*\"|'(?:\\\\.|[^'])*'|\\(.*?\\)|[^;])*/g, m;\n while (m = prop.exec(prev.style))\n { dom.style.removeProperty(m[1]); }\n }\n if (cur.style)\n { dom.style.cssText += cur.style; }\n }\n}\n\nfunction applyOuterDeco(dom, deco, node) {\n return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1))\n}\n\n// : ([Decoration], [Decoration]) → bool\nfunction sameOuterDeco(a, b) {\n if (a.length != b.length) { return false }\n for (var i = 0; i < a.length; i++) { if (!a[i].type.eq(b[i].type)) { return false } }\n return true\n}\n\n// Remove a DOM node and return its next sibling.\nfunction rm(dom) {\n var next = dom.nextSibling;\n dom.parentNode.removeChild(dom);\n return next\n}\n\n// Helper class for incrementally updating a tree of mark descs and\n// the widget and node descs inside of them.\nvar ViewTreeUpdater = function ViewTreeUpdater(top, lockedNode) {\n this.top = top;\n this.lock = lockedNode;\n // Index into `this.top`'s child array, represents the current\n // update position.\n this.index = 0;\n // When entering a mark, the current top and index are pushed\n // onto this.\n this.stack = [];\n // Tracks whether anything was changed\n this.changed = false;\n\n var pre = preMatch(top.node.content, top.children);\n this.preMatched = pre.nodes;\n this.preMatchOffset = pre.offset;\n};\n\nViewTreeUpdater.prototype.getPreMatch = function getPreMatch (index) {\n return index >= this.preMatchOffset ? this.preMatched[index - this.preMatchOffset] : null\n};\n\n// Destroy and remove the children between the given indices in\n// `this.top`.\nViewTreeUpdater.prototype.destroyBetween = function destroyBetween (start, end) {\n if (start == end) { return }\n for (var i = start; i < end; i++) { this.top.children[i].destroy(); }\n this.top.children.splice(start, end - start);\n this.changed = true;\n};\n\n// Destroy all remaining children in `this.top`.\nViewTreeUpdater.prototype.destroyRest = function destroyRest () {\n this.destroyBetween(this.index, this.top.children.length);\n};\n\n// : ([Mark], EditorView)\n// Sync the current stack of mark descs with the given array of\n// marks, reusing existing mark descs when possible.\nViewTreeUpdater.prototype.syncToMarks = function syncToMarks (marks, inline, view) {\n var keep = 0, depth = this.stack.length >> 1;\n var maxKeep = Math.min(depth, marks.length);\n while (keep < maxKeep &&\n (keep == depth - 1 ? this.top : this.stack[(keep + 1) << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)\n { keep++; }\n\n while (keep < depth) {\n this.destroyRest();\n this.top.dirty = NOT_DIRTY;\n this.index = this.stack.pop();\n this.top = this.stack.pop();\n depth--;\n }\n while (depth < marks.length) {\n this.stack.push(this.top, this.index + 1);\n var found = -1;\n for (var i = this.index; i < Math.min(this.index + 3, this.top.children.length); i++) {\n if (this.top.children[i].matchesMark(marks[depth])) { found = i; break }\n }\n if (found > -1) {\n if (found > this.index) {\n this.changed = true;\n this.destroyBetween(this.index, found);\n }\n this.top = this.top.children[this.index];\n } else {\n var markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view);\n this.top.children.splice(this.index, 0, markDesc);\n this.top = markDesc;\n this.changed = true;\n }\n this.index = 0;\n depth++;\n }\n};\n\n// : (Node, [Decoration], DecorationSet) → bool\n// Try to find a node desc matching the given data. Skip over it and\n// return true when successful.\nViewTreeUpdater.prototype.findNodeMatch = function findNodeMatch (node, outerDeco, innerDeco, index) {\n var found = -1, preMatch = index < 0 ? undefined : this.getPreMatch(index), children = this.top.children;\n if (preMatch && preMatch.matchesNode(node, outerDeco, innerDeco)) {\n found = children.indexOf(preMatch);\n } else {\n for (var i = this.index, e = Math.min(children.length, i + 5); i < e; i++) {\n var child = children[i];\n if (child.matchesNode(node, outerDeco, innerDeco) && this.preMatched.indexOf(child) < 0) {\n found = i;\n break\n }\n }\n }\n if (found < 0) { return false }\n this.destroyBetween(this.index, found);\n this.index++;\n return true\n};\n\n// : (Node, [Decoration], DecorationSet, EditorView, Fragment, number) → bool\n// Try to update the next node, if any, to the given data. Checks\n// pre-matches to avoid overwriting nodes that could still be used.\nViewTreeUpdater.prototype.updateNextNode = function updateNextNode (node, outerDeco, innerDeco, view, index) {\n for (var i = this.index; i < this.top.children.length; i++) {\n var next = this.top.children[i];\n if (next instanceof NodeViewDesc) {\n var preMatch = this.preMatched.indexOf(next);\n if (preMatch > -1 && preMatch + this.preMatchOffset != index) { return false }\n var nextDOM = next.dom;\n\n // Can't update if nextDOM is or contains this.lock, except if\n // it's a text node whose content already matches the new text\n // and whose decorations match the new ones.\n var locked = this.lock && (nextDOM == this.lock || nextDOM.nodeType == 1 && nextDOM.contains(this.lock.parentNode)) &&\n !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text &&\n next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco));\n if (!locked && next.update(node, outerDeco, innerDeco, view)) {\n this.destroyBetween(this.index, i);\n if (next.dom != nextDOM) { this.changed = true; }\n this.index++;\n return true\n }\n break\n }\n }\n return false\n};\n\n// : (Node, [Decoration], DecorationSet, EditorView)\n// Insert the node as a newly created node desc.\nViewTreeUpdater.prototype.addNode = function addNode (node, outerDeco, innerDeco, view, pos) {\n this.top.children.splice(this.index++, 0, NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos));\n this.changed = true;\n};\n\nViewTreeUpdater.prototype.placeWidget = function placeWidget (widget, view, pos) {\n var next = this.index < this.top.children.length ? this.top.children[this.index] : null;\n if (next && next.matchesWidget(widget) && (widget == next.widget || !next.widget.type.toDOM.parentNode)) {\n this.index++;\n } else {\n var desc = new WidgetViewDesc(this.top, widget, view, pos);\n this.top.children.splice(this.index++, 0, desc);\n this.changed = true;\n }\n};\n\n// Make sure a textblock looks and behaves correctly in\n// contentEditable.\nViewTreeUpdater.prototype.addTextblockHacks = function addTextblockHacks () {\n var lastChild = this.top.children[this.index - 1];\n while (lastChild instanceof MarkViewDesc) { lastChild = lastChild.children[lastChild.children.length - 1]; }\n\n if (!lastChild || // Empty textblock\n !(lastChild instanceof TextViewDesc) ||\n /\\n$/.test(lastChild.node.text)) {\n if (this.index < this.top.children.length && this.top.children[this.index].matchesHack()) {\n this.index++;\n } else {\n var dom = document.createElement(\"br\");\n this.top.children.splice(this.index++, 0, new BRHackViewDesc(this.top, nothing, dom, null));\n this.changed = true;\n }\n }\n};\n\n// : (Fragment, [ViewDesc]) → [ViewDesc]\n// Iterate from the end of the fragment and array of descs to find\n// directly matching ones, in order to avoid overeagerly reusing\n// those for other nodes. Returns an array whose positions correspond\n// to node positions in the fragment, and whose elements are either\n// descs matched to the child at that index, or empty.\nfunction preMatch(frag, descs) {\n var result = [], end = frag.childCount;\n for (var i = descs.length - 1; end > 0 && i >= 0; i--) {\n var desc = descs[i], node = desc.node;\n if (!node) { continue }\n if (node != frag.child(end - 1)) { break }\n result.push(desc);\n --end;\n }\n return {nodes: result.reverse(), offset: end}\n}\n\nfunction compareSide(a, b) { return a.type.side - b.type.side }\n\n// : (ViewDesc, DecorationSet, (Decoration, number), (Node, [Decoration], DecorationSet, number))\n// This function abstracts iterating over the nodes and decorations in\n// a fragment. Calls `onNode` for each node, with its local and child\n// decorations. Splits text nodes when there is a decoration starting\n// or ending inside of them. Calls `onWidget` for each widget.\nfunction iterDeco(parent, deco, onWidget, onNode) {\n var locals = deco.locals(parent), offset = 0;\n // Simple, cheap variant for when there are no local decorations\n if (locals.length == 0) {\n for (var i = 0; i < parent.childCount; i++) {\n var child = parent.child(i);\n onNode(child, locals, deco.forChild(offset, child), i);\n offset += child.nodeSize;\n }\n return\n }\n\n var decoIndex = 0, active = [], restNode = null;\n for (var parentIndex = 0;;) {\n if (decoIndex < locals.length && locals[decoIndex].to == offset) {\n var widget = locals[decoIndex++], widgets = (void 0);\n while (decoIndex < locals.length && locals[decoIndex].to == offset)\n { (widgets || (widgets = [widget])).push(locals[decoIndex++]); }\n if (widgets) {\n widgets.sort(compareSide);\n for (var i$1 = 0; i$1 < widgets.length; i$1++) { onWidget(widgets[i$1], parentIndex, !!restNode); }\n } else {\n onWidget(widget, parentIndex, !!restNode);\n }\n }\n\n var child$1 = (void 0), index = (void 0);\n if (restNode) {\n index = -1;\n child$1 = restNode;\n restNode = null;\n } else if (parentIndex < parent.childCount) {\n index = parentIndex;\n child$1 = parent.child(parentIndex++);\n } else {\n break\n }\n\n for (var i$2 = 0; i$2 < active.length; i$2++) { if (active[i$2].to <= offset) { active.splice(i$2--, 1); } }\n while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)\n { active.push(locals[decoIndex++]); }\n\n var end = offset + child$1.nodeSize;\n if (child$1.isText) {\n var cutAt = end;\n if (decoIndex < locals.length && locals[decoIndex].from < cutAt) { cutAt = locals[decoIndex].from; }\n for (var i$3 = 0; i$3 < active.length; i$3++) { if (active[i$3].to < cutAt) { cutAt = active[i$3].to; } }\n if (cutAt < end) {\n restNode = child$1.cut(cutAt - offset);\n child$1 = child$1.cut(0, cutAt - offset);\n end = cutAt;\n index = -1;\n }\n }\n\n var outerDeco = !active.length ? nothing\n : child$1.isInline && !child$1.isLeaf ? active.filter(function (d) { return !d.inline; })\n : active.slice();\n onNode(child$1, outerDeco, deco.forChild(offset, child$1), index);\n offset = end;\n }\n}\n\n// List markers in Mobile Safari will mysteriously disappear\n// sometimes. This works around that.\nfunction iosHacks(dom) {\n if (dom.nodeName == \"UL\" || dom.nodeName == \"OL\") {\n var oldCSS = dom.style.cssText;\n dom.style.cssText = oldCSS + \"; list-style: square !important\";\n window.getComputedStyle(dom).listStyle;\n dom.style.cssText = oldCSS;\n }\n}\n\nfunction nearbyTextNode(node, offset) {\n for (;;) {\n if (node.nodeType == 3) { return node }\n if (node.nodeType == 1 && offset > 0) {\n if (node.childNodes.length > offset && node.childNodes[offset].nodeType == 3)\n { return node.childNodes[offset] }\n node = node.childNodes[offset - 1];\n offset = nodeSize(node);\n } else if (node.nodeType == 1 && offset < node.childNodes.length) {\n node = node.childNodes[offset];\n offset = 0;\n } else {\n return null\n }\n }\n}\n\n// Find a piece of text in an inline fragment, overlapping from-to\nfunction findTextInFragment(frag, text, from, to) {\n for (var i = 0, pos = 0; i < frag.childCount && pos <= to;) {\n var child = frag.child(i++), childStart = pos;\n pos += child.nodeSize;\n if (!child.isText) { continue }\n var str = child.text;\n while (i < frag.childCount) {\n var next = frag.child(i++);\n pos += next.nodeSize;\n if (!next.isText) { break }\n str += next.text;\n }\n if (pos >= from) {\n var found = str.lastIndexOf(text, to - childStart);\n if (found >= 0 && found + text.length + childStart >= from)\n { return childStart + found }\n }\n }\n return -1\n}\n\n// Replace range from-to in an array of view descs with replacement\n// (may be null to just delete). This goes very much against the grain\n// of the rest of this code, which tends to create nodes with the\n// right shape in one go, rather than messing with them after\n// creation, but is necessary in the composition hack.\nfunction replaceNodes(nodes, from, to, view, replacement) {\n var result = [];\n for (var i = 0, off = 0; i < nodes.length; i++) {\n var child = nodes[i], start = off, end = off += child.size;\n if (start >= to || end <= from) {\n result.push(child);\n } else {\n if (start < from) { result.push(child.slice(0, from - start, view)); }\n if (replacement) {\n result.push(replacement);\n replacement = null;\n }\n if (end > to) { result.push(child.slice(to - start, child.size, view)); }\n }\n }\n return result\n}\n\nfunction selectionFromDOM(view, origin) {\n var domSel = view.root.getSelection(), doc = view.state.doc;\n if (!domSel.focusNode) { return null }\n var nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;\n var head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);\n if (head < 0) { return null }\n var $head = doc.resolve(head), $anchor, selection;\n if (selectionCollapsed(domSel)) {\n $anchor = $head;\n while (nearestDesc && !nearestDesc.node) { nearestDesc = nearestDesc.parent; }\n if (nearestDesc && nearestDesc.node.isAtom && NodeSelection.isSelectable(nearestDesc.node) && nearestDesc.parent\n && !(nearestDesc.node.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {\n var pos = nearestDesc.posBefore;\n selection = new NodeSelection(head == pos ? $head : doc.resolve(pos));\n }\n } else {\n var anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);\n if (anchor < 0) { return null }\n $anchor = doc.resolve(anchor);\n }\n\n if (!selection) {\n var bias = origin == \"pointer\" || (view.state.selection.head < $head.pos && !inWidget) ? 1 : -1;\n selection = selectionBetween(view, $anchor, $head, bias);\n }\n return selection\n}\n\nfunction selectionToDOM(view, force) {\n var sel = view.state.selection;\n syncNodeSelection(view, sel);\n\n if (view.editable ? !view.hasFocus() :\n !(hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom))) { return }\n\n view.domObserver.disconnectSelection();\n\n if (view.cursorWrapper) {\n selectCursorWrapper(view);\n } else {\n var anchor = sel.anchor;\n var head = sel.head;\n var resetEditableFrom, resetEditableTo;\n if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) {\n if (!sel.$from.parent.inlineContent)\n { resetEditableFrom = temporarilyEditableNear(view, sel.from); }\n if (!sel.empty && !sel.$from.parent.inlineContent)\n { resetEditableTo = temporarilyEditableNear(view, sel.to); }\n }\n view.docView.setSelection(anchor, head, view.root, force);\n if (brokenSelectBetweenUneditable) {\n if (resetEditableFrom) { resetEditable(resetEditableFrom); }\n if (resetEditableTo) { resetEditable(resetEditableTo); }\n }\n if (sel.visible) {\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n } else {\n view.dom.classList.add(\"ProseMirror-hideselection\");\n if (\"onselectionchange\" in document) { removeClassOnSelectionChange(view); }\n }\n }\n\n view.domObserver.setCurSelection();\n view.domObserver.connectSelection();\n}\n\n// Kludge to work around Webkit not allowing a selection to start/end\n// between non-editable block nodes. We briefly make something\n// editable, set the selection, then set it uneditable again.\n\nvar brokenSelectBetweenUneditable = result.safari || result.chrome && result.chrome_version < 63;\n\nfunction temporarilyEditableNear(view, pos) {\n var ref = view.docView.domFromPos(pos);\n var node = ref.node;\n var offset = ref.offset;\n var after = offset < node.childNodes.length ? node.childNodes[offset] : null;\n var before = offset ? node.childNodes[offset - 1] : null;\n if (result.safari && after && after.contentEditable == \"false\") { return setEditable(after) }\n if ((!after || after.contentEditable == \"false\") && (!before || before.contentEditable == \"false\")) {\n if (after) { return setEditable(after) }\n else if (before) { return setEditable(before) }\n }\n}\n\nfunction setEditable(element) {\n element.contentEditable = \"true\";\n if (result.safari && element.draggable) { element.draggable = false; element.wasDraggable = true; }\n return element\n}\n\nfunction resetEditable(element) {\n element.contentEditable = \"false\";\n if (element.wasDraggable) { element.draggable = true; element.wasDraggable = null; }\n}\n\nfunction removeClassOnSelectionChange(view) {\n var doc = view.dom.ownerDocument;\n doc.removeEventListener(\"selectionchange\", view.hideSelectionGuard);\n var domSel = view.root.getSelection();\n var node = domSel.anchorNode, offset = domSel.anchorOffset;\n doc.addEventListener(\"selectionchange\", view.hideSelectionGuard = function () {\n if (domSel.anchorNode != node || domSel.anchorOffset != offset) {\n doc.removeEventListener(\"selectionchange\", view.hideSelectionGuard);\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n }\n });\n}\n\nfunction selectCursorWrapper(view) {\n var domSel = view.root.getSelection(), range = document.createRange();\n var node = view.cursorWrapper.dom, img = node.nodeName == \"IMG\";\n if (img) { range.setEnd(node.parentNode, domIndex(node) + 1); }\n else { range.setEnd(node, 0); }\n range.collapse(false);\n domSel.removeAllRanges();\n domSel.addRange(range);\n // Kludge to kill 'control selection' in IE11 when selecting an\n // invisible cursor wrapper, since that would result in those weird\n // resize handles and a selection that considers the absolutely\n // positioned wrapper, rather than the root editable node, the\n // focused element.\n if (!img && !view.state.selection.visible && result.ie && result.ie_version <= 11) {\n node.disabled = true;\n node.disabled = false;\n }\n}\n\nfunction syncNodeSelection(view, sel) {\n if (sel instanceof NodeSelection) {\n var desc = view.docView.descAt(sel.from);\n if (desc != view.lastSelectedViewDesc) {\n clearNodeSelection(view);\n if (desc) { desc.selectNode(); }\n view.lastSelectedViewDesc = desc;\n }\n } else {\n clearNodeSelection(view);\n }\n}\n\n// Clear all DOM statefulness of the last node selection.\nfunction clearNodeSelection(view) {\n if (view.lastSelectedViewDesc) {\n if (view.lastSelectedViewDesc.parent)\n { view.lastSelectedViewDesc.deselectNode(); }\n view.lastSelectedViewDesc = null;\n }\n}\n\nfunction selectionBetween(view, $anchor, $head, bias) {\n return view.someProp(\"createSelectionBetween\", function (f) { return f(view, $anchor, $head); })\n || TextSelection.between($anchor, $head, bias)\n}\n\nfunction hasFocusAndSelection(view) {\n if (view.editable && view.root.activeElement != view.dom) { return false }\n return hasSelection(view)\n}\n\nfunction hasSelection(view) {\n var sel = view.root.getSelection();\n if (!sel.anchorNode) { return false }\n try {\n // Firefox will raise 'permission denied' errors when accessing\n // properties of `sel.anchorNode` when it's in a generated CSS\n // element.\n return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) &&\n (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode))\n } catch(_) {\n return false\n }\n}\n\nfunction anchorInRightPlace(view) {\n var anchorDOM = view.docView.domFromPos(view.state.selection.anchor);\n var domSel = view.root.getSelection();\n return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset)\n}\n\nfunction moveSelectionBlock(state, dir) {\n var ref = state.selection;\n var $anchor = ref.$anchor;\n var $head = ref.$head;\n var $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);\n var $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;\n return $start && Selection.findFrom($start, dir)\n}\n\nfunction apply(view, sel) {\n view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());\n return true\n}\n\nfunction selectHorizontally(view, dir, mods) {\n var sel = view.state.selection;\n if (sel instanceof TextSelection) {\n if (!sel.empty || mods.indexOf(\"s\") > -1) {\n return false\n } else if (view.endOfTextblock(dir > 0 ? \"right\" : \"left\")) {\n var next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection)) { return apply(view, next) }\n return false\n } else if (!(result.mac && mods.indexOf(\"m\") > -1)) {\n var $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;\n if (!node || node.isText) { return false }\n var nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos;\n if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM)) { return false }\n if (NodeSelection.isSelectable(node)) {\n return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head))\n } else if (result.webkit) {\n // Chrome and Safari will introduce extra pointless cursor\n // positions around inline uneditable nodes, so we have to\n // take over and move the cursor past them (#937)\n return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize)))\n } else {\n return false\n }\n }\n } else if (sel instanceof NodeSelection && sel.node.isInline) {\n return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from))\n } else {\n var next$1 = moveSelectionBlock(view.state, dir);\n if (next$1) { return apply(view, next$1) }\n return false\n }\n}\n\nfunction nodeLen(node) {\n return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length\n}\n\nfunction isIgnorable(dom) {\n var desc = dom.pmViewDesc;\n return desc && desc.size == 0 && (dom.nextSibling || dom.nodeName != \"BR\")\n}\n\n// Make sure the cursor isn't directly after one or more ignored\n// nodes, which will confuse the browser's cursor motion logic.\nfunction skipIgnoredNodesLeft(view) {\n var sel = view.root.getSelection();\n var node = sel.focusNode, offset = sel.focusOffset;\n if (!node) { return }\n var moveNode, moveOffset, force = false;\n // Gecko will do odd things when the selection is directly in front\n // of a non-editable node, so in that case, move it into the next\n // node if possible. Issue prosemirror/prosemirror#832.\n if (result.gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset])) { force = true; }\n for (;;) {\n if (offset > 0) {\n if (node.nodeType != 1) {\n break\n } else {\n var before = node.childNodes[offset - 1];\n if (isIgnorable(before)) {\n moveNode = node;\n moveOffset = --offset;\n } else if (before.nodeType == 3) {\n node = before;\n offset = node.nodeValue.length;\n } else { break }\n }\n } else if (isBlockNode(node)) {\n break\n } else {\n var prev = node.previousSibling;\n while (prev && isIgnorable(prev)) {\n moveNode = node.parentNode;\n moveOffset = domIndex(prev);\n prev = prev.previousSibling;\n }\n if (!prev) {\n node = node.parentNode;\n if (node == view.dom) { break }\n offset = 0;\n } else {\n node = prev;\n offset = nodeLen(node);\n }\n }\n }\n if (force) { setSelFocus(view, sel, node, offset); }\n else if (moveNode) { setSelFocus(view, sel, moveNode, moveOffset); }\n}\n\n// Make sure the cursor isn't directly before one or more ignored\n// nodes.\nfunction skipIgnoredNodesRight(view) {\n var sel = view.root.getSelection();\n var node = sel.focusNode, offset = sel.focusOffset;\n if (!node) { return }\n var len = nodeLen(node);\n var moveNode, moveOffset;\n for (;;) {\n if (offset < len) {\n if (node.nodeType != 1) { break }\n var after = node.childNodes[offset];\n if (isIgnorable(after)) {\n moveNode = node;\n moveOffset = ++offset;\n }\n else { break }\n } else if (isBlockNode(node)) {\n break\n } else {\n var next = node.nextSibling;\n while (next && isIgnorable(next)) {\n moveNode = next.parentNode;\n moveOffset = domIndex(next) + 1;\n next = next.nextSibling;\n }\n if (!next) {\n node = node.parentNode;\n if (node == view.dom) { break }\n offset = len = 0;\n } else {\n node = next;\n offset = 0;\n len = nodeLen(node);\n }\n }\n }\n if (moveNode) { setSelFocus(view, sel, moveNode, moveOffset); }\n}\n\nfunction isBlockNode(dom) {\n var desc = dom.pmViewDesc;\n return desc && desc.node && desc.node.isBlock\n}\n\nfunction setSelFocus(view, sel, node, offset) {\n if (selectionCollapsed(sel)) {\n var range = document.createRange();\n range.setEnd(node, offset);\n range.setStart(node, offset);\n sel.removeAllRanges();\n sel.addRange(range);\n } else if (sel.extend) {\n sel.extend(node, offset);\n }\n view.domObserver.setCurSelection();\n var state = view.state;\n // If no state update ends up happening, reset the selection.\n setTimeout(function () {\n if (view.state == state) { selectionToDOM(view); }\n }, 50);\n}\n\n// : (EditorState, number)\n// Check whether vertical selection motion would involve node\n// selections. If so, apply it (if not, the result is left to the\n// browser)\nfunction selectVertically(view, dir, mods) {\n var sel = view.state.selection;\n if (sel instanceof TextSelection && !sel.empty || mods.indexOf(\"s\") > -1) { return false }\n if (result.mac && mods.indexOf(\"m\") > -1) { return false }\n var $from = sel.$from;\n var $to = sel.$to;\n\n if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? \"up\" : \"down\")) {\n var next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection))\n { return apply(view, next) }\n }\n if (!$from.parent.inlineContent) {\n var beyond = Selection.findFrom(dir < 0 ? $from : $to, dir);\n return beyond ? apply(view, beyond) : true\n }\n return false\n}\n\nfunction stopNativeHorizontalDelete(view, dir) {\n if (!(view.state.selection instanceof TextSelection)) { return true }\n var ref = view.state.selection;\n var $head = ref.$head;\n var $anchor = ref.$anchor;\n var empty = ref.empty;\n if (!$head.sameParent($anchor)) { return true }\n if (!empty) { return false }\n if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\")) { return true }\n var nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);\n if (nextNode && !nextNode.isText) {\n var tr = view.state.tr;\n if (dir < 0) { tr.delete($head.pos - nextNode.nodeSize, $head.pos); }\n else { tr.delete($head.pos, $head.pos + nextNode.nodeSize); }\n view.dispatch(tr);\n return true\n }\n return false\n}\n\nfunction switchEditable(view, node, state) {\n view.domObserver.stop();\n node.contentEditable = state;\n view.domObserver.start();\n}\n\n// Issue #867 / #1090 / https://bugs.chromium.org/p/chromium/issues/detail?id=903821\n// In which Safari (and at some point in the past, Chrome) does really\n// wrong things when the down arrow is pressed when the cursor is\n// directly at the start of a textblock and has an uneditable node\n// after it\nfunction safariDownArrowBug(view) {\n if (!result.safari || view.state.selection.$head.parentOffset > 0) { return }\n var ref = view.root.getSelection();\n var focusNode = ref.focusNode;\n var focusOffset = ref.focusOffset;\n if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 &&\n focusNode.firstChild && focusNode.firstChild.contentEditable == \"false\") {\n var child = focusNode.firstChild;\n switchEditable(view, child, true);\n setTimeout(function () { return switchEditable(view, child, false); }, 20);\n }\n}\n\n// A backdrop key mapping used to make sure we always suppress keys\n// that have a dangerous default effect, even if the commands they are\n// bound to return false, and to make sure that cursor-motion keys\n// find a cursor (as opposed to a node selection) when pressed. For\n// cursor-motion keys, the code in the handlers also takes care of\n// block selections.\n\nfunction getMods(event) {\n var result = \"\";\n if (event.ctrlKey) { result += \"c\"; }\n if (event.metaKey) { result += \"m\"; }\n if (event.altKey) { result += \"a\"; }\n if (event.shiftKey) { result += \"s\"; }\n return result\n}\n\nfunction captureKeyDown(view, event) {\n var code = event.keyCode, mods = getMods(event);\n if (code == 8 || (result.mac && code == 72 && mods == \"c\")) { // Backspace, Ctrl-h on Mac\n return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodesLeft(view)\n } else if (code == 46 || (result.mac && code == 68 && mods == \"c\")) { // Delete, Ctrl-d on Mac\n return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodesRight(view)\n } else if (code == 13 || code == 27) { // Enter, Esc\n return true\n } else if (code == 37) { // Left arrow\n return selectHorizontally(view, -1, mods) || skipIgnoredNodesLeft(view)\n } else if (code == 39) { // Right arrow\n return selectHorizontally(view, 1, mods) || skipIgnoredNodesRight(view)\n } else if (code == 38) { // Up arrow\n return selectVertically(view, -1, mods) || skipIgnoredNodesLeft(view)\n } else if (code == 40) { // Down arrow\n return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodesRight(view)\n } else if (mods == (result.mac ? \"m\" : \"c\") &&\n (code == 66 || code == 73 || code == 89 || code == 90)) { // Mod-[biyz]\n return true\n }\n return false\n}\n\n// Note that all referencing and parsing is done with the\n// start-of-operation selection and document, since that's the one\n// that the DOM represents. If any changes came in in the meantime,\n// the modification is mapped over those before it is applied, in\n// readDOMChange.\n\nfunction parseBetween(view, from_, to_) {\n var ref = view.docView.parseRange(from_, to_);\n var parent = ref.node;\n var fromOffset = ref.fromOffset;\n var toOffset = ref.toOffset;\n var from = ref.from;\n var to = ref.to;\n\n var domSel = view.root.getSelection(), find = null, anchor = domSel.anchorNode;\n if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) {\n find = [{node: anchor, offset: domSel.anchorOffset}];\n if (!selectionCollapsed(domSel))\n { find.push({node: domSel.focusNode, offset: domSel.focusOffset}); }\n }\n // Work around issue in Chrome where backspacing sometimes replaces\n // the deleted content with a random BR node (issues #799, #831)\n if (result.chrome && view.lastKeyCode === 8) {\n for (var off = toOffset; off > fromOffset; off--) {\n var node = parent.childNodes[off - 1], desc = node.pmViewDesc;\n if (node.nodeType == \"BR\" && !desc) { toOffset = off; break }\n if (!desc || desc.size) { break }\n }\n }\n var startDoc = view.state.doc;\n var parser = view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n var $from = startDoc.resolve(from);\n\n var sel = null, doc = parser.parse(parent, {\n topNode: $from.parent,\n topMatch: $from.parent.contentMatchAt($from.index()),\n topOpen: true,\n from: fromOffset,\n to: toOffset,\n preserveWhitespace: $from.parent.type.spec.code ? \"full\" : true,\n editableContent: true,\n findPositions: find,\n ruleFromNode: ruleFromNode,\n context: $from\n });\n if (find && find[0].pos != null) {\n var anchor$1 = find[0].pos, head = find[1] && find[1].pos;\n if (head == null) { head = anchor$1; }\n sel = {anchor: anchor$1 + from, head: head + from};\n }\n return {doc: doc, sel: sel, from: from, to: to}\n}\n\nfunction ruleFromNode(dom) {\n var desc = dom.pmViewDesc;\n if (desc) {\n return desc.parseRule()\n } else if (dom.nodeName == \"BR\" && dom.parentNode) {\n // Safari replaces the list item or table cell with a BR\n // directly in the list node (?!) if you delete the last\n // character in a list item or table cell (#708, #862)\n if (result.safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {\n var skip = document.createElement(\"div\");\n skip.appendChild(document.createElement(\"li\"));\n return {skip: skip}\n } else if (dom.parentNode.lastChild == dom || result.safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {\n return {ignore: true}\n }\n } else if (dom.nodeName == \"IMG\" && dom.getAttribute(\"mark-placeholder\")) {\n return {ignore: true}\n }\n}\n\nfunction readDOMChange(view, from, to, typeOver, addedNodes) {\n if (from < 0) {\n var origin = view.lastSelectionTime > Date.now() - 50 ? view.lastSelectionOrigin : null;\n var newSel = selectionFromDOM(view, origin);\n if (newSel && !view.state.selection.eq(newSel)) {\n var tr$1 = view.state.tr.setSelection(newSel);\n if (origin == \"pointer\") { tr$1.setMeta(\"pointer\", true); }\n else if (origin == \"key\") { tr$1.scrollIntoView(); }\n view.dispatch(tr$1);\n }\n return\n }\n\n var $before = view.state.doc.resolve(from);\n var shared = $before.sharedDepth(to);\n from = $before.before(shared + 1);\n to = view.state.doc.resolve(to).after(shared + 1);\n\n var sel = view.state.selection;\n var parse = parseBetween(view, from, to);\n\n var doc = view.state.doc, compare = doc.slice(parse.from, parse.to);\n var preferredPos, preferredSide;\n // Prefer anchoring to end when Backspace is pressed\n if (view.lastKeyCode === 8 && Date.now() - 100 < view.lastKeyCodeTime) {\n preferredPos = view.state.selection.to;\n preferredSide = \"end\";\n } else {\n preferredPos = view.state.selection.from;\n preferredSide = \"start\";\n }\n view.lastKeyCode = null;\n\n var change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide);\n if (!change) {\n if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) &&\n !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) {\n change = {start: sel.from, endA: sel.to, endB: sel.to};\n } else {\n if (parse.sel) {\n var sel$1 = resolveSelection(view, view.state.doc, parse.sel);\n if (sel$1 && !sel$1.eq(view.state.selection)) { view.dispatch(view.state.tr.setSelection(sel$1)); }\n }\n return\n }\n }\n view.domChangeCount++;\n // Handle the case where overwriting a selection by typing matches\n // the start or end of the selected content, creating a change\n // that's smaller than what was actually overwritten.\n if (view.state.selection.from < view.state.selection.to &&\n change.start == change.endB &&\n view.state.selection instanceof TextSelection) {\n if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2) {\n change.start = view.state.selection.from;\n } else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2) {\n change.endB += (view.state.selection.to - change.endA);\n change.endA = view.state.selection.to;\n }\n }\n\n // IE11 will insert a non-breaking space _ahead_ of the space after\n // the cursor space when adding a space before another space. When\n // that happened, adjust the change to cover the space instead.\n if (result.ie && result.ie_version <= 11 && change.endB == change.start + 1 &&\n change.endA == change.start && change.start > parse.from &&\n parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == \" \\u00a0\") {\n change.start--;\n change.endA--;\n change.endB--;\n }\n\n var $from = parse.doc.resolveNoCache(change.start - parse.from);\n var $to = parse.doc.resolveNoCache(change.endB - parse.from);\n var inlineChange = $from.sameParent($to) && $from.parent.inlineContent;\n var nextSel;\n // If this looks like the effect of pressing Enter (or was recorded\n // as being an iOS enter press), just dispatch an Enter key instead.\n if (((result.ios && view.lastIOSEnter > Date.now() - 225 &&\n (!inlineChange || addedNodes.some(function (n) { return n.nodeName == \"DIV\" || n.nodeName == \"P\"; }))) ||\n (!inlineChange && $from.pos < parse.doc.content.size &&\n (nextSel = Selection.findFrom(parse.doc.resolve($from.pos + 1), 1, true)) &&\n nextSel.head == $to.pos)) &&\n view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(13, \"Enter\")); })) {\n view.lastIOSEnter = 0;\n return\n }\n // Same for backspace\n if (view.state.selection.anchor > change.start &&\n looksLikeJoin(doc, change.start, change.endA, $from, $to) &&\n view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(8, \"Backspace\")); })) {\n if (result.android && result.chrome) { view.domObserver.suppressSelectionUpdates(); } // #820\n return\n }\n\n // This tries to detect Android virtual keyboard\n // enter-and-pick-suggestion action. That sometimes (see issue\n // #1059) first fires a DOM mutation, before moving the selection to\n // the newly created block. And then, because ProseMirror cleans up\n // the DOM selection, it gives up moving the selection entirely,\n // leaving the cursor in the wrong place. When that happens, we drop\n // the new paragraph from the initial change, and fire a simulated\n // enter key afterwards.\n if (result.android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth &&\n parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) {\n change.endB -= 2;\n $to = parse.doc.resolveNoCache(change.endB - parse.from);\n setTimeout(function () {\n view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(13, \"Enter\")); });\n }, 20);\n }\n\n var chFrom = change.start, chTo = change.endA;\n\n var tr, storedMarks, markChange, $from1;\n if (inlineChange) {\n if ($from.pos == $to.pos) { // Deletion\n // IE11 sometimes weirdly moves the DOM selection around after\n // backspacing out the first element in a textblock\n if (result.ie && result.ie_version <= 11 && $from.parentOffset == 0) {\n view.domObserver.suppressSelectionUpdates();\n setTimeout(function () { return selectionToDOM(view); }, 20);\n }\n tr = view.state.tr.delete(chFrom, chTo);\n storedMarks = doc.resolve(change.start).marksAcross(doc.resolve(change.endA));\n } else if ( // Adding or removing a mark\n change.endA == change.endB && ($from1 = doc.resolve(change.start)) &&\n (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset),\n $from1.parent.content.cut($from1.parentOffset, change.endA - $from1.start())))\n ) {\n tr = view.state.tr;\n if (markChange.type == \"add\") { tr.addMark(chFrom, chTo, markChange.mark); }\n else { tr.removeMark(chFrom, chTo, markChange.mark); }\n } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {\n // Both positions in the same text node -- simply insert text\n var text = $from.parent.textBetween($from.parentOffset, $to.parentOffset);\n if (view.someProp(\"handleTextInput\", function (f) { return f(view, chFrom, chTo, text); })) { return }\n tr = view.state.tr.insertText(text, chFrom, chTo);\n }\n }\n\n if (!tr)\n { tr = view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from)); }\n if (parse.sel) {\n var sel$2 = resolveSelection(view, tr.doc, parse.sel);\n // Chrome Android will sometimes, during composition, report the\n // selection in the wrong place. If it looks like that is\n // happening, don't update the selection.\n // Edge just doesn't move the cursor forward when you start typing\n // in an empty block or between br nodes.\n if (sel$2 && !(result.chrome && result.android && view.composing && sel$2.empty &&\n (sel$2.head == chFrom || sel$2.head == tr.mapping.map(chTo) - 1) ||\n result.ie && sel$2.empty && sel$2.head == chFrom))\n { tr.setSelection(sel$2); }\n }\n if (storedMarks) { tr.ensureMarks(storedMarks); }\n view.dispatch(tr.scrollIntoView());\n}\n\nfunction resolveSelection(view, doc, parsedSel) {\n if (Math.max(parsedSel.anchor, parsedSel.head) > doc.content.size) { return null }\n return selectionBetween(view, doc.resolve(parsedSel.anchor), doc.resolve(parsedSel.head))\n}\n\n// : (Fragment, Fragment) → ?{mark: Mark, type: string}\n// Given two same-length, non-empty fragments of inline content,\n// determine whether the first could be created from the second by\n// removing or adding a single mark type.\nfunction isMarkChange(cur, prev) {\n var curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;\n var added = curMarks, removed = prevMarks, type, mark, update;\n for (var i = 0; i < prevMarks.length; i++) { added = prevMarks[i].removeFromSet(added); }\n for (var i$1 = 0; i$1 < curMarks.length; i$1++) { removed = curMarks[i$1].removeFromSet(removed); }\n if (added.length == 1 && removed.length == 0) {\n mark = added[0];\n type = \"add\";\n update = function (node) { return node.mark(mark.addToSet(node.marks)); };\n } else if (added.length == 0 && removed.length == 1) {\n mark = removed[0];\n type = \"remove\";\n update = function (node) { return node.mark(mark.removeFromSet(node.marks)); };\n } else {\n return null\n }\n var updated = [];\n for (var i$2 = 0; i$2 < prev.childCount; i$2++) { updated.push(update(prev.child(i$2))); }\n if (Fragment.from(updated).eq(cur)) { return {mark: mark, type: type} }\n}\n\nfunction looksLikeJoin(old, start, end, $newStart, $newEnd) {\n if (!$newStart.parent.isTextblock ||\n // The content must have shrunk\n end - start <= $newEnd.pos - $newStart.pos ||\n // newEnd must point directly at or after the end of the block that newStart points into\n skipClosingAndOpening($newStart, true, false) < $newEnd.pos)\n { return false }\n\n var $start = old.resolve(start);\n // Start must be at the end of a block\n if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock)\n { return false }\n var $next = old.resolve(skipClosingAndOpening($start, true, true));\n // The next textblock must start before end and end near it\n if (!$next.parent.isTextblock || $next.pos > end ||\n skipClosingAndOpening($next, true, false) < end)\n { return false }\n\n // The fragments after the join point must match\n return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content)\n}\n\nfunction skipClosingAndOpening($pos, fromEnd, mayOpen) {\n var depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos;\n while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {\n depth--;\n end++;\n fromEnd = false;\n }\n if (mayOpen) {\n var next = $pos.node(depth).maybeChild($pos.indexAfter(depth));\n while (next && !next.isLeaf) {\n next = next.firstChild;\n end++;\n }\n }\n return end\n}\n\nfunction findDiff(a, b, pos, preferredPos, preferredSide) {\n var start = a.findDiffStart(b, pos);\n if (start == null) { return null }\n var ref = a.findDiffEnd(b, pos + a.size, pos + b.size);\n var endA = ref.a;\n var endB = ref.b;\n if (preferredSide == \"end\") {\n var adjust = Math.max(0, start - Math.min(endA, endB));\n preferredPos -= endA + adjust - start;\n }\n if (endA < start && a.size < b.size) {\n var move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0;\n start -= move;\n endB = start + (endB - endA);\n endA = start;\n } else if (endB < start) {\n var move$1 = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0;\n start -= move$1;\n endA = start + (endA - endB);\n endB = start;\n }\n return {start: start, endA: endA, endB: endB}\n}\n\nfunction serializeForClipboard(view, slice) {\n var context = [];\n var content = slice.content;\n var openStart = slice.openStart;\n var openEnd = slice.openEnd;\n while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {\n openStart--;\n openEnd--;\n var node = content.firstChild;\n context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null);\n content = node.content;\n }\n\n var serializer = view.someProp(\"clipboardSerializer\") || DOMSerializer.fromSchema(view.state.schema);\n var doc = detachedDoc(), wrap = doc.createElement(\"div\");\n wrap.appendChild(serializer.serializeFragment(content, {document: doc}));\n\n var firstChild = wrap.firstChild, needsWrap;\n while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {\n for (var i = needsWrap.length - 1; i >= 0; i--) {\n var wrapper = doc.createElement(needsWrap[i]);\n while (wrap.firstChild) { wrapper.appendChild(wrap.firstChild); }\n wrap.appendChild(wrapper);\n }\n firstChild = wrap.firstChild;\n }\n\n if (firstChild && firstChild.nodeType == 1)\n { firstChild.setAttribute(\"data-pm-slice\", (openStart + \" \" + openEnd + \" \" + (JSON.stringify(context)))); }\n\n var text = view.someProp(\"clipboardTextSerializer\", function (f) { return f(slice); }) ||\n slice.content.textBetween(0, slice.content.size, \"\\n\\n\");\n\n return {dom: wrap, text: text}\n}\n\n// : (EditorView, string, string, ?bool, ResolvedPos) → ?Slice\n// Read a slice of content from the clipboard (or drop data).\nfunction parseFromClipboard(view, text, html, plainText, $context) {\n var dom, inCode = $context.parent.type.spec.code, slice;\n if (!html && !text) { return null }\n var asText = text && (plainText || inCode || !html);\n if (asText) {\n view.someProp(\"transformPastedText\", function (f) { text = f(text, inCode || plainText); });\n if (inCode) { return new Slice(Fragment.from(view.state.schema.text(text)), 0, 0) }\n var parsed = view.someProp(\"clipboardTextParser\", function (f) { return f(text, $context, plainText); });\n if (parsed) {\n slice = parsed;\n } else {\n dom = document.createElement(\"div\");\n text.trim().split(/(?:\\r\\n?|\\n)+/).forEach(function (block) {\n dom.appendChild(document.createElement(\"p\")).textContent = block;\n });\n }\n } else {\n view.someProp(\"transformPastedHTML\", function (f) { html = f(html); });\n dom = readHTML(html);\n }\n\n var contextNode = dom && dom.querySelector(\"[data-pm-slice]\");\n var sliceData = contextNode && /^(\\d+) (\\d+) (.*)/.exec(contextNode.getAttribute(\"data-pm-slice\"));\n if (!slice) {\n var parser = view.someProp(\"clipboardParser\") || view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n slice = parser.parseSlice(dom, {preserveWhitespace: !!(asText || sliceData), context: $context});\n }\n if (sliceData)\n { slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[3]); }\n else // HTML wasn't created by ProseMirror. Make sure top-level siblings are coherent\n { slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), false); }\n\n view.someProp(\"transformPasted\", function (f) { slice = f(slice); });\n return slice\n}\n\n// Takes a slice parsed with parseSlice, which means there hasn't been\n// any content-expression checking done on the top nodes, tries to\n// find a parent node in the current context that might fit the nodes,\n// and if successful, rebuilds the slice so that it fits into that parent.\n//\n// This addresses the problem that Transform.replace expects a\n// coherent slice, and will fail to place a set of siblings that don't\n// fit anywhere in the schema.\nfunction normalizeSiblings(fragment, $context) {\n if (fragment.childCount < 2) { return fragment }\n var loop = function ( d ) {\n var parent = $context.node(d);\n var match = parent.contentMatchAt($context.index(d));\n var lastWrap = (void 0), result = [];\n fragment.forEach(function (node) {\n if (!result) { return }\n var wrap = match.findWrapping(node.type), inLast;\n if (!wrap) { return result = null }\n if (inLast = result.length && lastWrap.length && addToSibling(wrap, lastWrap, node, result[result.length - 1], 0)) {\n result[result.length - 1] = inLast;\n } else {\n if (result.length) { result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length); }\n var wrapped = withWrappers(node, wrap);\n result.push(wrapped);\n match = match.matchType(wrapped.type, wrapped.attrs);\n lastWrap = wrap;\n }\n });\n if (result) { return { v: Fragment.from(result) } }\n };\n\n for (var d = $context.depth; d >= 0; d--) {\n var returned = loop( d );\n\n if ( returned ) return returned.v;\n }\n return fragment\n}\n\nfunction withWrappers(node, wrap, from) {\n if ( from === void 0 ) from = 0;\n\n for (var i = wrap.length - 1; i >= from; i--)\n { node = wrap[i].create(null, Fragment.from(node)); }\n return node\n}\n\n// Used to group adjacent nodes wrapped in similar parents by\n// normalizeSiblings into the same parent node\nfunction addToSibling(wrap, lastWrap, node, sibling, depth) {\n if (depth < wrap.length && depth < lastWrap.length && wrap[depth] == lastWrap[depth]) {\n var inner = addToSibling(wrap, lastWrap, node, sibling.lastChild, depth + 1);\n if (inner) { return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner)) }\n var match = sibling.contentMatchAt(sibling.childCount);\n if (match.matchType(depth == wrap.length - 1 ? node.type : wrap[depth + 1]))\n { return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap, depth + 1)))) }\n }\n}\n\nfunction closeRight(node, depth) {\n if (depth == 0) { return node }\n var fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1));\n var fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true);\n return node.copy(fragment.append(fill))\n}\n\nfunction closeRange(fragment, side, from, to, depth, openEnd) {\n var node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content;\n if (depth < to - 1) { inner = closeRange(inner, side, from, to, depth + 1, openEnd); }\n if (depth >= from)\n { inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, fragment.childCount > 1 || openEnd <= depth).append(inner)\n : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true)); }\n return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner))\n}\n\nfunction closeSlice(slice, openStart, openEnd) {\n if (openStart < slice.openStart)\n { slice = new Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd); }\n if (openEnd < slice.openEnd)\n { slice = new Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd); }\n return slice\n}\n\n// Trick from jQuery -- some elements must be wrapped in other\n// elements for innerHTML to work. I.e. if you do `div.innerHTML =\n// \"..\"` the table cells are ignored.\nvar wrapMap = {\n thead: [\"table\"],\n tbody: [\"table\"],\n tfoot: [\"table\"],\n caption: [\"table\"],\n colgroup: [\"table\"],\n col: [\"table\", \"colgroup\"],\n tr: [\"table\", \"tbody\"],\n td: [\"table\", \"tbody\", \"tr\"],\n th: [\"table\", \"tbody\", \"tr\"]\n};\n\nvar _detachedDoc = null;\nfunction detachedDoc() {\n return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument(\"title\"))\n}\n\nfunction readHTML(html) {\n var metas = /(\\s*]*>)*/.exec(html);\n if (metas) { html = html.slice(metas[0].length); }\n var elt = detachedDoc().createElement(\"div\");\n var firstTag = /(?:]*>)*<([a-z][^>\\s]+)/i.exec(html), wrap, depth = 0;\n if (wrap = firstTag && wrapMap[firstTag[1].toLowerCase()]) {\n html = wrap.map(function (n) { return \"<\" + n + \">\"; }).join(\"\") + html + wrap.map(function (n) { return \"\"; }).reverse().join(\"\");\n depth = wrap.length;\n }\n elt.innerHTML = html;\n for (var i = 0; i < depth; i++) { elt = elt.firstChild; }\n return elt\n}\n\nfunction addContext(slice, context) {\n if (!slice.size) { return slice }\n var schema = slice.content.firstChild.type.schema, array;\n try { array = JSON.parse(context); }\n catch(e) { return slice }\n var content = slice.content;\n var openStart = slice.openStart;\n var openEnd = slice.openEnd;\n for (var i = array.length - 2; i >= 0; i -= 2) {\n var type = schema.nodes[array[i]];\n if (!type || type.hasRequiredAttrs()) { break }\n content = Fragment.from(type.create(array[i + 1], content));\n openStart++; openEnd++;\n }\n return new Slice(content, openStart, openEnd)\n}\n\nvar observeOptions = {\n childList: true,\n characterData: true,\n characterDataOldValue: true,\n attributes: true,\n attributeOldValue: true,\n subtree: true\n};\n// IE11 has very broken mutation observers, so we also listen to DOMCharacterDataModified\nvar useCharData = result.ie && result.ie_version <= 11;\n\nvar SelectionState = function SelectionState() {\n this.anchorNode = this.anchorOffset = this.focusNode = this.focusOffset = null;\n};\n\nSelectionState.prototype.set = function set (sel) {\n this.anchorNode = sel.anchorNode; this.anchorOffset = sel.anchorOffset;\n this.focusNode = sel.focusNode; this.focusOffset = sel.focusOffset;\n};\n\nSelectionState.prototype.eq = function eq (sel) {\n return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset &&\n sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset\n};\n\nvar DOMObserver = function DOMObserver(view, handleDOMChange) {\n var this$1 = this;\n\n this.view = view;\n this.handleDOMChange = handleDOMChange;\n this.queue = [];\n this.flushingSoon = -1;\n this.observer = window.MutationObserver &&\n new window.MutationObserver(function (mutations) {\n for (var i = 0; i < mutations.length; i++) { this$1.queue.push(mutations[i]); }\n // IE11 will sometimes (on backspacing out a single character\n // text node after a BR node) call the observer callback\n // before actually updating the DOM, which will cause\n // ProseMirror to miss the change (see #930)\n if (result.ie && result.ie_version <= 11 && mutations.some(\n function (m) { return m.type == \"childList\" && m.removedNodes.length ||\n m.type == \"characterData\" && m.oldValue.length > m.target.nodeValue.length; }))\n { this$1.flushSoon(); }\n else\n { this$1.flush(); }\n });\n this.currentSelection = new SelectionState;\n if (useCharData) {\n this.onCharData = function (e) {\n this$1.queue.push({target: e.target, type: \"characterData\", oldValue: e.prevValue});\n this$1.flushSoon();\n };\n }\n this.onSelectionChange = this.onSelectionChange.bind(this);\n this.suppressingSelectionUpdates = false;\n};\n\nDOMObserver.prototype.flushSoon = function flushSoon () {\n var this$1 = this;\n\n if (this.flushingSoon < 0)\n { this.flushingSoon = window.setTimeout(function () { this$1.flushingSoon = -1; this$1.flush(); }, 20); }\n};\n\nDOMObserver.prototype.forceFlush = function forceFlush () {\n if (this.flushingSoon > -1) {\n window.clearTimeout(this.flushingSoon);\n this.flushingSoon = -1;\n this.flush();\n }\n};\n\nDOMObserver.prototype.start = function start () {\n if (this.observer)\n { this.observer.observe(this.view.dom, observeOptions); }\n if (useCharData)\n { this.view.dom.addEventListener(\"DOMCharacterDataModified\", this.onCharData); }\n this.connectSelection();\n};\n\nDOMObserver.prototype.stop = function stop () {\n var this$1 = this;\n\n if (this.observer) {\n var take = this.observer.takeRecords();\n if (take.length) {\n for (var i = 0; i < take.length; i++) { this.queue.push(take[i]); }\n window.setTimeout(function () { return this$1.flush(); }, 20);\n }\n this.observer.disconnect();\n }\n if (useCharData) { this.view.dom.removeEventListener(\"DOMCharacterDataModified\", this.onCharData); }\n this.disconnectSelection();\n};\n\nDOMObserver.prototype.connectSelection = function connectSelection () {\n this.view.dom.ownerDocument.addEventListener(\"selectionchange\", this.onSelectionChange);\n};\n\nDOMObserver.prototype.disconnectSelection = function disconnectSelection () {\n this.view.dom.ownerDocument.removeEventListener(\"selectionchange\", this.onSelectionChange);\n};\n\nDOMObserver.prototype.suppressSelectionUpdates = function suppressSelectionUpdates () {\n var this$1 = this;\n\n this.suppressingSelectionUpdates = true;\n setTimeout(function () { return this$1.suppressingSelectionUpdates = false; }, 50);\n};\n\nDOMObserver.prototype.onSelectionChange = function onSelectionChange () {\n if (!hasFocusAndSelection(this.view)) { return }\n if (this.suppressingSelectionUpdates) { return selectionToDOM(this.view) }\n // Deletions on IE11 fire their events in the wrong order, giving\n // us a selection change event before the DOM changes are\n // reported.\n if (result.ie && result.ie_version <= 11 && !this.view.state.selection.empty) {\n var sel = this.view.root.getSelection();\n // Selection.isCollapsed isn't reliable on IE\n if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))\n { return this.flushSoon() }\n }\n this.flush();\n};\n\nDOMObserver.prototype.setCurSelection = function setCurSelection () {\n this.currentSelection.set(this.view.root.getSelection());\n};\n\nDOMObserver.prototype.ignoreSelectionChange = function ignoreSelectionChange (sel) {\n if (sel.rangeCount == 0) { return true }\n var container = sel.getRangeAt(0).commonAncestorContainer;\n var desc = this.view.docView.nearestDesc(container);\n if (desc && desc.ignoreMutation({type: \"selection\", target: container.nodeType == 3 ? container.parentNode : container})) {\n this.setCurSelection();\n return true\n }\n};\n\nDOMObserver.prototype.flush = function flush () {\n if (!this.view.docView || this.flushingSoon > -1) { return }\n var mutations = this.observer ? this.observer.takeRecords() : [];\n if (this.queue.length) {\n mutations = this.queue.concat(mutations);\n this.queue.length = 0;\n }\n\n var sel = this.view.root.getSelection();\n var newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasSelection(this.view) && !this.ignoreSelectionChange(sel);\n\n var from = -1, to = -1, typeOver = false, added = [];\n if (this.view.editable) {\n for (var i = 0; i < mutations.length; i++) {\n var result$1 = this.registerMutation(mutations[i], added);\n if (result$1) {\n from = from < 0 ? result$1.from : Math.min(result$1.from, from);\n to = to < 0 ? result$1.to : Math.max(result$1.to, to);\n if (result$1.typeOver) { typeOver = true; }\n }\n }\n }\n\n if (result.gecko && added.length > 1) {\n var brs = added.filter(function (n) { return n.nodeName == \"BR\"; });\n if (brs.length == 2) {\n var a = brs[0];\n var b = brs[1];\n if (a.parentNode && a.parentNode.parentNode == b.parentNode) { b.remove(); }\n else { a.remove(); }\n }\n }\n\n if (from > -1 || newSel) {\n if (from > -1) {\n this.view.docView.markDirty(from, to);\n checkCSS(this.view);\n }\n this.handleDOMChange(from, to, typeOver, added);\n if (this.view.docView.dirty) { this.view.updateState(this.view.state); }\n else if (!this.currentSelection.eq(sel)) { selectionToDOM(this.view); }\n }\n};\n\nDOMObserver.prototype.registerMutation = function registerMutation (mut, added) {\n // Ignore mutations inside nodes that were already noted as inserted\n if (added.indexOf(mut.target) > -1) { return null }\n var desc = this.view.docView.nearestDesc(mut.target);\n if (mut.type == \"attributes\" &&\n (desc == this.view.docView || mut.attributeName == \"contenteditable\" ||\n // Firefox sometimes fires spurious events for null/empty styles\n (mut.attributeName == \"style\" && !mut.oldValue && !mut.target.getAttribute(\"style\"))))\n { return null }\n if (!desc || desc.ignoreMutation(mut)) { return null }\n\n if (mut.type == \"childList\") {\n var prev = mut.previousSibling, next = mut.nextSibling;\n if (result.ie && result.ie_version <= 11 && mut.addedNodes.length) {\n // IE11 gives us incorrect next/prev siblings for some\n // insertions, so if there are added nodes, recompute those\n for (var i = 0; i < mut.addedNodes.length; i++) {\n var ref = mut.addedNodes[i];\n var previousSibling = ref.previousSibling;\n var nextSibling = ref.nextSibling;\n if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0) { prev = previousSibling; }\n if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0) { next = nextSibling; }\n }\n }\n var fromOffset = prev && prev.parentNode == mut.target\n ? domIndex(prev) + 1 : 0;\n var from = desc.localPosFromDOM(mut.target, fromOffset, -1);\n var toOffset = next && next.parentNode == mut.target\n ? domIndex(next) : mut.target.childNodes.length;\n for (var i$1 = 0; i$1 < mut.addedNodes.length; i$1++) { added.push(mut.addedNodes[i$1]); }\n var to = desc.localPosFromDOM(mut.target, toOffset, 1);\n return {from: from, to: to}\n } else if (mut.type == \"attributes\") {\n return {from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border}\n } else { // \"characterData\"\n return {\n from: desc.posAtStart,\n to: desc.posAtEnd,\n // An event was generated for a text change that didn't change\n // any text. Mark the dom change to fall back to assuming the\n // selection was typed over with an identical value if it can't\n // find another change.\n typeOver: mut.target.nodeValue == mut.oldValue\n }\n }\n};\n\nvar cssChecked = false;\n\nfunction checkCSS(view) {\n if (cssChecked) { return }\n cssChecked = true;\n if (getComputedStyle(view.dom).whiteSpace == \"normal\")\n { console[\"warn\"](\"ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.\"); }\n}\n\n// A collection of DOM events that occur within the editor, and callback functions\n// to invoke when the event fires.\nvar handlers = {}, editHandlers = {};\n\nfunction initInput(view) {\n view.shiftKey = false;\n view.mouseDown = null;\n view.lastKeyCode = null;\n view.lastKeyCodeTime = 0;\n view.lastClick = {time: 0, x: 0, y: 0, type: \"\"};\n view.lastSelectionOrigin = null;\n view.lastSelectionTime = 0;\n\n view.lastIOSEnter = 0;\n view.lastIOSEnterFallbackTimeout = null;\n\n view.composing = false;\n view.composingTimeout = null;\n view.compositionNodes = [];\n view.compositionEndedAt = -2e8;\n\n view.domObserver = new DOMObserver(view, function (from, to, typeOver, added) { return readDOMChange(view, from, to, typeOver, added); });\n view.domObserver.start();\n // Used by hacks like the beforeinput handler to check whether anything happened in the DOM\n view.domChangeCount = 0;\n\n view.eventHandlers = Object.create(null);\n var loop = function ( event ) {\n var handler = handlers[event];\n view.dom.addEventListener(event, view.eventHandlers[event] = function (event) {\n if (eventBelongsToView(view, event) && !runCustomHandler(view, event) &&\n (view.editable || !(event.type in editHandlers)))\n { handler(view, event); }\n });\n };\n\n for (var event in handlers) loop( event );\n // On Safari, for reasons beyond my understanding, adding an input\n // event handler makes an issue where the composition vanishes when\n // you press enter go away.\n if (result.safari) { view.dom.addEventListener(\"input\", function () { return null; }); }\n\n ensureListeners(view);\n}\n\nfunction setSelectionOrigin(view, origin) {\n view.lastSelectionOrigin = origin;\n view.lastSelectionTime = Date.now();\n}\n\nfunction destroyInput(view) {\n view.domObserver.stop();\n for (var type in view.eventHandlers)\n { view.dom.removeEventListener(type, view.eventHandlers[type]); }\n clearTimeout(view.composingTimeout);\n clearTimeout(view.lastIOSEnterFallbackTimeout);\n}\n\nfunction ensureListeners(view) {\n view.someProp(\"handleDOMEvents\", function (currentHandlers) {\n for (var type in currentHandlers) { if (!view.eventHandlers[type])\n { view.dom.addEventListener(type, view.eventHandlers[type] = function (event) { return runCustomHandler(view, event); }); } }\n });\n}\n\nfunction runCustomHandler(view, event) {\n return view.someProp(\"handleDOMEvents\", function (handlers) {\n var handler = handlers[event.type];\n return handler ? handler(view, event) || event.defaultPrevented : false\n })\n}\n\nfunction eventBelongsToView(view, event) {\n if (!event.bubbles) { return true }\n if (event.defaultPrevented) { return false }\n for (var node = event.target; node != view.dom; node = node.parentNode)\n { if (!node || node.nodeType == 11 ||\n (node.pmViewDesc && node.pmViewDesc.stopEvent(event)))\n { return false } }\n return true\n}\n\nfunction dispatchEvent(view, event) {\n if (!runCustomHandler(view, event) && handlers[event.type] &&\n (view.editable || !(event.type in editHandlers)))\n { handlers[event.type](view, event); }\n}\n\neditHandlers.keydown = function (view, event) {\n view.shiftKey = event.keyCode == 16 || event.shiftKey;\n if (inOrNearComposition(view, event)) { return }\n view.domObserver.forceFlush();\n view.lastKeyCode = event.keyCode;\n view.lastKeyCodeTime = Date.now();\n // On iOS, if we preventDefault enter key presses, the virtual\n // keyboard gets confused. So the hack here is to set a flag that\n // makes the DOM change code recognize that what just happens should\n // be replaced by whatever the Enter key handlers do.\n if (result.ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {\n var now = Date.now();\n view.lastIOSEnter = now;\n view.lastIOSEnterFallbackTimeout = setTimeout(function () {\n if (view.lastIOSEnter == now) {\n view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(13, \"Enter\")); });\n view.lastIOSEnter = 0;\n }\n }, 200);\n } else if (view.someProp(\"handleKeyDown\", function (f) { return f(view, event); }) || captureKeyDown(view, event)) {\n event.preventDefault();\n } else {\n setSelectionOrigin(view, \"key\");\n }\n};\n\neditHandlers.keyup = function (view, e) {\n if (e.keyCode == 16) { view.shiftKey = false; }\n};\n\neditHandlers.keypress = function (view, event) {\n if (inOrNearComposition(view, event) || !event.charCode ||\n event.ctrlKey && !event.altKey || result.mac && event.metaKey) { return }\n\n if (view.someProp(\"handleKeyPress\", function (f) { return f(view, event); })) {\n event.preventDefault();\n return\n }\n\n var sel = view.state.selection;\n if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {\n var text = String.fromCharCode(event.charCode);\n if (!view.someProp(\"handleTextInput\", function (f) { return f(view, sel.$from.pos, sel.$to.pos, text); }))\n { view.dispatch(view.state.tr.insertText(text).scrollIntoView()); }\n event.preventDefault();\n }\n};\n\nfunction eventCoords(event) { return {left: event.clientX, top: event.clientY} }\n\nfunction isNear(event, click) {\n var dx = click.x - event.clientX, dy = click.y - event.clientY;\n return dx * dx + dy * dy < 100\n}\n\nfunction runHandlerOnContext(view, propName, pos, inside, event) {\n if (inside == -1) { return false }\n var $pos = view.state.doc.resolve(inside);\n var loop = function ( i ) {\n if (view.someProp(propName, function (f) { return i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true)\n : f(view, pos, $pos.node(i), $pos.before(i), event, false); }))\n { return { v: true } }\n };\n\n for (var i = $pos.depth + 1; i > 0; i--) {\n var returned = loop( i );\n\n if ( returned ) return returned.v;\n }\n return false\n}\n\nfunction updateSelection(view, selection, origin) {\n if (!view.focused) { view.focus(); }\n var tr = view.state.tr.setSelection(selection);\n if (origin == \"pointer\") { tr.setMeta(\"pointer\", true); }\n view.dispatch(tr);\n}\n\nfunction selectClickedLeaf(view, inside) {\n if (inside == -1) { return false }\n var $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter;\n if (node && node.isAtom && NodeSelection.isSelectable(node)) {\n updateSelection(view, new NodeSelection($pos), \"pointer\");\n return true\n }\n return false\n}\n\nfunction selectClickedNode(view, inside) {\n if (inside == -1) { return false }\n var sel = view.state.selection, selectedNode, selectAt;\n if (sel instanceof NodeSelection) { selectedNode = sel.node; }\n\n var $pos = view.state.doc.resolve(inside);\n for (var i = $pos.depth + 1; i > 0; i--) {\n var node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n if (NodeSelection.isSelectable(node)) {\n if (selectedNode && sel.$from.depth > 0 &&\n i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos)\n { selectAt = $pos.before(sel.$from.depth); }\n else\n { selectAt = $pos.before(i); }\n break\n }\n }\n\n if (selectAt != null) {\n updateSelection(view, NodeSelection.create(view.state.doc, selectAt), \"pointer\");\n return true\n } else {\n return false\n }\n}\n\nfunction handleSingleClick(view, pos, inside, event, selectNode) {\n return runHandlerOnContext(view, \"handleClickOn\", pos, inside, event) ||\n view.someProp(\"handleClick\", function (f) { return f(view, pos, event); }) ||\n (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside))\n}\n\nfunction handleDoubleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleDoubleClickOn\", pos, inside, event) ||\n view.someProp(\"handleDoubleClick\", function (f) { return f(view, pos, event); })\n}\n\nfunction handleTripleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleTripleClickOn\", pos, inside, event) ||\n view.someProp(\"handleTripleClick\", function (f) { return f(view, pos, event); }) ||\n defaultTripleClick(view, inside)\n}\n\nfunction defaultTripleClick(view, inside) {\n var doc = view.state.doc;\n if (inside == -1) {\n if (doc.inlineContent) {\n updateSelection(view, TextSelection.create(doc, 0, doc.content.size), \"pointer\");\n return true\n }\n return false\n }\n\n var $pos = doc.resolve(inside);\n for (var i = $pos.depth + 1; i > 0; i--) {\n var node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n var nodePos = $pos.before(i);\n if (node.inlineContent)\n { updateSelection(view, TextSelection.create(doc, nodePos + 1, nodePos + 1 + node.content.size), \"pointer\"); }\n else if (NodeSelection.isSelectable(node))\n { updateSelection(view, NodeSelection.create(doc, nodePos), \"pointer\"); }\n else\n { continue }\n return true\n }\n}\n\nfunction forceDOMFlush(view) {\n return endComposition(view)\n}\n\nvar selectNodeModifier = result.mac ? \"metaKey\" : \"ctrlKey\";\n\nhandlers.mousedown = function (view, event) {\n view.shiftKey = event.shiftKey;\n var flushed = forceDOMFlush(view);\n var now = Date.now(), type = \"singleClick\";\n if (now - view.lastClick.time < 500 && isNear(event, view.lastClick) && !event[selectNodeModifier]) {\n if (view.lastClick.type == \"singleClick\") { type = \"doubleClick\"; }\n else if (view.lastClick.type == \"doubleClick\") { type = \"tripleClick\"; }\n }\n view.lastClick = {time: now, x: event.clientX, y: event.clientY, type: type};\n\n var pos = view.posAtCoords(eventCoords(event));\n if (!pos) { return }\n\n if (type == \"singleClick\")\n { view.mouseDown = new MouseDown(view, pos, event, flushed); }\n else if ((type == \"doubleClick\" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event))\n { event.preventDefault(); }\n else\n { setSelectionOrigin(view, \"pointer\"); }\n};\n\nvar MouseDown = function MouseDown(view, pos, event, flushed) {\n var this$1 = this;\n\n this.view = view;\n this.startDoc = view.state.doc;\n this.pos = pos;\n this.event = event;\n this.flushed = flushed;\n this.selectNode = event[selectNodeModifier];\n this.allowDefault = event.shiftKey;\n\n var targetNode, targetPos;\n if (pos.inside > -1) {\n targetNode = view.state.doc.nodeAt(pos.inside);\n targetPos = pos.inside;\n } else {\n var $pos = view.state.doc.resolve(pos.pos);\n targetNode = $pos.parent;\n targetPos = $pos.depth ? $pos.before() : 0;\n }\n\n this.mightDrag = null;\n\n var target = flushed ? null : event.target;\n var targetDesc = target ? view.docView.nearestDesc(target, true) : null;\n this.target = targetDesc ? targetDesc.dom : null;\n\n if (targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false ||\n view.state.selection instanceof NodeSelection && targetPos == view.state.selection.from)\n { this.mightDrag = {node: targetNode,\n pos: targetPos,\n addAttr: this.target && !this.target.draggable,\n setUneditable: this.target && result.gecko && !this.target.hasAttribute(\"contentEditable\")}; }\n\n if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) {\n this.view.domObserver.stop();\n if (this.mightDrag.addAttr) { this.target.draggable = true; }\n if (this.mightDrag.setUneditable)\n { setTimeout(function () { return this$1.target.setAttribute(\"contentEditable\", \"false\"); }, 20); }\n this.view.domObserver.start();\n }\n\n view.root.addEventListener(\"mouseup\", this.up = this.up.bind(this));\n view.root.addEventListener(\"mousemove\", this.move = this.move.bind(this));\n setSelectionOrigin(view, \"pointer\");\n};\n\nMouseDown.prototype.done = function done () {\n this.view.root.removeEventListener(\"mouseup\", this.up);\n this.view.root.removeEventListener(\"mousemove\", this.move);\n if (this.mightDrag && this.target) {\n this.view.domObserver.stop();\n if (this.mightDrag.addAttr) { this.target.removeAttribute(\"draggable\"); }\n if (this.mightDrag.setUneditable) { this.target.removeAttribute(\"contentEditable\"); }\n this.view.domObserver.start();\n }\n this.view.mouseDown = null;\n};\n\nMouseDown.prototype.up = function up (event) {\n this.done();\n\n if (!this.view.dom.contains(event.target.nodeType == 3 ? event.target.parentNode : event.target))\n { return }\n\n var pos = this.pos;\n if (this.view.state.doc != this.startDoc) { pos = this.view.posAtCoords(eventCoords(event)); }\n\n if (this.allowDefault || !pos) {\n setSelectionOrigin(this.view, \"pointer\");\n } else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {\n event.preventDefault();\n } else if (this.flushed ||\n // Safari ignores clicks on draggable elements\n (result.safari && this.mightDrag && !this.mightDrag.node.isAtom) ||\n // Chrome will sometimes treat a node selection as a\n // cursor, but still report that the node is selected\n // when asked through getSelection. You'll then get a\n // situation where clicking at the point where that\n // (hidden) cursor is doesn't change the selection, and\n // thus doesn't get a reaction from ProseMirror. This\n // works around that.\n (result.chrome && !(this.view.state.selection instanceof TextSelection) &&\n (pos.pos == this.view.state.selection.from || pos.pos == this.view.state.selection.to))) {\n updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)), \"pointer\");\n event.preventDefault();\n } else {\n setSelectionOrigin(this.view, \"pointer\");\n }\n};\n\nMouseDown.prototype.move = function move (event) {\n if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 ||\n Math.abs(this.event.y - event.clientY) > 4))\n { this.allowDefault = true; }\n setSelectionOrigin(this.view, \"pointer\");\n};\n\nhandlers.touchdown = function (view) {\n forceDOMFlush(view);\n setSelectionOrigin(view, \"pointer\");\n};\n\nhandlers.contextmenu = function (view) { return forceDOMFlush(view); };\n\nfunction inOrNearComposition(view, event) {\n if (view.composing) { return true }\n // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.\n // On Japanese input method editors (IMEs), the Enter key is used to confirm character\n // selection. On Safari, when Enter is pressed, compositionend and keydown events are\n // emitted. The keydown event triggers newline insertion, which we don't want.\n // This method returns true if the keydown event should be ignored.\n // We only ignore it once, as pressing Enter a second time *should* insert a newline.\n // Furthermore, the keydown event timestamp must be close to the compositionEndedAt timestamp.\n // This guards against the case where compositionend is triggered without the keyboard\n // (e.g. character confirmation may be done with the mouse), and keydown is triggered\n // afterwards- we wouldn't want to ignore the keydown event in this case.\n if (result.safari && Math.abs(event.timeStamp - view.compositionEndedAt) < 500) {\n view.compositionEndedAt = -2e8;\n return true\n }\n return false\n}\n\n// Drop active composition after 5 seconds of inactivity on Android\nvar timeoutComposition = result.android ? 5000 : -1;\n\neditHandlers.compositionstart = editHandlers.compositionupdate = function (view) {\n if (!view.composing) {\n view.domObserver.flush();\n var state = view.state;\n var $pos = state.selection.$from;\n if (state.selection.empty &&\n (state.storedMarks || (!$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some(function (m) { return m.type.spec.inclusive === false; })))) {\n // Need to wrap the cursor in mark nodes different from the ones in the DOM context\n view.markCursor = view.state.storedMarks || $pos.marks();\n endComposition(view, true);\n view.markCursor = null;\n } else {\n endComposition(view);\n // In firefox, if the cursor is after but outside a marked node,\n // the inserted text won't inherit the marks. So this moves it\n // inside if necessary.\n if (result.gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {\n var sel = view.root.getSelection();\n for (var node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0;) {\n var before = offset < 0 ? node.lastChild : node.childNodes[offset - 1];\n if (!before) { break }\n if (before.nodeType == 3) {\n sel.collapse(before, before.nodeValue.length);\n break\n } else {\n node = before;\n offset = -1;\n }\n }\n }\n }\n view.composing = true;\n }\n scheduleComposeEnd(view, timeoutComposition);\n};\n\neditHandlers.compositionend = function (view, event) {\n if (view.composing) {\n view.composing = false;\n view.compositionEndedAt = event.timeStamp;\n scheduleComposeEnd(view, 20);\n }\n};\n\nfunction scheduleComposeEnd(view, delay) {\n clearTimeout(view.composingTimeout);\n if (delay > -1) { view.composingTimeout = setTimeout(function () { return endComposition(view); }, delay); }\n}\n\nfunction clearComposition(view) {\n view.composing = false;\n while (view.compositionNodes.length > 0) { view.compositionNodes.pop().markParentsDirty(); }\n}\n\nfunction endComposition(view, forceUpdate) {\n view.domObserver.forceFlush();\n clearComposition(view);\n if (forceUpdate || view.docView.dirty) {\n var sel = selectionFromDOM(view);\n if (sel && !sel.eq(view.state.selection)) { view.dispatch(view.state.tr.setSelection(sel)); }\n else { view.updateState(view.state); }\n return true\n }\n return false\n}\n\nfunction captureCopy(view, dom) {\n // The extra wrapper is somehow necessary on IE/Edge to prevent the\n // content from being mangled when it is put onto the clipboard\n if (!view.dom.parentNode) { return }\n var wrap = view.dom.parentNode.appendChild(document.createElement(\"div\"));\n wrap.appendChild(dom);\n wrap.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n var sel = getSelection(), range = document.createRange();\n range.selectNodeContents(dom);\n // Done because IE will fire a selectionchange moving the selection\n // to its start when removeAllRanges is called and the editor still\n // has focus (which will mess up the editor's selection state).\n view.dom.blur();\n sel.removeAllRanges();\n sel.addRange(range);\n setTimeout(function () {\n if (wrap.parentNode) { wrap.parentNode.removeChild(wrap); }\n view.focus();\n }, 50);\n}\n\n// This is very crude, but unfortunately both these browsers _pretend_\n// that they have a clipboard API—all the objects and methods are\n// there, they just don't work, and they are hard to test.\nvar brokenClipboardAPI = (result.ie && result.ie_version < 15) ||\n (result.ios && result.webkit_version < 604);\n\nhandlers.copy = editHandlers.cut = function (view, e) {\n var sel = view.state.selection, cut = e.type == \"cut\";\n if (sel.empty) { return }\n\n // IE and Edge's clipboard interface is completely broken\n var data = brokenClipboardAPI ? null : e.clipboardData;\n var slice = sel.content();\n var ref = serializeForClipboard(view, slice);\n var dom = ref.dom;\n var text = ref.text;\n if (data) {\n e.preventDefault();\n data.clearData();\n data.setData(\"text/html\", dom.innerHTML);\n data.setData(\"text/plain\", text);\n } else {\n captureCopy(view, dom);\n }\n if (cut) { view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta(\"uiEvent\", \"cut\")); }\n};\n\nfunction sliceSingleNode(slice) {\n return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null\n}\n\nfunction capturePaste(view, e) {\n if (!view.dom.parentNode) { return }\n var plainText = view.shiftKey || view.state.selection.$from.parent.type.spec.code;\n var target = view.dom.parentNode.appendChild(document.createElement(plainText ? \"textarea\" : \"div\"));\n if (!plainText) { target.contentEditable = \"true\"; }\n target.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n target.focus();\n setTimeout(function () {\n view.focus();\n if (target.parentNode) { target.parentNode.removeChild(target); }\n if (plainText) { doPaste(view, target.value, null, e); }\n else { doPaste(view, target.textContent, target.innerHTML, e); }\n }, 50);\n}\n\nfunction doPaste(view, text, html, e) {\n var slice = parseFromClipboard(view, text, html, view.shiftKey, view.state.selection.$from);\n if (view.someProp(\"handlePaste\", function (f) { return f(view, e, slice || Slice.empty); }) || !slice) { return }\n\n var singleNode = sliceSingleNode(slice);\n var tr = singleNode ? view.state.tr.replaceSelectionWith(singleNode, view.shiftKey) : view.state.tr.replaceSelection(slice);\n view.dispatch(tr.scrollIntoView().setMeta(\"paste\", true).setMeta(\"uiEvent\", \"paste\"));\n}\n\neditHandlers.paste = function (view, e) {\n var data = brokenClipboardAPI ? null : e.clipboardData;\n var html = data && data.getData(\"text/html\"), text = data && data.getData(\"text/plain\");\n if (data && (html || text || data.files.length)) {\n doPaste(view, text, html, e);\n e.preventDefault();\n } else {\n capturePaste(view, e);\n }\n};\n\nvar Dragging = function Dragging(slice, move) {\n this.slice = slice;\n this.move = move;\n};\n\nvar dragCopyModifier = result.mac ? \"altKey\" : \"ctrlKey\";\n\nhandlers.dragstart = function (view, e) {\n var mouseDown = view.mouseDown;\n if (mouseDown) { mouseDown.done(); }\n if (!e.dataTransfer) { return }\n\n var sel = view.state.selection;\n var pos = sel.empty ? null : view.posAtCoords(eventCoords(e));\n if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1: sel.to)) ; else if (mouseDown && mouseDown.mightDrag) {\n view.dispatch(view.state.tr.setSelection(NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos)));\n } else if (e.target && e.target.nodeType == 1) {\n var desc = view.docView.nearestDesc(e.target, true);\n if (!desc || !desc.node.type.spec.draggable || desc == view.docView) { return }\n view.dispatch(view.state.tr.setSelection(NodeSelection.create(view.state.doc, desc.posBefore)));\n }\n var slice = view.state.selection.content();\n var ref = serializeForClipboard(view, slice);\n var dom = ref.dom;\n var text = ref.text;\n e.dataTransfer.clearData();\n e.dataTransfer.setData(brokenClipboardAPI ? \"Text\" : \"text/html\", dom.innerHTML);\n if (!brokenClipboardAPI) { e.dataTransfer.setData(\"text/plain\", text); }\n view.dragging = new Dragging(slice, !e[dragCopyModifier]);\n};\n\nhandlers.dragend = function (view) {\n var dragging = view.dragging;\n window.setTimeout(function () {\n if (view.dragging == dragging) { view.dragging = null; }\n }, 50);\n};\n\neditHandlers.dragover = editHandlers.dragenter = function (_, e) { return e.preventDefault(); };\n\neditHandlers.drop = function (view, e) {\n var dragging = view.dragging;\n view.dragging = null;\n\n if (!e.dataTransfer) { return }\n\n var eventPos = view.posAtCoords(eventCoords(e));\n if (!eventPos) { return }\n var $mouse = view.state.doc.resolve(eventPos.pos);\n if (!$mouse) { return }\n var slice = dragging && dragging.slice ||\n parseFromClipboard(view, e.dataTransfer.getData(brokenClipboardAPI ? \"Text\" : \"text/plain\"),\n brokenClipboardAPI ? null : e.dataTransfer.getData(\"text/html\"), false, $mouse);\n var move = dragging && !e[dragCopyModifier];\n if (view.someProp(\"handleDrop\", function (f) { return f(view, e, slice || Slice.empty, move); })) {\n e.preventDefault();\n return\n }\n if (!slice) { return }\n\n e.preventDefault();\n var insertPos = slice ? dropPoint(view.state.doc, $mouse.pos, slice) : $mouse.pos;\n if (insertPos == null) { insertPos = $mouse.pos; }\n\n var tr = view.state.tr;\n if (move) { tr.deleteSelection(); }\n\n var pos = tr.mapping.map(insertPos);\n var isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1;\n var beforeInsert = tr.doc;\n if (isNode)\n { tr.replaceRangeWith(pos, pos, slice.content.firstChild); }\n else\n { tr.replaceRange(pos, pos, slice); }\n if (tr.doc.eq(beforeInsert)) { return }\n\n var $pos = tr.doc.resolve(pos);\n if (isNode && NodeSelection.isSelectable(slice.content.firstChild) &&\n $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice.content.firstChild)) {\n tr.setSelection(new NodeSelection($pos));\n } else {\n var end = tr.mapping.map(insertPos);\n tr.mapping.maps[tr.mapping.maps.length - 1].forEach(function (_from, _to, _newFrom, newTo) { return end = newTo; });\n tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(end)));\n }\n view.focus();\n view.dispatch(tr.setMeta(\"uiEvent\", \"drop\"));\n};\n\nhandlers.focus = function (view) {\n if (!view.focused) {\n view.domObserver.stop();\n view.dom.classList.add(\"ProseMirror-focused\");\n view.domObserver.start();\n view.focused = true;\n setTimeout(function () {\n if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.root.getSelection()))\n { selectionToDOM(view); }\n }, 20);\n }\n};\n\nhandlers.blur = function (view) {\n if (view.focused) {\n view.domObserver.stop();\n view.dom.classList.remove(\"ProseMirror-focused\");\n view.domObserver.start();\n view.domObserver.currentSelection.set({});\n view.focused = false;\n }\n};\n\nhandlers.beforeinput = function (view, event) {\n // We should probably do more with beforeinput events, but support\n // is so spotty that I'm still waiting to see where they are going.\n\n // Very specific hack to deal with backspace sometimes failing on\n // Chrome Android when after an uneditable node.\n if (result.chrome && result.android && event.inputType == \"deleteContentBackward\") {\n var domChangeCount = view.domChangeCount;\n setTimeout(function () {\n if (view.domChangeCount != domChangeCount) { return } // Event already had some effect\n // This bug tends to close the virtual keyboard, so we refocus\n view.dom.blur();\n view.focus();\n if (view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(8, \"Backspace\")); })) { return }\n var ref = view.state.selection;\n var $cursor = ref.$cursor;\n // Crude approximation of backspace behavior when no command handled it\n if ($cursor && $cursor.pos > 0) { view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView()); }\n }, 50);\n }\n};\n\n// Make sure all handlers get registered\nfor (var prop in editHandlers) { handlers[prop] = editHandlers[prop]; }\n\nfunction compareObjs(a, b) {\n if (a == b) { return true }\n for (var p in a) { if (a[p] !== b[p]) { return false } }\n for (var p$1 in b) { if (!(p$1 in a)) { return false } }\n return true\n}\n\nvar WidgetType = function WidgetType(toDOM, spec) {\n this.spec = spec || noSpec;\n this.side = this.spec.side || 0;\n this.toDOM = toDOM;\n};\n\nWidgetType.prototype.map = function map (mapping, span, offset, oldOffset) {\n var ref = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);\n var pos = ref.pos;\n var deleted = ref.deleted;\n return deleted ? null : new Decoration(pos - offset, pos - offset, this)\n};\n\nWidgetType.prototype.valid = function valid () { return true };\n\nWidgetType.prototype.eq = function eq (other) {\n return this == other ||\n (other instanceof WidgetType &&\n (this.spec.key && this.spec.key == other.spec.key ||\n this.toDOM == other.toDOM && compareObjs(this.spec, other.spec)))\n};\n\nvar InlineType = function InlineType(attrs, spec) {\n this.spec = spec || noSpec;\n this.attrs = attrs;\n};\n\nInlineType.prototype.map = function map (mapping, span, offset, oldOffset) {\n var from = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;\n var to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;\n return from >= to ? null : new Decoration(from, to, this)\n};\n\nInlineType.prototype.valid = function valid (_, span) { return span.from < span.to };\n\nInlineType.prototype.eq = function eq (other) {\n return this == other ||\n (other instanceof InlineType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec))\n};\n\nInlineType.is = function is (span) { return span.type instanceof InlineType };\n\nvar NodeType = function NodeType(attrs, spec) {\n this.spec = spec || noSpec;\n this.attrs = attrs;\n};\n\nNodeType.prototype.map = function map (mapping, span, offset, oldOffset) {\n var from = mapping.mapResult(span.from + oldOffset, 1);\n if (from.deleted) { return null }\n var to = mapping.mapResult(span.to + oldOffset, -1);\n if (to.deleted || to.pos <= from.pos) { return null }\n return new Decoration(from.pos - offset, to.pos - offset, this)\n};\n\nNodeType.prototype.valid = function valid (node, span) {\n var ref = node.content.findIndex(span.from);\n var index = ref.index;\n var offset = ref.offset;\n return offset == span.from && offset + node.child(index).nodeSize == span.to\n};\n\nNodeType.prototype.eq = function eq (other) {\n return this == other ||\n (other instanceof NodeType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec))\n};\n\n// ::- Decoration objects can be provided to the view through the\n// [`decorations` prop](#view.EditorProps.decorations). They come in\n// several variants—see the static members of this class for details.\nvar Decoration = function Decoration(from, to, type) {\n // :: number\n // The start position of the decoration.\n this.from = from;\n // :: number\n // The end position. Will be the same as `from` for [widget\n // decorations](#view.Decoration^widget).\n this.to = to;\n this.type = type;\n};\n\nvar prototypeAccessors$1 = { spec: { configurable: true },inline: { configurable: true } };\n\nDecoration.prototype.copy = function copy (from, to) {\n return new Decoration(from, to, this.type)\n};\n\nDecoration.prototype.eq = function eq (other, offset) {\n if ( offset === void 0 ) offset = 0;\n\n return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to\n};\n\nDecoration.prototype.map = function map (mapping, offset, oldOffset) {\n return this.type.map(mapping, this, offset, oldOffset)\n};\n\n// :: (number, union<(view: EditorView, getPos: () → number) → dom.Node, dom.Node>, ?Object) → Decoration\n// Creates a widget decoration, which is a DOM node that's shown in\n// the document at the given position. It is recommended that you\n// delay rendering the widget by passing a function that will be\n// called when the widget is actually drawn in a view, but you can\n// also directly pass a DOM node. `getPos` can be used to find the\n// widget's current document position.\n//\n// spec::- These options are supported:\n//\n// side:: ?number\n// Controls which side of the document position this widget is\n// associated with. When negative, it is drawn before a cursor\n// at its position, and content inserted at that position ends\n// up after the widget. When zero (the default) or positive, the\n// widget is drawn after the cursor and content inserted there\n// ends up before the widget.\n//\n// When there are multiple widgets at a given position, their\n// `side` values determine the order in which they appear. Those\n// with lower values appear first. The ordering of widgets with\n// the same `side` value is unspecified.\n//\n// When `marks` is null, `side` also determines the marks that\n// the widget is wrapped in—those of the node before when\n// negative, those of the node after when positive.\n//\n// marks:: ?[Mark]\n// The precise set of marks to draw around the widget.\n//\n// stopEvent:: ?(event: dom.Event) → bool\n// Can be used to control which DOM events, when they bubble out\n// of this widget, the editor view should ignore.\n//\n// ignoreSelection:: ?bool\n// When set (defaults to false), selection changes inside the\n// widget are ignored, and don't cause ProseMirror to try and\n// re-sync the selection with its selection state.\n//\n// key:: ?string\n// When comparing decorations of this type (in order to decide\n// whether it needs to be redrawn), ProseMirror will by default\n// compare the widget DOM node by identity. If you pass a key,\n// that key will be compared instead, which can be useful when\n// you generate decorations on the fly and don't want to store\n// and reuse DOM nodes. Make sure that any widgets with the same\n// key are interchangeable—if widgets differ in, for example,\n// the behavior of some event handler, they should get\n// different keys.\nDecoration.widget = function widget (pos, toDOM, spec) {\n return new Decoration(pos, pos, new WidgetType(toDOM, spec))\n};\n\n// :: (number, number, DecorationAttrs, ?Object) → Decoration\n// Creates an inline decoration, which adds the given attributes to\n// each inline node between `from` and `to`.\n//\n// spec::- These options are recognized:\n//\n// inclusiveStart:: ?bool\n// Determines how the left side of the decoration is\n// [mapped](#transform.Position_Mapping) when content is\n// inserted directly at that position. By default, the decoration\n// won't include the new content, but you can set this to `true`\n// to make it inclusive.\n//\n// inclusiveEnd:: ?bool\n// Determines how the right side of the decoration is mapped.\n// See\n// [`inclusiveStart`](#view.Decoration^inline^spec.inclusiveStart).\nDecoration.inline = function inline (from, to, attrs, spec) {\n return new Decoration(from, to, new InlineType(attrs, spec))\n};\n\n// :: (number, number, DecorationAttrs, ?Object) → Decoration\n// Creates a node decoration. `from` and `to` should point precisely\n// before and after a node in the document. That node, and only that\n// node, will receive the given attributes.\n//\n// spec::-\n//\n// Optional information to store with the decoration. It\n// is also used when comparing decorators for equality.\nDecoration.node = function node (from, to, attrs, spec) {\n return new Decoration(from, to, new NodeType(attrs, spec))\n};\n\n// :: Object\n// The spec provided when creating this decoration. Can be useful\n// if you've stored extra information in that object.\nprototypeAccessors$1.spec.get = function () { return this.type.spec };\n\nprototypeAccessors$1.inline.get = function () { return this.type instanceof InlineType };\n\nObject.defineProperties( Decoration.prototype, prototypeAccessors$1 );\n\n// DecorationAttrs:: interface\n// A set of attributes to add to a decorated node. Most properties\n// simply directly correspond to DOM attributes of the same name,\n// which will be set to the property's value. These are exceptions:\n//\n// class:: ?string\n// A CSS class name or a space-separated set of class names to be\n// _added_ to the classes that the node already had.\n//\n// style:: ?string\n// A string of CSS to be _added_ to the node's existing `style` property.\n//\n// nodeName:: ?string\n// When non-null, the target node is wrapped in a DOM element of\n// this type (and the other attributes are applied to this element).\n\nvar none = [], noSpec = {};\n\n// ::- A collection of [decorations](#view.Decoration), organized in\n// such a way that the drawing algorithm can efficiently use and\n// compare them. This is a persistent data structure—it is not\n// modified, updates create a new value.\nvar DecorationSet = function DecorationSet(local, children) {\n this.local = local && local.length ? local : none;\n this.children = children && children.length ? children : none;\n};\n\n// :: (Node, [Decoration]) → DecorationSet\n// Create a set of decorations, using the structure of the given\n// document.\nDecorationSet.create = function create (doc, decorations) {\n return decorations.length ? buildTree(decorations, doc, 0, noSpec) : empty\n};\n\n// :: (?number, ?number, ?(spec: Object) → bool) → [Decoration]\n// Find all decorations in this set which touch the given range\n// (including decorations that start or end directly at the\n// boundaries) and match the given predicate on their spec. When\n// `start` and `end` are omitted, all decorations in the set are\n// considered. When `predicate` isn't given, all decorations are\n// assumed to match.\nDecorationSet.prototype.find = function find (start, end, predicate) {\n var result = [];\n this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate);\n return result\n};\n\nDecorationSet.prototype.findInner = function findInner (start, end, result, offset, predicate) {\n for (var i = 0; i < this.local.length; i++) {\n var span = this.local[i];\n if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec)))\n { result.push(span.copy(span.from + offset, span.to + offset)); }\n }\n for (var i$1 = 0; i$1 < this.children.length; i$1 += 3) {\n if (this.children[i$1] < end && this.children[i$1 + 1] > start) {\n var childOff = this.children[i$1] + 1;\n this.children[i$1 + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate);\n }\n }\n};\n\n// :: (Mapping, Node, ?Object) → DecorationSet\n// Map the set of decorations in response to a change in the\n// document.\n//\n// options::- An optional set of options.\n//\n// onRemove:: ?(decorationSpec: Object)\n// When given, this function will be called for each decoration\n// that gets dropped as a result of the mapping, passing the\n// spec of that decoration.\nDecorationSet.prototype.map = function map (mapping, doc, options) {\n if (this == empty || mapping.maps.length == 0) { return this }\n return this.mapInner(mapping, doc, 0, 0, options || noSpec)\n};\n\nDecorationSet.prototype.mapInner = function mapInner (mapping, node, offset, oldOffset, options) {\n var newLocal;\n for (var i = 0; i < this.local.length; i++) {\n var mapped = this.local[i].map(mapping, offset, oldOffset);\n if (mapped && mapped.type.valid(node, mapped)) { (newLocal || (newLocal = [])).push(mapped); }\n else if (options.onRemove) { options.onRemove(this.local[i].spec); }\n }\n\n if (this.children.length)\n { return mapChildren(this.children, newLocal, mapping, node, offset, oldOffset, options) }\n else\n { return newLocal ? new DecorationSet(newLocal.sort(byPos)) : empty }\n};\n\n// :: (Node, [Decoration]) → DecorationSet\n// Add the given array of decorations to the ones in the set,\n// producing a new set. Needs access to the current document to\n// create the appropriate tree structure.\nDecorationSet.prototype.add = function add (doc, decorations) {\n if (!decorations.length) { return this }\n if (this == empty) { return DecorationSet.create(doc, decorations) }\n return this.addInner(doc, decorations, 0)\n};\n\nDecorationSet.prototype.addInner = function addInner (doc, decorations, offset) {\n var this$1 = this;\n\n var children, childIndex = 0;\n doc.forEach(function (childNode, childOffset) {\n var baseOffset = childOffset + offset, found;\n if (!(found = takeSpansForNode(decorations, childNode, baseOffset))) { return }\n\n if (!children) { children = this$1.children.slice(); }\n while (childIndex < children.length && children[childIndex] < childOffset) { childIndex += 3; }\n if (children[childIndex] == childOffset)\n { children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found, baseOffset + 1); }\n else\n { children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found, childNode, baseOffset + 1, noSpec)); }\n childIndex += 3;\n });\n\n var local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset);\n return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local,\n children || this.children)\n};\n\n// :: ([Decoration]) → DecorationSet\n// Create a new set that contains the decorations in this set, minus\n// the ones in the given array.\nDecorationSet.prototype.remove = function remove (decorations) {\n if (decorations.length == 0 || this == empty) { return this }\n return this.removeInner(decorations, 0)\n};\n\nDecorationSet.prototype.removeInner = function removeInner (decorations, offset) {\n var children = this.children, local = this.local;\n for (var i = 0; i < children.length; i += 3) {\n var found = (void 0), from = children[i] + offset, to = children[i + 1] + offset;\n for (var j = 0, span = (void 0); j < decorations.length; j++) { if (span = decorations[j]) {\n if (span.from > from && span.to < to) {\n decorations[j] = null\n ;(found || (found = [])).push(span);\n }\n } }\n if (!found) { continue }\n if (children == this.children) { children = this.children.slice(); }\n var removed = children[i + 2].removeInner(found, from + 1);\n if (removed != empty) {\n children[i + 2] = removed;\n } else {\n children.splice(i, 3);\n i -= 3;\n }\n }\n if (local.length) { for (var i$1 = 0, span$1 = (void 0); i$1 < decorations.length; i$1++) { if (span$1 = decorations[i$1]) {\n for (var j$1 = 0; j$1 < local.length; j$1++) { if (local[j$1].eq(span$1, offset)) {\n if (local == this.local) { local = this.local.slice(); }\n local.splice(j$1--, 1);\n } }\n } } }\n if (children == this.children && local == this.local) { return this }\n return local.length || children.length ? new DecorationSet(local, children) : empty\n};\n\nDecorationSet.prototype.forChild = function forChild (offset, node) {\n if (this == empty) { return this }\n if (node.isLeaf) { return DecorationSet.empty }\n\n var child, local;\n for (var i = 0; i < this.children.length; i += 3) { if (this.children[i] >= offset) {\n if (this.children[i] == offset) { child = this.children[i + 2]; }\n break\n } }\n var start = offset + 1, end = start + node.content.size;\n for (var i$1 = 0; i$1 < this.local.length; i$1++) {\n var dec = this.local[i$1];\n if (dec.from < end && dec.to > start && (dec.type instanceof InlineType)) {\n var from = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start;\n if (from < to) { (local || (local = [])).push(dec.copy(from, to)); }\n }\n }\n if (local) {\n var localSet = new DecorationSet(local.sort(byPos));\n return child ? new DecorationGroup([localSet, child]) : localSet\n }\n return child || empty\n};\n\nDecorationSet.prototype.eq = function eq (other) {\n if (this == other) { return true }\n if (!(other instanceof DecorationSet) ||\n this.local.length != other.local.length ||\n this.children.length != other.children.length) { return false }\n for (var i = 0; i < this.local.length; i++)\n { if (!this.local[i].eq(other.local[i])) { return false } }\n for (var i$1 = 0; i$1 < this.children.length; i$1 += 3)\n { if (this.children[i$1] != other.children[i$1] ||\n this.children[i$1 + 1] != other.children[i$1 + 1] ||\n !this.children[i$1 + 2].eq(other.children[i$1 + 2])) { return false } }\n return true\n};\n\nDecorationSet.prototype.locals = function locals (node) {\n return removeOverlap(this.localsInner(node))\n};\n\nDecorationSet.prototype.localsInner = function localsInner (node) {\n if (this == empty) { return none }\n if (node.inlineContent || !this.local.some(InlineType.is)) { return this.local }\n var result = [];\n for (var i = 0; i < this.local.length; i++) {\n if (!(this.local[i].type instanceof InlineType))\n { result.push(this.local[i]); }\n }\n return result\n};\n\nvar empty = new DecorationSet();\n\n// :: DecorationSet\n// The empty set of decorations.\nDecorationSet.empty = empty;\n\nDecorationSet.removeOverlap = removeOverlap;\n\n// :- An abstraction that allows the code dealing with decorations to\n// treat multiple DecorationSet objects as if it were a single object\n// with (a subset of) the same interface.\nvar DecorationGroup = function DecorationGroup(members) {\n this.members = members;\n};\n\nDecorationGroup.prototype.forChild = function forChild (offset, child) {\n if (child.isLeaf) { return DecorationSet.empty }\n var found = [];\n for (var i = 0; i < this.members.length; i++) {\n var result = this.members[i].forChild(offset, child);\n if (result == empty) { continue }\n if (result instanceof DecorationGroup) { found = found.concat(result.members); }\n else { found.push(result); }\n }\n return DecorationGroup.from(found)\n};\n\nDecorationGroup.prototype.eq = function eq (other) {\n if (!(other instanceof DecorationGroup) ||\n other.members.length != this.members.length) { return false }\n for (var i = 0; i < this.members.length; i++)\n { if (!this.members[i].eq(other.members[i])) { return false } }\n return true\n};\n\nDecorationGroup.prototype.locals = function locals (node) {\n var result, sorted = true;\n for (var i = 0; i < this.members.length; i++) {\n var locals = this.members[i].localsInner(node);\n if (!locals.length) { continue }\n if (!result) {\n result = locals;\n } else {\n if (sorted) {\n result = result.slice();\n sorted = false;\n }\n for (var j = 0; j < locals.length; j++) { result.push(locals[j]); }\n }\n }\n return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none\n};\n\n// : ([DecorationSet]) → union\n// Create a group for the given array of decoration sets, or return\n// a single set when possible.\nDecorationGroup.from = function from (members) {\n switch (members.length) {\n case 0: return empty\n case 1: return members[0]\n default: return new DecorationGroup(members)\n }\n};\n\nfunction mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) {\n var children = oldChildren.slice();\n\n // Mark the children that are directly touched by changes, and\n // move those that are after the changes.\n var shift = function (oldStart, oldEnd, newStart, newEnd) {\n for (var i = 0; i < children.length; i += 3) {\n var end = children[i + 1], dSize = (void 0);\n if (end == -1 || oldStart > end + oldOffset) { continue }\n if (oldEnd >= children[i] + oldOffset) {\n children[i + 1] = -1;\n } else if (newStart >= offset && (dSize = (newEnd - newStart) - (oldEnd - oldStart))) {\n children[i] += dSize;\n children[i + 1] += dSize;\n }\n }\n };\n for (var i = 0; i < mapping.maps.length; i++) { mapping.maps[i].forEach(shift); }\n\n // Find the child nodes that still correspond to a single node,\n // recursively call mapInner on them and update their positions.\n var mustRebuild = false;\n for (var i$1 = 0; i$1 < children.length; i$1 += 3) { if (children[i$1 + 1] == -1) { // Touched nodes\n var from = mapping.map(oldChildren[i$1] + oldOffset), fromLocal = from - offset;\n if (fromLocal < 0 || fromLocal >= node.content.size) {\n mustRebuild = true;\n continue\n }\n // Must read oldChildren because children was tagged with -1\n var to = mapping.map(oldChildren[i$1 + 1] + oldOffset, -1), toLocal = to - offset;\n var ref = node.content.findIndex(fromLocal);\n var index = ref.index;\n var childOffset = ref.offset;\n var childNode = node.maybeChild(index);\n if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {\n var mapped = children[i$1 + 2].mapInner(mapping, childNode, from + 1, oldChildren[i$1] + oldOffset + 1, options);\n if (mapped != empty) {\n children[i$1] = fromLocal;\n children[i$1 + 1] = toLocal;\n children[i$1 + 2] = mapped;\n } else {\n children[i$1 + 1] = -2;\n mustRebuild = true;\n }\n } else {\n mustRebuild = true;\n }\n } }\n\n // Remaining children must be collected and rebuilt into the appropriate structure\n if (mustRebuild) {\n var decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal || [], mapping,\n offset, oldOffset, options);\n var built = buildTree(decorations, node, 0, options);\n newLocal = built.local;\n for (var i$2 = 0; i$2 < children.length; i$2 += 3) { if (children[i$2 + 1] < 0) {\n children.splice(i$2, 3);\n i$2 -= 3;\n } }\n for (var i$3 = 0, j = 0; i$3 < built.children.length; i$3 += 3) {\n var from$1 = built.children[i$3];\n while (j < children.length && children[j] < from$1) { j += 3; }\n children.splice(j, 0, built.children[i$3], built.children[i$3 + 1], built.children[i$3 + 2]);\n }\n }\n\n return new DecorationSet(newLocal && newLocal.sort(byPos), children)\n}\n\nfunction moveSpans(spans, offset) {\n if (!offset || !spans.length) { return spans }\n var result = [];\n for (var i = 0; i < spans.length; i++) {\n var span = spans[i];\n result.push(new Decoration(span.from + offset, span.to + offset, span.type));\n }\n return result\n}\n\nfunction mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) {\n // Gather all decorations from the remaining marked children\n function gather(set, oldOffset) {\n for (var i = 0; i < set.local.length; i++) {\n var mapped = set.local[i].map(mapping, offset, oldOffset);\n if (mapped) { decorations.push(mapped); }\n else if (options.onRemove) { options.onRemove(set.local[i].spec); }\n }\n for (var i$1 = 0; i$1 < set.children.length; i$1 += 3)\n { gather(set.children[i$1 + 2], set.children[i$1] + oldOffset + 1); }\n }\n for (var i = 0; i < children.length; i += 3) { if (children[i + 1] == -1)\n { gather(children[i + 2], oldChildren[i] + oldOffset + 1); } }\n\n return decorations\n}\n\nfunction takeSpansForNode(spans, node, offset) {\n if (node.isLeaf) { return null }\n var end = offset + node.nodeSize, found = null;\n for (var i = 0, span = (void 0); i < spans.length; i++) {\n if ((span = spans[i]) && span.from > offset && span.to < end) {\n(found || (found = [])).push(span);\n spans[i] = null;\n }\n }\n return found\n}\n\nfunction withoutNulls(array) {\n var result = [];\n for (var i = 0; i < array.length; i++)\n { if (array[i] != null) { result.push(array[i]); } }\n return result\n}\n\n// : ([Decoration], Node, number) → DecorationSet\n// Build up a tree that corresponds to a set of decorations. `offset`\n// is a base offset that should be subtractet from the `from` and `to`\n// positions in the spans (so that we don't have to allocate new spans\n// for recursive calls).\nfunction buildTree(spans, node, offset, options) {\n var children = [], hasNulls = false;\n node.forEach(function (childNode, localStart) {\n var found = takeSpansForNode(spans, childNode, localStart + offset);\n if (found) {\n hasNulls = true;\n var subtree = buildTree(found, childNode, offset + localStart + 1, options);\n if (subtree != empty)\n { children.push(localStart, localStart + childNode.nodeSize, subtree); }\n }\n });\n var locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);\n for (var i = 0; i < locals.length; i++) { if (!locals[i].type.valid(node, locals[i])) {\n if (options.onRemove) { options.onRemove(locals[i].spec); }\n locals.splice(i--, 1);\n } }\n return locals.length || children.length ? new DecorationSet(locals, children) : empty\n}\n\n// : (Decoration, Decoration) → number\n// Used to sort decorations so that ones with a low start position\n// come first, and within a set with the same start position, those\n// with an smaller end position come first.\nfunction byPos(a, b) {\n return a.from - b.from || a.to - b.to\n}\n\n// : ([Decoration]) → [Decoration]\n// Scan a sorted array of decorations for partially overlapping spans,\n// and split those so that only fully overlapping spans are left (to\n// make subsequent rendering easier). Will return the input array if\n// no partially overlapping spans are found (the common case).\nfunction removeOverlap(spans) {\n var working = spans;\n for (var i = 0; i < working.length - 1; i++) {\n var span = working[i];\n if (span.from != span.to) { for (var j = i + 1; j < working.length; j++) {\n var next = working[j];\n if (next.from == span.from) {\n if (next.to != span.to) {\n if (working == spans) { working = spans.slice(); }\n // Followed by a partially overlapping larger span. Split that\n // span.\n working[j] = next.copy(next.from, span.to);\n insertAhead(working, j + 1, next.copy(span.to, next.to));\n }\n continue\n } else {\n if (next.from < span.to) {\n if (working == spans) { working = spans.slice(); }\n // The end of this one overlaps with a subsequent span. Split\n // this one.\n working[i] = span.copy(span.from, next.from);\n insertAhead(working, j, span.copy(next.from, span.to));\n }\n break\n }\n } }\n }\n return working\n}\n\nfunction insertAhead(array, i, deco) {\n while (i < array.length && byPos(deco, array[i]) > 0) { i++; }\n array.splice(i, 0, deco);\n}\n\n// : (EditorView) → union\n// Get the decorations associated with the current props of a view.\nfunction viewDecorations(view) {\n var found = [];\n view.someProp(\"decorations\", function (f) {\n var result = f(view.state);\n if (result && result != empty) { found.push(result); }\n });\n if (view.cursorWrapper)\n { found.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco])); }\n return DecorationGroup.from(found)\n}\n\n// ::- An editor view manages the DOM structure that represents an\n// editable document. Its state and behavior are determined by its\n// [props](#view.DirectEditorProps).\nvar EditorView = function EditorView(place, props) {\n this._props = props;\n // :: EditorState\n // The view's current [state](#state.EditorState).\n this.state = props.state;\n\n this.dispatch = this.dispatch.bind(this);\n\n this._root = null;\n this.focused = false;\n // Kludge used to work around a Chrome bug\n this.trackWrites = null;\n\n // :: dom.Element\n // An editable DOM node containing the document. (You probably\n // should not directly interfere with its content.)\n this.dom = (place && place.mount) || document.createElement(\"div\");\n if (place) {\n if (place.appendChild) { place.appendChild(this.dom); }\n else if (place.apply) { place(this.dom); }\n else if (place.mount) { this.mounted = true; }\n }\n\n // :: bool\n // Indicates whether the editor is currently [editable](#view.EditorProps.editable).\n this.editable = getEditable(this);\n this.markCursor = null;\n this.cursorWrapper = null;\n updateCursorWrapper(this);\n this.nodeViews = buildNodeViews(this);\n this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);\n\n this.lastSelectedViewDesc = null;\n // :: ?{slice: Slice, move: bool}\n // When editor content is being dragged, this object contains\n // information about the dragged slice and whether it is being\n // copied or moved. At any other time, it is null.\n this.dragging = null;\n\n initInput(this);\n\n this.pluginViews = [];\n this.updatePluginViews();\n};\n\nvar prototypeAccessors$2 = { props: { configurable: true },root: { configurable: true } };\n\n// composing:: boolean\n// Holds `true` when a\n// [composition](https://developer.mozilla.org/en-US/docs/Mozilla/IME_handling_guide)\n// is active.\n\n// :: DirectEditorProps\n// The view's current [props](#view.EditorProps).\nprototypeAccessors$2.props.get = function () {\n if (this._props.state != this.state) {\n var prev = this._props;\n this._props = {};\n for (var name in prev) { this._props[name] = prev[name]; }\n this._props.state = this.state;\n }\n return this._props\n};\n\n// :: (DirectEditorProps)\n// Update the view's props. Will immediately cause an update to\n// the DOM.\nEditorView.prototype.update = function update (props) {\n if (props.handleDOMEvents != this._props.handleDOMEvents) { ensureListeners(this); }\n this._props = props;\n this.updateStateInner(props.state, true);\n};\n\n// :: (DirectEditorProps)\n// Update the view by updating existing props object with the object\n// given as argument. Equivalent to `view.update(Object.assign({},\n// view.props, props))`.\nEditorView.prototype.setProps = function setProps (props) {\n var updated = {};\n for (var name in this._props) { updated[name] = this._props[name]; }\n updated.state = this.state;\n for (var name$1 in props) { updated[name$1] = props[name$1]; }\n this.update(updated);\n};\n\n// :: (EditorState)\n// Update the editor's `state` prop, without touching any of the\n// other props.\nEditorView.prototype.updateState = function updateState (state) {\n this.updateStateInner(state, this.state.plugins != state.plugins);\n};\n\nEditorView.prototype.updateStateInner = function updateStateInner (state, reconfigured) {\n var this$1 = this;\n\n var prev = this.state, redraw = false, updateSel = false;\n // When stored marks are added, stop composition, so that they can\n // be displayed.\n if (state.storedMarks && this.composing) {\n clearComposition(this);\n updateSel = true;\n }\n this.state = state;\n if (reconfigured) {\n var nodeViews = buildNodeViews(this);\n if (changedNodeViews(nodeViews, this.nodeViews)) {\n this.nodeViews = nodeViews;\n redraw = true;\n }\n ensureListeners(this);\n }\n\n this.editable = getEditable(this);\n updateCursorWrapper(this);\n var innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);\n\n var scroll = reconfigured ? \"reset\"\n : state.scrollToSelection > prev.scrollToSelection ? \"to selection\" : \"preserve\";\n var updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);\n if (updateDoc || !state.selection.eq(prev.selection)) { updateSel = true; }\n var oldScrollPos = scroll == \"preserve\" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);\n\n if (updateSel) {\n this.domObserver.stop();\n // Work around an issue in Chrome, IE, and Edge where changing\n // the DOM around an active selection puts it into a broken\n // state where the thing the user sees differs from the\n // selection reported by the Selection object (#710, #973,\n // #1011, #1013, #1035).\n var forceSelUpdate = updateDoc && (result.ie || result.chrome) && !this.composing &&\n !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);\n if (updateDoc) {\n // If the node that the selection points into is written to,\n // Chrome sometimes starts misreporting the selection, so this\n // tracks that and forces a selection reset when our update\n // did write to the node.\n var chromeKludge = result.chrome ? (this.trackWrites = this.root.getSelection().focusNode) : null;\n if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {\n this.docView.updateOuterDeco([]);\n this.docView.destroy();\n this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);\n }\n if (chromeKludge && !this.trackWrites) { forceSelUpdate = true; }\n }\n // Work around for an issue where an update arriving right between\n // a DOM selection change and the \"selectionchange\" event for it\n // can cause a spurious DOM selection update, disrupting mouse\n // drag selection.\n if (forceSelUpdate ||\n !(this.mouseDown && this.domObserver.currentSelection.eq(this.root.getSelection()) && anchorInRightPlace(this))) {\n selectionToDOM(this, forceSelUpdate);\n } else {\n syncNodeSelection(this, state.selection);\n this.domObserver.setCurSelection();\n }\n this.domObserver.start();\n }\n\n this.updatePluginViews(prev);\n\n if (scroll == \"reset\") {\n this.dom.scrollTop = 0;\n } else if (scroll == \"to selection\") {\n var startDOM = this.root.getSelection().focusNode;\n if (this.someProp(\"handleScrollToSelection\", function (f) { return f(this$1); }))\n ; // Handled\n else if (state.selection instanceof NodeSelection)\n { scrollRectIntoView(this, this.docView.domAfterPos(state.selection.from).getBoundingClientRect(), startDOM); }\n else\n { scrollRectIntoView(this, this.coordsAtPos(state.selection.head, 1), startDOM); }\n } else if (oldScrollPos) {\n resetScrollPos(oldScrollPos);\n }\n};\n\nEditorView.prototype.destroyPluginViews = function destroyPluginViews () {\n var view;\n while (view = this.pluginViews.pop()) { if (view.destroy) { view.destroy(); } }\n};\n\nEditorView.prototype.updatePluginViews = function updatePluginViews (prevState) {\n if (!prevState || prevState.plugins != this.state.plugins) {\n this.destroyPluginViews();\n for (var i = 0; i < this.state.plugins.length; i++) {\n var plugin = this.state.plugins[i];\n if (plugin.spec.view) { this.pluginViews.push(plugin.spec.view(this)); }\n }\n } else {\n for (var i$1 = 0; i$1 < this.pluginViews.length; i$1++) {\n var pluginView = this.pluginViews[i$1];\n if (pluginView.update) { pluginView.update(this, prevState); }\n }\n }\n};\n\n// :: (string, ?(prop: *) → *) → *\n// Goes over the values of a prop, first those provided directly,\n// then those from plugins (in order), and calls `f` every time a\n// non-undefined value is found. When `f` returns a truthy value,\n// that is immediately returned. When `f` isn't provided, it is\n// treated as the identity function (the prop value is returned\n// directly).\nEditorView.prototype.someProp = function someProp (propName, f) {\n var prop = this._props && this._props[propName], value;\n if (prop != null && (value = f ? f(prop) : prop)) { return value }\n var plugins = this.state.plugins;\n if (plugins) { for (var i = 0; i < plugins.length; i++) {\n var prop$1 = plugins[i].props[propName];\n if (prop$1 != null && (value = f ? f(prop$1) : prop$1)) { return value }\n } }\n};\n\n// :: () → bool\n// Query whether the view has focus.\nEditorView.prototype.hasFocus = function hasFocus () {\n return this.root.activeElement == this.dom\n};\n\n// :: ()\n// Focus the editor.\nEditorView.prototype.focus = function focus () {\n this.domObserver.stop();\n if (this.editable) { focusPreventScroll(this.dom); }\n selectionToDOM(this);\n this.domObserver.start();\n};\n\n// :: union\n// Get the document root in which the editor exists. This will\n// usually be the top-level `document`, but might be a [shadow\n// DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)\n// root if the editor is inside one.\nprototypeAccessors$2.root.get = function () {\n var cached = this._root;\n if (cached == null) { for (var search = this.dom.parentNode; search; search = search.parentNode) {\n if (search.nodeType == 9 || (search.nodeType == 11 && search.host)) {\n if (!search.getSelection) { Object.getPrototypeOf(search).getSelection = function () { return document.getSelection(); }; }\n return this._root = search\n }\n } }\n return cached || document\n};\n\n// :: ({left: number, top: number}) → ?{pos: number, inside: number}\n// Given a pair of viewport coordinates, return the document\n// position that corresponds to them. May return null if the given\n// coordinates aren't inside of the editor. When an object is\n// returned, its `pos` property is the position nearest to the\n// coordinates, and its `inside` property holds the position of the\n// inner node that the position falls inside of, or -1 if it is at\n// the top level, not in any node.\nEditorView.prototype.posAtCoords = function posAtCoords$1 (coords) {\n return posAtCoords(this, coords)\n};\n\n// :: (number, number) → {left: number, right: number, top: number, bottom: number}\n// Returns the viewport rectangle at a given document position.\n// `left` and `right` will be the same number, as this returns a\n// flat cursor-ish rectangle. If the position is between two things\n// that aren't directly adjacent, `side` determines which element is\n// used. When < 0, the element before the position is used,\n// otherwise the element after.\nEditorView.prototype.coordsAtPos = function coordsAtPos$1 (pos, side) {\n if ( side === void 0 ) side = 1;\n\n return coordsAtPos(this, pos, side)\n};\n\n// :: (number) → {node: dom.Node, offset: number}\n// Find the DOM position that corresponds to the given document\n// position. Note that you should **not** mutate the editor's\n// internal DOM, only inspect it (and even that is usually not\n// necessary).\nEditorView.prototype.domAtPos = function domAtPos (pos) {\n return this.docView.domFromPos(pos)\n};\n\n// :: (number) → ?dom.Node\n// Find the DOM node that represents the document node after the\n// given position. May return `null` when the position doesn't point\n// in front of a node or if the node is inside an opaque node view.\n//\n// This is intended to be able to call things like\n// `getBoundingClientRect` on that DOM node. Do **not** mutate the\n// editor DOM directly, or add styling this way, since that will be\n// immediately overriden by the editor as it redraws the node.\nEditorView.prototype.nodeDOM = function nodeDOM (pos) {\n var desc = this.docView.descAt(pos);\n return desc ? desc.nodeDOM : null\n};\n\n// :: (dom.Node, number, ?number) → number\n// Find the document position that corresponds to a given DOM\n// position. (Whenever possible, it is preferable to inspect the\n// document structure directly, rather than poking around in the\n// DOM, but sometimes—for example when interpreting an event\n// target—you don't have a choice.)\n//\n// The `bias` parameter can be used to influence which side of a DOM\n// node to use when the position is inside a leaf node.\nEditorView.prototype.posAtDOM = function posAtDOM (node, offset, bias) {\n if ( bias === void 0 ) bias = -1;\n\n var pos = this.docView.posFromDOM(node, offset, bias);\n if (pos == null) { throw new RangeError(\"DOM position not inside the editor\") }\n return pos\n};\n\n// :: (union<\"up\", \"down\", \"left\", \"right\", \"forward\", \"backward\">, ?EditorState) → bool\n// Find out whether the selection is at the end of a textblock when\n// moving in a given direction. When, for example, given `\"left\"`,\n// it will return true if moving left from the current cursor\n// position would leave that position's parent textblock. Will apply\n// to the view's current state by default, but it is possible to\n// pass a different state.\nEditorView.prototype.endOfTextblock = function endOfTextblock$1 (dir, state) {\n return endOfTextblock(this, state || this.state, dir)\n};\n\n// :: ()\n// Removes the editor from the DOM and destroys all [node\n// views](#view.NodeView).\nEditorView.prototype.destroy = function destroy () {\n if (!this.docView) { return }\n destroyInput(this);\n this.destroyPluginViews();\n if (this.mounted) {\n this.docView.update(this.state.doc, [], viewDecorations(this), this);\n this.dom.textContent = \"\";\n } else if (this.dom.parentNode) {\n this.dom.parentNode.removeChild(this.dom);\n }\n this.docView.destroy();\n this.docView = null;\n};\n\n// Used for testing.\nEditorView.prototype.dispatchEvent = function dispatchEvent$1 (event) {\n return dispatchEvent(this, event)\n};\n\n// :: (Transaction)\n// Dispatch a transaction. Will call\n// [`dispatchTransaction`](#view.DirectEditorProps.dispatchTransaction)\n// when given, and otherwise defaults to applying the transaction to\n// the current state and calling\n// [`updateState`](#view.EditorView.updateState) with the result.\n// This method is bound to the view instance, so that it can be\n// easily passed around.\nEditorView.prototype.dispatch = function dispatch (tr) {\n var dispatchTransaction = this._props.dispatchTransaction;\n if (dispatchTransaction) { dispatchTransaction.call(this, tr); }\n else { this.updateState(this.state.apply(tr)); }\n};\n\nObject.defineProperties( EditorView.prototype, prototypeAccessors$2 );\n\nfunction computeDocDeco(view) {\n var attrs = Object.create(null);\n attrs.class = \"ProseMirror\";\n attrs.contenteditable = String(view.editable);\n\n view.someProp(\"attributes\", function (value) {\n if (typeof value == \"function\") { value = value(view.state); }\n if (value) { for (var attr in value) {\n if (attr == \"class\")\n { attrs.class += \" \" + value[attr]; }\n else if (!attrs[attr] && attr != \"contenteditable\" && attr != \"nodeName\")\n { attrs[attr] = String(value[attr]); }\n } }\n });\n\n return [Decoration.node(0, view.state.doc.content.size, attrs)]\n}\n\nfunction updateCursorWrapper(view) {\n if (view.markCursor) {\n var dom = document.createElement(\"img\");\n dom.setAttribute(\"mark-placeholder\", \"true\");\n view.cursorWrapper = {dom: dom, deco: Decoration.widget(view.state.selection.head, dom, {raw: true, marks: view.markCursor})};\n } else {\n view.cursorWrapper = null;\n }\n}\n\nfunction getEditable(view) {\n return !view.someProp(\"editable\", function (value) { return value(view.state) === false; })\n}\n\nfunction selectionContextChanged(sel1, sel2) {\n var depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));\n return sel1.$anchor.start(depth) != sel2.$anchor.start(depth)\n}\n\nfunction buildNodeViews(view) {\n var result = {};\n view.someProp(\"nodeViews\", function (obj) {\n for (var prop in obj) { if (!Object.prototype.hasOwnProperty.call(result, prop))\n { result[prop] = obj[prop]; } }\n });\n return result\n}\n\nfunction changedNodeViews(a, b) {\n var nA = 0, nB = 0;\n for (var prop in a) {\n if (a[prop] != b[prop]) { return true }\n nA++;\n }\n for (var _ in b) { nB++; }\n return nA != nB\n}\n\n// EditorProps:: interface\n//\n// Props are configuration values that can be passed to an editor view\n// or included in a plugin. This interface lists the supported props.\n//\n// The various event-handling functions may all return `true` to\n// indicate that they handled the given event. The view will then take\n// care to call `preventDefault` on the event, except with\n// `handleDOMEvents`, where the handler itself is responsible for that.\n//\n// How a prop is resolved depends on the prop. Handler functions are\n// called one at a time, starting with the base props and then\n// searching through the plugins (in order of appearance) until one of\n// them returns true. For some props, the first plugin that yields a\n// value gets precedence.\n//\n// handleDOMEvents:: ?Object<(view: EditorView, event: dom.Event) → bool>\n// Can be an object mapping DOM event type names to functions that\n// handle them. Such functions will be called before any handling\n// ProseMirror does of events fired on the editable DOM element.\n// Contrary to the other event handling props, when returning true\n// from such a function, you are responsible for calling\n// `preventDefault` yourself (or not, if you want to allow the\n// default behavior).\n//\n// handleKeyDown:: ?(view: EditorView, event: dom.KeyboardEvent) → bool\n// Called when the editor receives a `keydown` event.\n//\n// handleKeyPress:: ?(view: EditorView, event: dom.KeyboardEvent) → bool\n// Handler for `keypress` events.\n//\n// handleTextInput:: ?(view: EditorView, from: number, to: number, text: string) → bool\n// Whenever the user directly input text, this handler is called\n// before the input is applied. If it returns `true`, the default\n// behavior of actually inserting the text is suppressed.\n//\n// handleClickOn:: ?(view: EditorView, pos: number, node: Node, nodePos: number, event: dom.MouseEvent, direct: bool) → bool\n// Called for each node around a click, from the inside out. The\n// `direct` flag will be true for the inner node.\n//\n// handleClick:: ?(view: EditorView, pos: number, event: dom.MouseEvent) → bool\n// Called when the editor is clicked, after `handleClickOn` handlers\n// have been called.\n//\n// handleDoubleClickOn:: ?(view: EditorView, pos: number, node: Node, nodePos: number, event: dom.MouseEvent, direct: bool) → bool\n// Called for each node around a double click.\n//\n// handleDoubleClick:: ?(view: EditorView, pos: number, event: dom.MouseEvent) → bool\n// Called when the editor is double-clicked, after `handleDoubleClickOn`.\n//\n// handleTripleClickOn:: ?(view: EditorView, pos: number, node: Node, nodePos: number, event: dom.MouseEvent, direct: bool) → bool\n// Called for each node around a triple click.\n//\n// handleTripleClick:: ?(view: EditorView, pos: number, event: dom.MouseEvent) → bool\n// Called when the editor is triple-clicked, after `handleTripleClickOn`.\n//\n// handlePaste:: ?(view: EditorView, event: dom.ClipboardEvent, slice: Slice) → bool\n// Can be used to override the behavior of pasting. `slice` is the\n// pasted content parsed by the editor, but you can directly access\n// the event to get at the raw content.\n//\n// handleDrop:: ?(view: EditorView, event: dom.Event, slice: Slice, moved: bool) → bool\n// Called when something is dropped on the editor. `moved` will be\n// true if this drop moves from the current selection (which should\n// thus be deleted).\n//\n// handleScrollToSelection:: ?(view: EditorView) → bool\n// Called when the view, after updating its state, tries to scroll\n// the selection into view. A handler function may return false to\n// indicate that it did not handle the scrolling and further\n// handlers or the default behavior should be tried.\n//\n// createSelectionBetween:: ?(view: EditorView, anchor: ResolvedPos, head: ResolvedPos) → ?Selection\n// Can be used to override the way a selection is created when\n// reading a DOM selection between the given anchor and head.\n//\n// domParser:: ?DOMParser\n// The [parser](#model.DOMParser) to use when reading editor changes\n// from the DOM. Defaults to calling\n// [`DOMParser.fromSchema`](#model.DOMParser^fromSchema) on the\n// editor's schema.\n//\n// transformPastedHTML:: ?(html: string) → string\n// Can be used to transform pasted HTML text, _before_ it is parsed,\n// for example to clean it up.\n//\n// clipboardParser:: ?DOMParser\n// The [parser](#model.DOMParser) to use when reading content from\n// the clipboard. When not given, the value of the\n// [`domParser`](#view.EditorProps.domParser) prop is used.\n//\n// transformPastedText:: ?(text: string, plain: bool) → string\n// Transform pasted plain text. The `plain` flag will be true when\n// the text is pasted as plain text.\n//\n// clipboardTextParser:: ?(text: string, $context: ResolvedPos, plain: bool) → Slice\n// A function to parse text from the clipboard into a document\n// slice. Called after\n// [`transformPastedText`](#view.EditorProps.transformPastedText).\n// The default behavior is to split the text into lines, wrap them\n// in `

` tags, and call\n// [`clipboardParser`](#view.EditorProps.clipboardParser) on it.\n// The `plain` flag will be true when the text is pasted as plain text.\n//\n// transformPasted:: ?(Slice) → Slice\n// Can be used to transform pasted content before it is applied to\n// the document.\n//\n// nodeViews:: ?Object<(node: Node, view: EditorView, getPos: () → number, decorations: [Decoration]) → NodeView>\n// Allows you to pass custom rendering and behavior logic for nodes\n// and marks. Should map node and mark names to constructor\n// functions that produce a [`NodeView`](#view.NodeView) object\n// implementing the node's display behavior. For nodes, the third\n// argument `getPos` is a function that can be called to get the\n// node's current position, which can be useful when creating\n// transactions to update it. For marks, the third argument is a\n// boolean that indicates whether the mark's content is inline.\n//\n// `decorations` is an array of node or inline decorations that are\n// active around the node. They are automatically drawn in the\n// normal way, and you will usually just want to ignore this, but\n// they can also be used as a way to provide context information to\n// the node view without adding it to the document itself.\n//\n// clipboardSerializer:: ?DOMSerializer\n// The DOM serializer to use when putting content onto the\n// clipboard. If not given, the result of\n// [`DOMSerializer.fromSchema`](#model.DOMSerializer^fromSchema)\n// will be used.\n//\n// clipboardTextSerializer:: ?(Slice) → string\n// A function that will be called to get the text for the current\n// selection when copying text to the clipboard. By default, the\n// editor will use [`textBetween`](#model.Node.textBetween) on the\n// selected range.\n//\n// decorations:: ?(state: EditorState) → ?DecorationSet\n// A set of [document decorations](#view.Decoration) to show in the\n// view.\n//\n// editable:: ?(state: EditorState) → bool\n// When this returns false, the content of the view is not directly\n// editable.\n//\n// attributes:: ?union, (EditorState) → ?Object>\n// Control the DOM attributes of the editable element. May be either\n// an object or a function going from an editor state to an object.\n// By default, the element will get a class `\"ProseMirror\"`, and\n// will have its `contentEditable` attribute determined by the\n// [`editable` prop](#view.EditorProps.editable). Additional classes\n// provided here will be added to the class. For other attributes,\n// the value provided first (as in\n// [`someProp`](#view.EditorView.someProp)) will be used.\n//\n// scrollThreshold:: ?union\n// Determines the distance (in pixels) between the cursor and the\n// end of the visible viewport at which point, when scrolling the\n// cursor into view, scrolling takes place. Defaults to 0.\n//\n// scrollMargin:: ?union\n// Determines the extra space (in pixels) that is left above or\n// below the cursor when it is scrolled into view. Defaults to 5.\n\n// DirectEditorProps:: interface extends EditorProps\n//\n// The props object given directly to the editor view supports two\n// fields that can't be used in plugins:\n//\n// state:: EditorState\n// The current state of the editor.\n//\n// dispatchTransaction:: ?(tr: Transaction)\n// The callback over which to send transactions (state updates)\n// produced by the view. If you specify this, you probably want to\n// make sure this ends up calling the view's\n// [`updateState`](#view.EditorView.updateState) method with a new\n// state that has the transaction\n// [applied](#state.EditorState.apply). The callback will be bound to have\n// the view instance as its `this` binding.\n\nexport { Decoration, DecorationSet, EditorView, endComposition as __endComposition, parseFromClipboard as __parseFromClipboard, serializeForClipboard as __serializeForClipboard };\n//# sourceMappingURL=index.es.js.map\n","/**\n * Mutual exclude for JavaScript.\n *\n * @module mutex\n */\n\n/**\n * @callback mutex\n * @param {function():void} cb Only executed when this mutex is not in the current stack\n * @param {function():void} [elseCb] Executed when this mutex is in the current stack\n */\n\n/**\n * Creates a mutual exclude function with the following property:\n *\n * ```js\n * const mutex = createMutex()\n * mutex(() => {\n * // This function is immediately executed\n * mutex(() => {\n * // This function is not executed, as the mutex is already active.\n * })\n * })\n * ```\n *\n * @return {mutex} A mutual exclude function\n * @public\n */\nexport const createMutex = () => {\n let token = true\n return (f, g) => {\n if (token) {\n token = false\n try {\n f()\n } finally {\n token = true\n }\n } else if (g !== undefined) {\n g()\n }\n }\n}\n","\nimport { PluginKey } from 'prosemirror-state' // eslint-disable-line\n\n/**\n * The unique prosemirror plugin key for syncPlugin\n *\n * @public\n */\nexport const ySyncPluginKey = new PluginKey('y-sync')\n\n/**\n * The unique prosemirror plugin key for undoPlugin\n *\n * @public\n */\nexport const yUndoPluginKey = new PluginKey('y-undo')\n\n/**\n * The unique prosemirror plugin key for cursorPlugin\n *\n * @public\n */\nexport const yCursorPluginKey = new PluginKey('yjs-cursor')\n","/**\n * @module bindings/prosemirror\n */\n\nimport { createMutex } from 'lib0/mutex.js'\nimport { Node as PMNode, Slice as PMSlice, Fragment as PMFragment, Schema as PMSchema } from 'prosemirror-model'\nimport { Plugin, TextSelection } from 'prosemirror-state' // eslint-disable-line\nimport { min } from 'lib0/math.js'\nimport { keys } from 'lib0/object.js'\nimport { simpleDiff } from 'lib0/diff.js'\nimport { methodUnimplemented } from 'lib0/error.js'\nimport { ySyncPluginKey } from './keys.js'\nimport * as Y from 'yjs'\nimport { absolutePositionToRelativePosition, relativePositionToAbsolutePosition } from '../lib.js'\nimport { isBrowser } from 'lib0/environment.js'\nimport { doc } from 'lib0/dom.js'\n\n/**\n * @param {Y.Item} item\n * @param {Y.Snapshot} [snapshot]\n */\nexport const isVisible = (item, snapshot) => snapshot === undefined ? !item.deleted : (snapshot.sv.has(item.id.client) && /** @type {number} */ (snapshot.sv.get(item.id.client)) > item.id.clock && !Y.isDeleted(snapshot.ds, item.id))\n\n/**\n * Either a node if type is YXmlElement or an Array of text nodes if YXmlText\n * @typedef {Map>} ProsemirrorMapping\n */\n\n/**\n * @typedef {Object} ColorDef\n * @property {string} ColorDef.light\n * @property {string} ColorDef.dark\n */\n\n/**\n * @typedef {Object} YSyncOpts\n * @property {Array} [YSyncOpts.colors]\n * @property {Map} [YSyncOpts.colorMapping]\n * @property {Y.PermanentUserData|null} [YSyncOpts.permanentUserData]\n */\n\n/**\n * @type {Array}\n */\nconst defaultColors = [{ light: '#ecd44433', dark: '#ecd444' }]\n\n/**\n * @param {Map} colorMapping\n * @param {Array} colors\n * @param {string} user\n * @return {ColorDef}\n */\nconst getUserColor = (colorMapping, colors, user) => {\n if (!colorMapping.has(user)) {\n colorMapping.set(user, colors[colorMapping.size % colors.length]);\n }\n return /** @type {ColorDef} */ (colorMapping.get(user));\n}\n\n/**\n * This plugin listens to changes in prosemirror view and keeps yXmlState and view in sync.\n *\n * This plugin also keeps references to the type and the shared document so other plugins can access it.\n * @param {Y.XmlFragment} yXmlFragment\n * @param {YSyncOpts} opts\n * @return {any} Returns a prosemirror plugin that binds to this type\n */\nexport const ySyncPlugin = (yXmlFragment, { colors = defaultColors, colorMapping = new Map(), permanentUserData = null } = {}) => {\n let changedInitialContent = false\n const plugin = new Plugin({\n props: {\n editable: (state) => {\n const syncState = ySyncPluginKey.getState(state)\n return syncState.snapshot == null && syncState.prevSnapshot == null\n }\n },\n key: ySyncPluginKey,\n state: {\n init: (initargs, state) => {\n return {\n type: yXmlFragment,\n doc: yXmlFragment.doc,\n binding: null,\n snapshot: null,\n prevSnapshot: null,\n isChangeOrigin: false,\n colors,\n colorMapping,\n permanentUserData\n }\n },\n apply: (tr, pluginState) => {\n const change = tr.getMeta(ySyncPluginKey)\n if (change !== undefined) {\n pluginState = Object.assign({}, pluginState)\n for (const key in change) {\n pluginState[key] = change[key]\n }\n }\n // always set isChangeOrigin. If undefined, this is not change origin.\n pluginState.isChangeOrigin = change !== undefined && !!change.isChangeOrigin\n if (pluginState.binding !== null) {\n if (change !== undefined && (change.snapshot != null || change.prevSnapshot != null)) {\n // snapshot changed, rerender next\n setTimeout(() => {\n if (change.restore == null) {\n pluginState.binding._renderSnapshot(change.snapshot, change.prevSnapshot, pluginState)\n } else {\n pluginState.binding._renderSnapshot(change.snapshot, change.snapshot, pluginState)\n // reset to current prosemirror state\n delete pluginState.restore\n delete pluginState.snapshot\n delete pluginState.prevSnapshot\n pluginState.binding._prosemirrorChanged(pluginState.binding.prosemirrorView.state.doc)\n }\n }, 0)\n }\n }\n return pluginState\n }\n },\n view: view => {\n\n const binding = new ProsemirrorBinding(yXmlFragment, view);\n binding._forceRerender();\n view.dispatch(view.state.tr.setMeta(ySyncPluginKey, { binding }));\n\n return {\n update: () => {\n const pluginState = plugin.getState(view.state)\n if (pluginState.snapshot == null && pluginState.prevSnapshot == null) {\n if (changedInitialContent || view.state.doc.content.findDiffStart(view.state.doc.type.createAndFill().content) != null) {\n changedInitialContent = true\n binding._prosemirrorChanged(view.state.doc)\n }\n }\n },\n destroy: () => {\n binding.destroy()\n }\n }\n }\n })\n return plugin\n}\n\n/**\n * @param {any} tr\n * @param {any} relSel\n * @param {ProsemirrorBinding} binding\n */\nconst restoreRelativeSelection = (tr, relSel, binding) => {\n if (relSel !== null && relSel.anchor !== null && relSel.head !== null) {\n const anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping)\n const head = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.head, binding.mapping)\n if (anchor !== null && head !== null) {\n tr = tr.setSelection(TextSelection.create(tr.doc, anchor, head))\n }\n }\n}\n\nexport const getRelativeSelection = (pmbinding, state) => ({\n anchor: absolutePositionToRelativePosition(state.selection.anchor, pmbinding.type, pmbinding.mapping),\n head: absolutePositionToRelativePosition(state.selection.head, pmbinding.type, pmbinding.mapping)\n})\n\n/**\n * Binding for prosemirror.\n *\n * @protected\n */\nexport class ProsemirrorBinding {\n /**\n * @param {Y.XmlFragment} yXmlFragment The bind source\n * @param {any} prosemirrorView The target binding\n */\n constructor (yXmlFragment, prosemirrorView) {\n this.type = yXmlFragment\n this.prosemirrorView = prosemirrorView\n this.mux = createMutex()\n /**\n * @type {ProsemirrorMapping}\n */\n this.mapping = new Map()\n this._observeFunction = this._typeChanged.bind(this)\n /**\n * @type {Y.Doc}\n */\n // @ts-ignore\n this.doc = yXmlFragment.doc\n /**\n * current selection as relative positions in the Yjs model\n */\n this.beforeTransactionSelection = null\n this.beforeAllTransactions = () => {\n if (this.beforeTransactionSelection === null) {\n this.beforeTransactionSelection = getRelativeSelection(this, prosemirrorView.state)\n }\n }\n this.afterAllTransactions = () => {\n this.beforeTransactionSelection = null\n }\n\n this.doc.on('beforeAllTransactions', this.beforeAllTransactions)\n this.doc.on('afterAllTransactions', this.afterAllTransactions)\n yXmlFragment.observeDeep(this._observeFunction)\n\n this._domSelectionInView = null\n }\n\n _isLocalCursorInView () {\n if (!this.prosemirrorView.hasFocus()) return false\n if (isBrowser && this._domSelectionInView === null) {\n // Calculate the domSelectionInView and clear by next tick after all events are finished\n setTimeout(() => {\n this._domSelectionInView = null\n }, 0)\n this._domSelectionInView = this._isDomSelectionInView()\n }\n return this._domSelectionInView\n }\n\n _isDomSelectionInView () {\n const selection = this.prosemirrorView._root.getSelection()\n\n const range = this.prosemirrorView._root.createRange()\n range.setStart(selection.anchorNode, selection.anchorOffset)\n range.setEnd(selection.focusNode, selection.focusOffset)\n\n // This is a workaround for an edgecase where getBoundingClientRect will\n // return zero values if the selection is collapsed at the start of a newline\n // see reference here: https://stackoverflow.com/a/59780954\n const rects = range.getClientRects()\n if (rects.length === 0) {\n // probably buggy newline behavior, explicitly select the node contents\n if (range.startContainer && range.collapsed) {\n range.selectNodeContents(range.startContainer)\n }\n }\n\n const bounding = range.getBoundingClientRect()\n const documentElement = doc.documentElement\n\n return bounding.bottom >= 0 && bounding.right >= 0 &&\n bounding.left <= (window.innerWidth || documentElement.clientWidth || 0) &&\n bounding.top <= (window.innerHeight || documentElement.clientHeight || 0)\n }\n\n renderSnapshot (snapshot, prevSnapshot) {\n if (!prevSnapshot) {\n prevSnapshot = Y.createSnapshot(Y.createDeleteSet(), new Map())\n }\n this.prosemirrorView.dispatch(this.prosemirrorView.state.tr.setMeta(ySyncPluginKey, { snapshot, prevSnapshot }))\n }\n\n unrenderSnapshot () {\n this.mapping = new Map()\n this.mux(() => {\n const fragmentContent = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null)\n // @ts-ignore\n const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new PMSlice(new PMFragment(fragmentContent), 0, 0))\n tr.setMeta(ySyncPluginKey, { snapshot: null, prevSnapshot: null })\n this.prosemirrorView.dispatch(tr)\n })\n }\n\n _forceRerender () {\n this.mapping = new Map()\n this.mux(() => {\n let content = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null);\n if (content.length) {\n // @ts-ignore\n const tr = this.prosemirrorView.state.tr.replaceWith(0, this.prosemirrorView.state.doc.content.size, new PMFragment(content));\n this.prosemirrorView.dispatch(tr);\n }\n })\n }\n\n /**\n * @param {Y.Snapshot} snapshot\n * @param {Y.Snapshot} prevSnapshot\n * @param {Object} pluginState\n */\n _renderSnapshot (snapshot, prevSnapshot, pluginState) {\n if (!snapshot) {\n snapshot = Y.snapshot(this.doc)\n }\n // clear mapping because we are going to rerender\n this.mapping = new Map()\n this.mux(() => {\n this.doc.transact(transaction => {\n // before rendering, we are going to sanitize ops and split deleted ops\n // if they were deleted by seperate users.\n const pud = pluginState.permanentUserData\n if (pud) {\n pud.dss.forEach(ds => {\n Y.iterateDeletedStructs(transaction, ds, item => {})\n })\n }\n const computeYChange = (type, id) => {\n const user = type === 'added' ? pud.getUserByClientId(id.client) : pud.getUserByDeletedId(id)\n return {\n user,\n type,\n color: getUserColor(pluginState.colorMapping, pluginState.colors, user)\n }\n }\n // Create document fragment and render\n const fragmentContent = Y.typeListToArraySnapshot(this.type, new Y.Snapshot(prevSnapshot.ds, snapshot.sv)).map(t => {\n if (!t._item.deleted || isVisible(t._item, snapshot) || isVisible(t._item, prevSnapshot)) {\n return createNodeFromYElement(t, this.prosemirrorView.state.schema, new Map(), snapshot, prevSnapshot, computeYChange)\n } else {\n // No need to render elements that are not visible by either snapshot.\n // If a client adds and deletes content in the same snapshot the element is not visible by either snapshot.\n return null\n }\n }).filter(n => n !== null)\n // @ts-ignore\n const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new PMSlice(new PMFragment(fragmentContent), 0, 0))\n this.prosemirrorView.dispatch(tr)\n }, ySyncPluginKey)\n })\n }\n\n /**\n * @param {Array} events\n * @param {Y.Transaction} transaction\n */\n _typeChanged (events, transaction) {\n const syncState = ySyncPluginKey.getState(this.prosemirrorView.state)\n if (events.length === 0 || syncState.snapshot != null || syncState.prevSnapshot != null) {\n // drop out if snapshot is active\n this.renderSnapshot(syncState.snapshot, syncState.prevSnapshot)\n return\n }\n this.mux(() => {\n /**\n * @param {any} _\n * @param {Y.AbstractType} type\n */\n const delType = (_, type) => this.mapping.delete(type)\n Y.iterateDeletedStructs(transaction, transaction.deleteSet, struct => struct.constructor === Y.Item && this.mapping.delete(/** @type {Y.ContentType} */ (/** @type {Y.Item} */ (struct).content).type))\n transaction.changed.forEach(delType)\n transaction.changedParentTypes.forEach(delType)\n const fragmentContent = this.type.toArray().map(t => createNodeIfNotExists(/** @type {Y.XmlElement | Y.XmlHook} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null)\n // @ts-ignore\n let tr = this.prosemirrorView.state.tr.replaceWith(0, this.prosemirrorView.state.doc.content.size, new PMFragment(fragmentContent));\n restoreRelativeSelection(tr, this.beforeTransactionSelection, this)\n tr = tr.setMeta(ySyncPluginKey, { isChangeOrigin: true })\n if (this.beforeTransactionSelection !== null && this._isLocalCursorInView()) {\n tr.scrollIntoView()\n }\n this.prosemirrorView.dispatch(tr)\n })\n }\n\n _prosemirrorChanged (doc) {\n this.mux(() => {\n this.doc.transact(() => {\n updateYFragment(this.doc, this.type, doc, this.mapping)\n this.beforeTransactionSelection = getRelativeSelection(this, this.prosemirrorView.state)\n }, ySyncPluginKey)\n })\n }\n\n destroy () {\n this.type.unobserveDeep(this._observeFunction)\n this.doc.off('beforeAllTransactions', this.beforeAllTransactions)\n this.doc.off('afterAllTransactions', this.afterAllTransactions)\n }\n}\n\n/**\n * @private\n * @param {Y.XmlElement | Y.XmlHook} el\n * @param {PMSchema} schema\n * @param {ProsemirrorMapping} mapping\n * @param {Y.Snapshot} [snapshot]\n * @param {Y.Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', Y.ID):any} [computeYChange]\n * @return {PMNode | null}\n */\nconst createNodeIfNotExists = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => {\n const node = /** @type {PMNode} */ (mapping.get(el))\n if (node === undefined) {\n if (el instanceof Y.XmlElement) {\n return createNodeFromYElement(el, schema, mapping, snapshot, prevSnapshot, computeYChange)\n } else {\n throw methodUnimplemented() // we are currently not handling hooks\n }\n }\n return node\n}\n\n/**\n * @private\n * @param {Y.XmlElement} el\n * @param {any} schema\n * @param {ProsemirrorMapping} mapping\n * @param {Y.Snapshot} [snapshot]\n * @param {Y.Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', Y.ID):any} [computeYChange]\n * @return {PMNode | null} Returns node if node could be created. Otherwise it deletes the yjs type and returns null\n */\nconst createNodeFromYElement = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => {\n const children = []\n const createChildren = type => {\n if (type.constructor === Y.XmlElement) {\n const n = createNodeIfNotExists(type, schema, mapping, snapshot, prevSnapshot, computeYChange)\n if (n !== null) {\n children.push(n)\n }\n } else {\n const ns = createTextNodesFromYText(type, schema, mapping, snapshot, prevSnapshot, computeYChange)\n if (ns !== null) {\n ns.forEach(textchild => {\n if (textchild !== null) {\n children.push(textchild)\n }\n })\n }\n }\n }\n if (snapshot === undefined || prevSnapshot === undefined) {\n el.toArray().forEach(createChildren)\n } else {\n Y.typeListToArraySnapshot(el, new Y.Snapshot(prevSnapshot.ds, snapshot.sv)).forEach(createChildren)\n }\n try {\n const attrs = el.getAttributes(snapshot)\n if (snapshot !== undefined) {\n if (!isVisible(/** @type {Y.Item} */ (el._item), snapshot)) {\n attrs.ychange = computeYChange ? computeYChange('removed', /** @type {Y.Item} */ (el._item).id) : { type: 'removed' }\n } else if (!isVisible(/** @type {Y.Item} */ (el._item), prevSnapshot)) {\n attrs.ychange = computeYChange ? computeYChange('added', /** @type {Y.Item} */ (el._item).id) : { type: 'added' }\n }\n }\n const node = schema.node(el.nodeName, attrs, children)\n mapping.set(el, node)\n return node\n } catch (e) {\n // an error occured while creating the node. This is probably a result of a concurrent action.\n /** @type {Y.Doc} */ (el.doc).transact(transaction => {\n /** @type {Y.Item} */ (el._item).delete(transaction)\n }, ySyncPluginKey)\n mapping.delete(el)\n return null\n }\n}\n\n/**\n * @private\n * @param {Y.XmlText} text\n * @param {any} schema\n * @param {ProsemirrorMapping} mapping\n * @param {Y.Snapshot} [snapshot]\n * @param {Y.Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', Y.ID):any} [computeYChange]\n * @return {Array|null}\n */\nconst createTextNodesFromYText = (text, schema, mapping, snapshot, prevSnapshot, computeYChange) => {\n const nodes = []\n const deltas = text.toDelta(snapshot, prevSnapshot, computeYChange)\n try {\n for (let i = 0; i < deltas.length; i++) {\n const delta = deltas[i]\n const marks = []\n for (const markName in delta.attributes) {\n marks.push(schema.mark(markName, delta.attributes[markName]))\n }\n nodes.push(schema.text(delta.insert, marks))\n }\n } catch (e) {\n // an error occured while creating the node. This is probably a result of a concurrent action.\n /** @type {Y.Doc} */ (text.doc).transact(transaction => {\n /** @type {Y.Item} */ (text._item).delete(transaction)\n }, ySyncPluginKey)\n return null\n }\n // @ts-ignore\n return nodes\n}\n\n/**\n * @private\n * @param {Array} nodes prosemirror node\n * @param {ProsemirrorMapping} mapping\n * @return {Y.XmlText}\n */\nconst createTypeFromTextNodes = (nodes, mapping) => {\n const type = new Y.XmlText()\n const delta = nodes.map(node => ({\n // @ts-ignore\n insert: node.text,\n attributes: marksToAttributes(node.marks)\n }))\n type.applyDelta(delta)\n mapping.set(type, nodes)\n return type\n}\n\n/**\n * @private\n * @param {any} node prosemirror node\n * @param {ProsemirrorMapping} mapping\n * @return {Y.XmlElement}\n */\nconst createTypeFromElementNode = (node, mapping) => {\n const type = new Y.XmlElement(node.type.name)\n for (const key in node.attrs) {\n const val = node.attrs[key]\n if (val !== null && key !== 'ychange') {\n type.setAttribute(key, val)\n }\n }\n type.insert(0, normalizePNodeContent(node).map(n => createTypeFromTextOrElementNode(n, mapping)))\n mapping.set(type, node)\n return type\n}\n\n/**\n * @private\n * @param {PMNode|Array} node prosemirror text node\n * @param {ProsemirrorMapping} mapping\n * @return {Y.XmlElement|Y.XmlText}\n */\nconst createTypeFromTextOrElementNode = (node, mapping) => node instanceof Array ? createTypeFromTextNodes(node, mapping) : createTypeFromElementNode(node, mapping)\n\nconst equalAttrs = (pattrs, yattrs) => {\n const keys = Object.keys(pattrs).filter(key => pattrs[key] !== null)\n let eq = keys.length === Object.keys(yattrs).filter(key => yattrs[key] !== null).length\n for (let i = 0; i < keys.length && eq; i++) {\n const key = keys[i]\n const l = pattrs[key]\n const r = yattrs[key]\n eq = key === 'ychange' || l === r || (typeof l === 'object' && typeof r === 'object' && equalAttrs(l, r))\n }\n return eq\n}\n\n/**\n * @typedef {Array|PMNode>} NormalizedPNodeContent\n */\n\n/**\n * @param {any} pnode\n * @return {NormalizedPNodeContent}\n */\nconst normalizePNodeContent = pnode => {\n const c = pnode.content.content\n const res = []\n for (let i = 0; i < c.length; i++) {\n const n = c[i]\n if (n.isText) {\n const textNodes = []\n for (let tnode = c[i]; i < c.length && tnode.isText; tnode = c[++i]) {\n textNodes.push(tnode)\n }\n i--\n res.push(textNodes)\n } else {\n res.push(n)\n }\n }\n return res\n}\n\n/**\n * @param {Y.XmlText} ytext\n * @param {Array} ptexts\n */\nconst equalYTextPText = (ytext, ptexts) => {\n const delta = ytext.toDelta()\n return delta.length === ptexts.length && delta.every((d, i) => d.insert === /** @type {any} */ (ptexts[i]).text && keys(d.attributes || {}).length === ptexts[i].marks.length && ptexts[i].marks.every(mark => equalAttrs(d.attributes[mark.type.name] || {}, mark.attrs)))\n}\n\n/**\n * @param {Y.XmlElement|Y.XmlText|Y.XmlHook} ytype\n * @param {any|Array} pnode\n */\nconst equalYTypePNode = (ytype, pnode) => {\n if (ytype instanceof Y.XmlElement && !(pnode instanceof Array) && matchNodeName(ytype, pnode)) {\n const normalizedContent = normalizePNodeContent(pnode)\n return ytype._length === normalizedContent.length && equalAttrs(ytype.getAttributes(), pnode.attrs) && ytype.toArray().every((ychild, i) => equalYTypePNode(ychild, normalizedContent[i]))\n }\n return ytype instanceof Y.XmlText && pnode instanceof Array && equalYTextPText(ytype, pnode)\n}\n\n/**\n * @param {PMNode | Array | undefined} mapped\n * @param {PMNode | Array} pcontent\n */\nconst mappedIdentity = (mapped, pcontent) => mapped === pcontent || (mapped instanceof Array && pcontent instanceof Array && mapped.length === pcontent.length && mapped.every((a, i) => pcontent[i] === a))\n\n/**\n * @param {Y.XmlElement} ytype\n * @param {PMNode} pnode\n * @param {ProsemirrorMapping} mapping\n * @return {{ foundMappedChild: boolean, equalityFactor: number }}\n */\nconst computeChildEqualityFactor = (ytype, pnode, mapping) => {\n const yChildren = ytype.toArray()\n const pChildren = normalizePNodeContent(pnode)\n const pChildCnt = pChildren.length\n const yChildCnt = yChildren.length\n const minCnt = min(yChildCnt, pChildCnt)\n let left = 0\n let right = 0\n let foundMappedChild = false\n for (; left < minCnt; left++) {\n const leftY = yChildren[left]\n const leftP = pChildren[left]\n if (mappedIdentity(mapping.get(leftY), leftP)) {\n foundMappedChild = true// definite (good) match!\n } else if (!equalYTypePNode(leftY, leftP)) {\n break\n }\n }\n for (; left + right < minCnt; right++) {\n const rightY = yChildren[yChildCnt - right - 1]\n const rightP = pChildren[pChildCnt - right - 1]\n if (mappedIdentity(mapping.get(rightY), rightP)) {\n foundMappedChild = true\n } else if (!equalYTypePNode(rightY, rightP)) {\n break\n }\n }\n return {\n equalityFactor: left + right,\n foundMappedChild\n }\n}\n\nconst ytextTrans = ytext => {\n let str = ''\n /**\n * @type {Y.Item|null}\n */\n let n = ytext._start\n const nAttrs = {}\n while (n !== null) {\n if (!n.deleted) {\n if (n.countable && n.content instanceof Y.ContentString) {\n str += n.content.str\n } else if (n.content instanceof Y.ContentFormat) {\n nAttrs[n.content.key] = null\n }\n }\n n = n.right\n }\n return {\n str,\n nAttrs\n }\n}\n\n/**\n * @todo test this more\n *\n * @param {Y.Text} ytext\n * @param {Array} ptexts\n * @param {ProsemirrorMapping} mapping\n */\nconst updateYText = (ytext, ptexts, mapping) => {\n mapping.set(ytext, ptexts)\n const { nAttrs, str } = ytextTrans(ytext)\n const content = ptexts.map(p => ({ insert: /** @type {any} */ (p).text, attributes: Object.assign({}, nAttrs, marksToAttributes(p.marks)) }))\n const { insert, remove, index } = simpleDiff(str, content.map(c => c.insert).join(''))\n ytext.delete(index, remove)\n ytext.insert(index, insert)\n ytext.applyDelta(content.map(c => ({ retain: c.insert.length, attributes: c.attributes })))\n}\n\nconst marksToAttributes = marks => {\n const pattrs = {}\n marks.forEach(mark => {\n if (mark.type.name !== 'ychange') {\n pattrs[mark.type.name] = mark.attrs\n }\n })\n return pattrs\n}\n\n/**\n * @private\n * @param {Y.Doc} y\n * @param {Y.XmlFragment} yDomFragment\n * @param {any} pNode\n * @param {ProsemirrorMapping} mapping\n */\nexport const updateYFragment = (y, yDomFragment, pNode, mapping) => {\n if (yDomFragment instanceof Y.XmlElement && yDomFragment.nodeName !== pNode.type.name) {\n throw new Error('node name mismatch!')\n }\n mapping.set(yDomFragment, pNode)\n // update attributes\n if (yDomFragment instanceof Y.XmlElement) {\n const yDomAttrs = yDomFragment.getAttributes()\n const pAttrs = pNode.attrs\n for (const key in pAttrs) {\n if (pAttrs[key] !== null) {\n if (yDomAttrs[key] !== pAttrs[key] && key !== 'ychange') {\n yDomFragment.setAttribute(key, pAttrs[key])\n }\n } else {\n yDomFragment.removeAttribute(key)\n }\n }\n // remove all keys that are no longer in pAttrs\n for (const key in yDomAttrs) {\n if (pAttrs[key] === undefined) {\n yDomFragment.removeAttribute(key)\n }\n }\n }\n // update children\n const pChildren = normalizePNodeContent(pNode)\n const pChildCnt = pChildren.length\n const yChildren = yDomFragment.toArray()\n const yChildCnt = yChildren.length\n const minCnt = min(pChildCnt, yChildCnt)\n let left = 0\n let right = 0\n // find number of matching elements from left\n for (;left < minCnt; left++) {\n const leftY = yChildren[left]\n const leftP = pChildren[left]\n if (!mappedIdentity(mapping.get(leftY), leftP)) {\n if (equalYTypePNode(leftY, leftP)) {\n // update mapping\n mapping.set(leftY, leftP)\n } else {\n break\n }\n }\n }\n // find number of matching elements from right\n for (;right + left + 1 < minCnt; right++) {\n const rightY = yChildren[yChildCnt - right - 1]\n const rightP = pChildren[pChildCnt - right - 1]\n if (!mappedIdentity(mapping.get(rightY), rightP)) {\n if (equalYTypePNode(rightY, rightP)) {\n // update mapping\n mapping.set(rightY, rightP)\n } else {\n break\n }\n }\n }\n y.transact(() => {\n // try to compare and update\n while (yChildCnt - left - right > 0 && pChildCnt - left - right > 0) {\n const leftY = yChildren[left]\n const leftP = pChildren[left]\n const rightY = yChildren[yChildCnt - right - 1]\n const rightP = pChildren[pChildCnt - right - 1]\n if (leftY instanceof Y.XmlText && leftP instanceof Array) {\n if (!equalYTextPText(leftY, leftP)) {\n updateYText(leftY, leftP, mapping)\n }\n left += 1\n } else {\n let updateLeft = leftY instanceof Y.XmlElement && matchNodeName(leftY, leftP)\n let updateRight = rightY instanceof Y.XmlElement && matchNodeName(rightY, rightP)\n if (updateLeft && updateRight) {\n // decide which which element to update\n const equalityLeft = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (leftY), /** @type {PMNode} */ (leftP), mapping)\n const equalityRight = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (rightY), /** @type {PMNode} */ (rightP), mapping)\n if (equalityLeft.foundMappedChild && !equalityRight.foundMappedChild) {\n updateRight = false\n } else if (!equalityLeft.foundMappedChild && equalityRight.foundMappedChild) {\n updateLeft = false\n } else if (equalityLeft.equalityFactor < equalityRight.equalityFactor) {\n updateLeft = false\n } else {\n updateRight = false\n }\n }\n if (updateLeft) {\n updateYFragment(y, /** @type {Y.XmlFragment} */ (leftY), /** @type {PMNode} */ (leftP), mapping)\n left += 1\n } else if (updateRight) {\n updateYFragment(y, /** @type {Y.XmlFragment} */ (rightY), /** @type {PMNode} */ (rightP), mapping)\n right += 1\n } else {\n yDomFragment.delete(left, 1)\n yDomFragment.insert(left, [createTypeFromTextOrElementNode(leftP, mapping)])\n left += 1\n }\n }\n }\n const yDelLen = yChildCnt - left - right\n if (yDelLen > 0) {\n yDomFragment.delete(left, yDelLen)\n }\n if (left + right < pChildCnt) {\n const ins = []\n for (let i = left; i < pChildCnt - right; i++) {\n ins.push(createTypeFromTextOrElementNode(pChildren[i], mapping))\n }\n yDomFragment.insert(left, ins)\n }\n }, ySyncPluginKey)\n}\n\n/**\n * @function\n * @param {Y.XmlElement} yElement\n * @param {any} pNode Prosemirror Node\n */\nconst matchNodeName = (yElement, pNode) => !(pNode instanceof Array) && yElement.nodeName === pNode.type.name\n","import { updateYFragment } from './plugins/sync-plugin.js' // eslint-disable-line\nimport * as Y from 'yjs'\nimport { EditorView } from 'prosemirror-view' // eslint-disable-line\nimport { Node, Schema } from 'prosemirror-model' // eslint-disable-line\nimport * as error from 'lib0/error.js'\nimport * as map from 'lib0/map.js'\nimport * as eventloop from 'lib0/eventloop.js'\n\n/**\n * Either a node if type is YXmlElement or an Array of text nodes if YXmlText\n * @typedef {Map>} ProsemirrorMapping\n */\n\n/**\n * Is null if no timeout is in progress.\n * Is defined if a timeout is in progress.\n * Maps from view\n * @type {Map>|null}\n */\nlet viewsToUpdate = null\n\nconst updateMetas = () => {\n const ups = /** @type {Map>} */ (viewsToUpdate)\n viewsToUpdate = null\n ups.forEach((metas, view) => {\n const tr = view.state.tr\n metas.forEach((val, key) => {\n tr.setMeta(key, val)\n })\n view.dispatch(tr)\n })\n}\n\nexport const setMeta = (view, key, value) => {\n if (!viewsToUpdate) {\n viewsToUpdate = new Map()\n eventloop.timeout(0, updateMetas)\n }\n map.setIfUndefined(viewsToUpdate, view, map.create).set(key, value)\n}\n\n/**\n * Transforms a Prosemirror based absolute position to a Yjs Cursor (relative position in the Yjs model).\n *\n * @param {number} pos\n * @param {Y.XmlFragment} type\n * @param {ProsemirrorMapping} mapping\n * @return {any} relative position\n */\nexport const absolutePositionToRelativePosition = (pos, type, mapping) => {\n if (pos === 0) {\n return Y.createRelativePositionFromTypeIndex(type, 0)\n }\n let n = type._first === null ? null : /** @type {Y.ContentType} */ (type._first.content).type\n while (n !== null && type !== n) {\n if (n.constructor === Y.XmlText) {\n if (n._length >= pos) {\n return Y.createRelativePositionFromTypeIndex(n, pos)\n } else {\n pos -= n._length\n }\n if (n._item !== null && n._item.next !== null) {\n n = /** @type {Y.ContentType} */ (n._item.next.content).type\n } else {\n do {\n n = n._item === null ? null : n._item.parent\n pos--\n } while (n !== type && n !== null && n._item !== null && n._item.next === null)\n if (n !== null && n !== type) {\n // @ts-gnore we know that n.next !== null because of above loop conditition\n n = n._item === null ? null : /** @type {Y.ContentType} */ (/** @type Y.Item */ (n._item.next).content).type\n }\n }\n } else {\n const pNodeSize = /** @type {any} */ (mapping.get(n) || { nodeSize: 0 }).nodeSize\n if (n._first !== null && pos < pNodeSize) {\n n = /** @type {Y.ContentType} */ (n._first.content).type\n pos--\n } else {\n if (pos === 1 && n._length === 0 && pNodeSize > 1) {\n // edge case, should end in this paragraph\n return new Y.RelativePosition(n._item === null ? null : n._item.id, n._item === null ? Y.findRootTypeKey(n) : null, null)\n }\n pos -= pNodeSize\n if (n._item !== null && n._item.next !== null) {\n n = /** @type {Y.ContentType} */ (n._item.next.content).type\n } else {\n if (pos === 0) {\n // set to end of n.parent\n n = n._item === null ? n : n._item.parent\n return new Y.RelativePosition(n._item === null ? null : n._item.id, n._item === null ? Y.findRootTypeKey(n) : null, null)\n }\n do {\n n = /** @type {Y.Item} */ (n._item).parent\n pos--\n } while (n !== type && /** @type {Y.Item} */ (n._item).next === null)\n // if n is null at this point, we have an unexpected case\n if (n !== type) {\n // We know that n._item.next is defined because of above loop condition\n n = /** @type {Y.ContentType} */ (/** @type {Y.Item} */ (/** @type {Y.Item} */ (n._item).next).content).type\n }\n }\n }\n }\n if (n === null) {\n throw error.unexpectedCase()\n }\n if (pos === 0 && n.constructor !== Y.XmlText && n !== type) { // TODO: set to <= 0\n return createRelativePosition(n._item.parent, n._item)\n }\n }\n return Y.createRelativePositionFromTypeIndex(type, type._length)\n}\n\nconst createRelativePosition = (type, item) => {\n let typeid = null\n let tname = null\n if (type._item === null) {\n tname = Y.findRootTypeKey(type)\n } else {\n typeid = Y.createID(type._item.id.client, type._item.id.clock)\n }\n return new Y.RelativePosition(typeid, tname, item.id)\n}\n\n/**\n * @param {Y.Doc} y\n * @param {Y.XmlFragment} documentType Top level type that is bound to pView\n * @param {any} relPos Encoded Yjs based relative position\n * @param {ProsemirrorMapping} mapping\n * @return {null|number}\n */\nexport const relativePositionToAbsolutePosition = (y, documentType, relPos, mapping) => {\n const decodedPos = Y.createAbsolutePositionFromRelativePosition(relPos, y)\n if (decodedPos === null || (decodedPos.type !== documentType && !Y.isParentOf(documentType, decodedPos.type._item))) {\n return null\n }\n let type = decodedPos.type\n let pos = 0\n if (type.constructor === Y.XmlText) {\n pos = decodedPos.index\n } else if (type._item === null || !type._item.deleted) {\n let n = type._first\n let i = 0\n while (i < type._length && i < decodedPos.index && n !== null) {\n if (!n.deleted) {\n const t = /** @type {Y.ContentType} */ (n.content).type\n i++\n if (t.constructor === Y.XmlText) {\n pos += t._length\n } else {\n pos += /** @type {any} */ (mapping.get(t)).nodeSize\n }\n }\n n = /** @type {Y.Item} */ (n.right)\n }\n pos += 1 // increase because we go out of n\n }\n while (type !== documentType && type._item !== null) {\n // @ts-ignore\n const parent = type._item.parent\n // @ts-ignore\n if (parent._item === null || !parent._item.deleted) {\n pos += 1 // the start tag\n let n = parent._first\n // now iterate until we found type\n while (n !== null) {\n const contentType = /** @type {Y.ContentType} */ (n.content).type\n if (contentType === type) {\n break\n }\n if (!n.deleted) {\n if (contentType.constructor === Y.XmlText) {\n pos += contentType._length\n } else {\n pos += /** @type {any} */ (mapping.get(contentType)).nodeSize\n }\n }\n n = n.right\n }\n }\n type = parent\n }\n return pos - 1 // we don't count the most outer tag, because it is a fragment\n}\n\n/**\n * Utility method to convert a Prosemirror Doc Node into a Y.Doc.\n *\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param {Node} doc\n * @param {string} xmlFragment\n * @return {Y.Doc}\n */\nexport function prosemirrorToYDoc (doc, xmlFragment = 'prosemirror') {\n const ydoc = new Y.Doc()\n const type = ydoc.get(xmlFragment, Y.XmlFragment)\n if (!type.doc) {\n return ydoc\n }\n\n updateYFragment(type.doc, type, doc, new Map())\n return type.doc\n}\n\n/**\n * Utility method to convert Prosemirror compatible JSON into a Y.Doc.\n *\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param {Schema} schema\n * @param {any} state\n * @param {string} xmlFragment\n * @return {Y.Doc}\n */\nexport function prosemirrorJSONToYDoc (schema, state, xmlFragment = 'prosemirror') {\n const doc = Node.fromJSON(schema, state)\n return prosemirrorToYDoc(doc, xmlFragment)\n}\n\n/**\n * Utility method to convert a Y.Doc to a Prosemirror Doc node.\n *\n * @param {Schema} schema\n * @param {Y.Doc} ydoc\n * @return {Node}\n */\nexport function yDocToProsemirror (schema, ydoc) {\n const state = yDocToProsemirrorJSON(ydoc)\n return Node.fromJSON(schema, state)\n}\n\n/**\n * Utility method to convert a Y.Doc to Prosemirror compatible JSON.\n *\n * @param {Y.Doc} ydoc\n * @param {string} xmlFragment\n * @return {Record}\n */\nexport function yDocToProsemirrorJSON (\n ydoc,\n xmlFragment = 'prosemirror'\n) {\n const items = ydoc.getXmlFragment(xmlFragment).toArray()\n\n function serialize (item) {\n /**\n * @type {Object} NodeObject\n * @property {string} NodeObject.type\n * @property {Record=} NodeObject.attrs\n * @property {Array=} NodeObject.content\n */\n let response\n\n // TODO: Must be a better way to detect text nodes than this\n if (!item.nodeName) {\n const delta = item.toDelta()\n response = delta.map((d) => {\n const text = {\n type: 'text',\n text: d.insert\n }\n\n if (d.attributes) {\n text.marks = Object.keys(d.attributes).map((type) => {\n const attrs = d.attributes[type]\n const mark = {\n type\n }\n\n if (Object.keys(attrs)) {\n mark.attrs = attrs\n }\n\n return mark\n })\n }\n return text\n })\n } else {\n response = {\n type: item.nodeName\n }\n\n const attrs = item.getAttributes()\n if (Object.keys(attrs).length) {\n response.attrs = attrs\n }\n\n const children = item.toArray()\n if (children.length) {\n response.content = children.map(serialize).flat()\n }\n }\n\n return response\n }\n\n return {\n type: 'doc',\n content: items.map(serialize)\n }\n}\n","import { Schema } from 'prosemirror-model';\n\nvar pDOM = [\"p\", 0], blockquoteDOM = [\"blockquote\", 0], hrDOM = [\"hr\"],\n preDOM = [\"pre\", [\"code\", 0]], brDOM = [\"br\"];\n\n// :: Object\n// [Specs](#model.NodeSpec) for the nodes defined in this schema.\nvar nodes = {\n // :: NodeSpec The top level document node.\n doc: {\n content: \"block+\"\n },\n\n // :: NodeSpec A plain paragraph textblock. Represented in the DOM\n // as a `

` element.\n paragraph: {\n content: \"inline*\",\n group: \"block\",\n parseDOM: [{tag: \"p\"}],\n toDOM: function toDOM() { return pDOM }\n },\n\n // :: NodeSpec A blockquote (`

`) wrapping one or more blocks.\n blockquote: {\n content: \"block+\",\n group: \"block\",\n defining: true,\n parseDOM: [{tag: \"blockquote\"}],\n toDOM: function toDOM() { return blockquoteDOM }\n },\n\n // :: NodeSpec A horizontal rule (`
`).\n horizontal_rule: {\n group: \"block\",\n parseDOM: [{tag: \"hr\"}],\n toDOM: function toDOM() { return hrDOM }\n },\n\n // :: NodeSpec A heading textblock, with a `level` attribute that\n // should hold the number 1 to 6. Parsed and serialized as `

` to\n // `

` elements.\n heading: {\n attrs: {level: {default: 1}},\n content: \"inline*\",\n group: \"block\",\n defining: true,\n parseDOM: [{tag: \"h1\", attrs: {level: 1}},\n {tag: \"h2\", attrs: {level: 2}},\n {tag: \"h3\", attrs: {level: 3}},\n {tag: \"h4\", attrs: {level: 4}},\n {tag: \"h5\", attrs: {level: 5}},\n {tag: \"h6\", attrs: {level: 6}}],\n toDOM: function toDOM(node) { return [\"h\" + node.attrs.level, 0] }\n },\n\n // :: NodeSpec A code listing. Disallows marks or non-text inline\n // nodes by default. Represented as a `
` element with a\n  // `` element inside of it.\n  code_block: {\n    content: \"text*\",\n    marks: \"\",\n    group: \"block\",\n    code: true,\n    defining: true,\n    parseDOM: [{tag: \"pre\", preserveWhitespace: \"full\"}],\n    toDOM: function toDOM() { return preDOM }\n  },\n\n  // :: NodeSpec The text node.\n  text: {\n    group: \"inline\"\n  },\n\n  // :: NodeSpec An inline image (``) node. Supports `src`,\n  // `alt`, and `href` attributes. The latter two default to the empty\n  // string.\n  image: {\n    inline: true,\n    attrs: {\n      src: {},\n      alt: {default: null},\n      title: {default: null}\n    },\n    group: \"inline\",\n    draggable: true,\n    parseDOM: [{tag: \"img[src]\", getAttrs: function getAttrs(dom) {\n      return {\n        src: dom.getAttribute(\"src\"),\n        title: dom.getAttribute(\"title\"),\n        alt: dom.getAttribute(\"alt\")\n      }\n    }}],\n    toDOM: function toDOM(node) { var ref = node.attrs;\n    var src = ref.src;\n    var alt = ref.alt;\n    var title = ref.title; return [\"img\", {src: src, alt: alt, title: title}] }\n  },\n\n  // :: NodeSpec A hard line break, represented in the DOM as `
`.\n hard_break: {\n inline: true,\n group: \"inline\",\n selectable: false,\n parseDOM: [{tag: \"br\"}],\n toDOM: function toDOM() { return brDOM }\n }\n};\n\nvar emDOM = [\"em\", 0], strongDOM = [\"strong\", 0], codeDOM = [\"code\", 0];\n\n// :: Object [Specs](#model.MarkSpec) for the marks in the schema.\nvar marks = {\n // :: MarkSpec A link. Has `href` and `title` attributes. `title`\n // defaults to the empty string. Rendered and parsed as an `
`\n // element.\n link: {\n attrs: {\n href: {},\n title: {default: null}\n },\n inclusive: false,\n parseDOM: [{tag: \"a[href]\", getAttrs: function getAttrs(dom) {\n return {href: dom.getAttribute(\"href\"), title: dom.getAttribute(\"title\")}\n }}],\n toDOM: function toDOM(node) { var ref = node.attrs;\n var href = ref.href;\n var title = ref.title; return [\"a\", {href: href, title: title}, 0] }\n },\n\n // :: MarkSpec An emphasis mark. Rendered as an `` element.\n // Has parse rules that also match `` and `font-style: italic`.\n em: {\n parseDOM: [{tag: \"i\"}, {tag: \"em\"}, {style: \"font-style=italic\"}],\n toDOM: function toDOM() { return emDOM }\n },\n\n // :: MarkSpec A strong mark. Rendered as ``, parse rules\n // also match `` and `font-weight: bold`.\n strong: {\n parseDOM: [{tag: \"strong\"},\n // This works around a Google Docs misbehavior where\n // pasted content will be inexplicably wrapped in ``\n // tags with a font-weight normal.\n {tag: \"b\", getAttrs: function (node) { return node.style.fontWeight != \"normal\" && null; }},\n {style: \"font-weight\", getAttrs: function (value) { return /^(bold(er)?|[5-9]\\d{2,})$/.test(value) && null; }}],\n toDOM: function toDOM() { return strongDOM }\n },\n\n // :: MarkSpec Code font mark. Represented as a `` element.\n code: {\n parseDOM: [{tag: \"code\"}],\n toDOM: function toDOM() { return codeDOM }\n }\n};\n\n// :: Schema\n// This schema roughly corresponds to the document schema used by\n// [CommonMark](http://commonmark.org/), minus the list elements,\n// which are defined in the [`prosemirror-schema-list`](#schema-list)\n// module.\n//\n// To reuse elements from this schema, extend or read from its\n// `spec.nodes` and `spec.marks` [properties](#model.Schema.spec).\nvar schema = new Schema({nodes: nodes, marks: marks});\n\nexport { marks, nodes, schema };\n//# sourceMappingURL=index.es.js.map\n","import { Schema } from 'prosemirror-model'\n\nconst brDOM = ['br']\n\nconst calcYchangeDomAttrs = (attrs, domAttrs = {}) => {\n domAttrs = Object.assign({}, domAttrs)\n if (attrs.ychange !== null) {\n domAttrs.ychange_user = attrs.ychange.user\n domAttrs.ychange_state = attrs.ychange.state\n }\n return domAttrs\n}\n\n// :: Object\n// [Specs](#model.NodeSpec) for the nodes defined in this schema.\nexport const nodes = {\n // :: NodeSpec The top level document node.\n doc: {\n content: 'custom paragraph'\n },\n\n custom: {\n atom: true,\n attrs: { checked: { default: false } },\n parseDOM: [{ tag: 'div' }],\n toDOM () {\n return ['div']\n }\n },\n\n // :: NodeSpec A plain paragraph textblock. Represented in the DOM\n // as a `

` element.\n paragraph: {\n attrs: { ychange: { default: null } },\n content: 'inline*',\n group: 'block',\n parseDOM: [{ tag: 'p' }],\n toDOM (node) {\n return ['p', calcYchangeDomAttrs(node.attrs), 0]\n }\n },\n\n // :: NodeSpec A blockquote (`

`) wrapping one or more blocks.\n blockquote: {\n attrs: { ychange: { default: null } },\n content: 'block+',\n group: 'block',\n defining: true,\n parseDOM: [{ tag: 'blockquote' }],\n toDOM (node) {\n return ['blockquote', calcYchangeDomAttrs(node.attrs), 0]\n }\n },\n\n // :: NodeSpec A horizontal rule (`
`).\n horizontal_rule: {\n attrs: { ychange: { default: null } },\n group: 'block',\n parseDOM: [{ tag: 'hr' }],\n toDOM (node) {\n return ['hr', calcYchangeDomAttrs(node.attrs)]\n }\n },\n\n // :: NodeSpec A heading textblock, with a `level` attribute that\n // should hold the number 1 to 6. Parsed and serialized as `

` to\n // `

` elements.\n heading: {\n attrs: {\n level: { default: 1 },\n ychange: { default: null }\n },\n content: 'inline*',\n group: 'block',\n defining: true,\n parseDOM: [\n { tag: 'h1', attrs: { level: 1 } },\n { tag: 'h2', attrs: { level: 2 } },\n { tag: 'h3', attrs: { level: 3 } },\n { tag: 'h4', attrs: { level: 4 } },\n { tag: 'h5', attrs: { level: 5 } },\n { tag: 'h6', attrs: { level: 6 } }\n ],\n toDOM (node) {\n return ['h' + node.attrs.level, calcYchangeDomAttrs(node.attrs), 0]\n }\n },\n\n // :: NodeSpec A code listing. Disallows marks or non-text inline\n // nodes by default. Represented as a `
` element with a\n  // `` element inside of it.\n  code_block: {\n    attrs: { ychange: { default: null } },\n    content: 'text*',\n    marks: '',\n    group: 'block',\n    code: true,\n    defining: true,\n    parseDOM: [{ tag: 'pre', preserveWhitespace: 'full' }],\n    toDOM (node) {\n      return ['pre', calcYchangeDomAttrs(node.attrs), ['code', 0]]\n    }\n  },\n\n  // :: NodeSpec The text node.\n  text: {\n    group: 'inline'\n  },\n\n  // :: NodeSpec An inline image (``) node. Supports `src`,\n  // `alt`, and `href` attributes. The latter two default to the empty\n  // string.\n  image: {\n    inline: true,\n    attrs: {\n      ychange: { default: null },\n      src: {},\n      alt: { default: null },\n      title: { default: null }\n    },\n    group: 'inline',\n    draggable: true,\n    parseDOM: [\n      {\n        tag: 'img[src]',\n        getAttrs (dom) {\n          return {\n            src: dom.getAttribute('src'),\n            title: dom.getAttribute('title'),\n            alt: dom.getAttribute('alt')\n          }\n        }\n      }\n    ],\n    toDOM (node) {\n      const domAttrs = {\n        src: node.attrs.src,\n        title: node.attrs.title,\n        alt: node.attrs.alt\n      }\n      return ['img', calcYchangeDomAttrs(node.attrs, domAttrs)]\n    }\n  },\n\n  // :: NodeSpec A hard line break, represented in the DOM as `
`.\n hard_break: {\n inline: true,\n group: 'inline',\n selectable: false,\n parseDOM: [{ tag: 'br' }],\n toDOM () {\n return brDOM\n }\n }\n}\n\nconst emDOM = ['em', 0]\nconst strongDOM = ['strong', 0]\nconst codeDOM = ['code', 0]\n\n// :: Object [Specs](#model.MarkSpec) for the marks in the schema.\nexport const marks = {\n // :: MarkSpec A link. Has `href` and `title` attributes. `title`\n // defaults to the empty string. Rendered and parsed as an `
`\n // element.\n link: {\n attrs: {\n href: {},\n title: { default: null }\n },\n inclusive: false,\n parseDOM: [\n {\n tag: 'a[href]',\n getAttrs (dom) {\n return {\n href: dom.getAttribute('href'),\n title: dom.getAttribute('title')\n }\n }\n }\n ],\n toDOM (node) {\n return ['a', node.attrs, 0]\n }\n },\n\n // :: MarkSpec An emphasis mark. Rendered as an `` element.\n // Has parse rules that also match `` and `font-style: italic`.\n em: {\n parseDOM: [{ tag: 'i' }, { tag: 'em' }, { style: 'font-style=italic' }],\n toDOM () {\n return emDOM\n }\n },\n\n // :: MarkSpec A strong mark. Rendered as ``, parse rules\n // also match `` and `font-weight: bold`.\n strong: {\n parseDOM: [\n { tag: 'strong' },\n // This works around a Google Docs misbehavior where\n // pasted content will be inexplicably wrapped in ``\n // tags with a font-weight normal.\n {\n tag: 'b',\n getAttrs: node => node.style.fontWeight !== 'normal' && null\n },\n {\n style: 'font-weight',\n getAttrs: value => /^(bold(er)?|[5-9]\\d{2,})$/.test(value) && null\n }\n ],\n toDOM () {\n return strongDOM\n }\n },\n\n // :: MarkSpec Code font mark. Represented as a `` element.\n code: {\n parseDOM: [{ tag: 'code' }],\n toDOM () {\n return codeDOM\n }\n },\n ychange: {\n attrs: {\n user: { default: null },\n state: { default: null }\n },\n inclusive: false,\n parseDOM: [{ tag: 'ychange' }],\n toDOM (node) {\n return [\n 'ychange',\n { ychange_user: node.attrs.user, ychange_state: node.attrs.state },\n 0\n ]\n }\n }\n}\n\n// :: Schema\n// This schema rougly corresponds to the document schema used by\n// [CommonMark](http://commonmark.org/), minus the list elements,\n// which are defined in the [`prosemirror-schema-list`](#schema-list)\n// module.\n//\n// To reuse elements from this schema, extend or read from its\n// `spec.nodes` and `spec.marks` [properties](#model.Schema.spec).\nexport const schema = new Schema({ nodes, marks })\n","\nimport * as t from 'lib0/testing.js'\nimport * as prng from 'lib0/prng.js'\nimport * as math from 'lib0/math.js'\nimport * as Y from 'yjs'\nimport { applyRandomTests } from 'yjs/tests/testHelper.js'\n\nimport { ySyncPlugin, prosemirrorJSONToYDoc, yDocToProsemirrorJSON } from '../src/y-prosemirror.js'\nimport { EditorState, TextSelection } from 'prosemirror-state'\nimport { EditorView } from 'prosemirror-view'\nimport * as basicSchema from 'prosemirror-schema-basic'\nimport { findWrapping } from 'prosemirror-transform'\nimport { schema as complexSchema } from './complexSchema.js'\n\nconst schema = /** @type {any} */ (basicSchema.schema)\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testDocTransformation = tc => {\n const view = createNewProsemirrorView(new Y.Doc())\n view.dispatch(view.state.tr.insert(0, /** @type {any} */ (schema.node('paragraph', undefined, schema.text('hello world')))))\n const stateJSON = view.state.doc.toJSON()\n // test if transforming back and forth from Yjs doc works\n const backandforth = yDocToProsemirrorJSON(prosemirrorJSONToYDoc(/** @type {any} */ (schema), stateJSON))\n t.compare(stateJSON, backandforth)\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testEmptyNotSync = tc => {\n const ydoc = new Y.Doc()\n const type = ydoc.getXmlFragment('prosemirror')\n const view = createNewComplexProsemirrorView(ydoc)\n t.assert(type.toString() === '', 'should only sync after first change')\n\n view.dispatch(\n view.state.tr.setNodeMarkup(0, undefined, {\n checked: true\n })\n )\n t.compareStrings(type.toString(), '')\n}\n\nconst createNewComplexProsemirrorView = y => {\n const view = new EditorView(null, {\n // @ts-ignore\n state: EditorState.create({\n schema: complexSchema,\n plugins: [ySyncPlugin(y.get('prosemirror', Y.XmlFragment))]\n })\n })\n return view\n}\n\nconst createNewProsemirrorView = y => {\n const view = new EditorView(null, {\n // @ts-ignore\n state: EditorState.create({\n schema,\n plugins: [ySyncPlugin(y.get('prosemirror', Y.XmlFragment))]\n })\n })\n return view\n}\n\nlet charCounter = 0\n\nconst marksChoices = [\n [schema.mark('strong')],\n [schema.mark('em')],\n [schema.mark('em'), schema.mark('strong')],\n [],\n []\n]\n\nconst pmChanges = [\n /**\n * @param {Y.Doc} y\n * @param {prng.PRNG} gen\n * @param {EditorView} p\n */\n (y, gen, p) => { // insert text\n const insertPos = prng.int32(gen, 0, p.state.doc.content.size)\n const marks = prng.oneOf(gen, marksChoices)\n const tr = p.state.tr\n const text = charCounter++ + prng.word(gen)\n p.dispatch(tr.insert(insertPos, schema.text(text, marks)))\n },\n /**\n * @param {Y.Doc} y\n * @param {prng.PRNG} gen\n * @param {EditorView} p\n */\n (y, gen, p) => { // delete text\n const insertPos = prng.int32(gen, 0, p.state.doc.content.size)\n const overwrite = math.min(prng.int32(gen, 0, p.state.doc.content.size - insertPos), 2)\n p.dispatch(p.state.tr.insertText('', insertPos, insertPos + overwrite))\n },\n /**\n * @param {Y.Doc} y\n * @param {prng.PRNG} gen\n * @param {EditorView} p\n */\n (y, gen, p) => { // replace text\n const insertPos = prng.int32(gen, 0, p.state.doc.content.size)\n const overwrite = math.min(prng.int32(gen, 0, p.state.doc.content.size - insertPos), 2)\n const text = charCounter++ + prng.word(gen)\n p.dispatch(p.state.tr.insertText(text, insertPos, insertPos + overwrite))\n },\n /**\n * @param {Y.Doc} y\n * @param {prng.PRNG} gen\n * @param {EditorView} p\n */\n (y, gen, p) => { // insert paragraph\n const insertPos = prng.int32(gen, 0, p.state.doc.content.size)\n const marks = prng.oneOf(gen, marksChoices)\n const tr = p.state.tr\n const text = charCounter++ + prng.word(gen)\n p.dispatch(tr.insert(insertPos, schema.node('paragraph', undefined, schema.text(text, marks))))\n },\n /**\n * @param {Y.Doc} y\n * @param {prng.PRNG} gen\n * @param {EditorView} p\n */\n (y, gen, p) => { // insert codeblock\n const insertPos = prng.int32(gen, 0, p.state.doc.content.size)\n const tr = p.state.tr\n const text = charCounter++ + prng.word(gen)\n p.dispatch(tr.insert(insertPos, schema.node('code_block', undefined, schema.text(text))))\n },\n /**\n * @param {Y.Doc} y\n * @param {prng.PRNG} gen\n * @param {EditorView} p\n */\n (y, gen, p) => { // wrap in blockquote\n const insertPos = prng.int32(gen, 0, p.state.doc.content.size)\n const overwrite = prng.int32(gen, 0, p.state.doc.content.size - insertPos)\n const tr = p.state.tr\n tr.setSelection(TextSelection.create(tr.doc, insertPos, insertPos + overwrite))\n const $from = tr.selection.$from\n const $to = tr.selection.$to\n const range = $from.blockRange($to)\n const wrapping = range && findWrapping(range, schema.nodes.blockquote)\n if (wrapping) {\n p.dispatch(tr.wrap(range, wrapping))\n }\n }\n]\n\n/**\n * @param {any} result\n */\nconst checkResult = result => {\n for (let i = 1; i < result.testObjects.length; i++) {\n const p1 = result.testObjects[i - 1].state.doc.toJSON()\n const p2 = result.testObjects[i].state.doc.toJSON()\n t.compare(p1, p2)\n }\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testRepeatGenerateProsemirrorChanges2 = tc => {\n checkResult(applyRandomTests(tc, pmChanges, 2, createNewProsemirrorView))\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testRepeatGenerateProsemirrorChanges3 = tc => {\n checkResult(applyRandomTests(tc, pmChanges, 3, createNewProsemirrorView))\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testRepeatGenerateProsemirrorChanges30 = tc => {\n checkResult(applyRandomTests(tc, pmChanges, 30, createNewProsemirrorView))\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testRepeatGenerateProsemirrorChanges40 = tc => {\n checkResult(applyRandomTests(tc, pmChanges, 40, createNewProsemirrorView))\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testRepeatGenerateProsemirrorChanges70 = tc => {\n checkResult(applyRandomTests(tc, pmChanges, 70, createNewProsemirrorView))\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testRepeatGenerateProsemirrorChanges100 = tc => {\n checkResult(applyRandomTests(tc, pmChanges, 100, createNewProsemirrorView))\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testRepeatGenerateProsemirrorChanges300 = tc => {\n checkResult(applyRandomTests(tc, pmChanges, 300, createNewProsemirrorView))\n}\n","\nimport * as prosemirror from './y-prosemirror.test.js'\n\nimport { runTests } from 'lib0/testing.js'\nimport { isBrowser, isNode } from 'lib0/environment.js'\nimport * as log from 'lib0/logging.js'\n\nif (isBrowser) {\n log.createVConsole(document.body)\n}\nrunTests({\n prosemirror\n}).then(success => {\n /* istanbul ignore next */\n if (isNode) {\n process.exit(success ? 0 : 1)\n }\n})\n"],"names":["map.create","string.fromCamelCase","conditions.undefinedToNull","storage.varStorage","create","pair.forEach","map.map","math.log10","math.round","math.exp10","metric.prefix","math.floor","forEach","map","symbol.create","pair.create","dom.mapToStyleString","env.isNode","env.isBrowser","dom.element","dom.text","json.stringify","eventloop.enqueue","dom.append","dom.addEventListener","performance","iso","cryptoRandomBuffer","binary.BITS32","length","buffer.createUint8ArrayViewFromArrayBuffer","math.max","binary.BITS7","binary.BIT8","math.isNegativeZero","binary.BITS6","binary.BIT7","math.min","number.isInteger","binary.BITS31","math.ceil","math.add","env.hasConf","env.hasParam","env.getParam","random.uint32","prng.create","log.GREY","log.PURPLE","log.BLUE","log.groupCollapsed","log.group","promise.isPromise","log.printError","log.groupEnd","time.humanizeDuration","array.last","statistics.median","statistics.average","log.print","log.BOLD","log.UNBOLD","log.RED","log.UNCOLOR","log.GREEN","object.length","object.forEach","object.hasProperty","object.map","log.printImgBase64","map.setIfUndefined","set.create","array.from","array.appendTo","encoding.writeVarUint","decoding.readVarUint","decoding.createDecoder","random.uuidv4","error.methodUnimplemented","decoding.readUint8","decoding.readVarString","decoding.readAny","buffer.copyUint8Array","decoding.readVarUint8Array","decoding.IntDiffOptRleDecoder","decoding.UintOptRleDecoder","decoding.RleDecoder","decoding.StringDecoder","encoding.createEncoder","encoding.Encoder","encoding.toUint8Array","encoding.writeUint8","encoding.writeVarString","encoding.writeAny","encoding.writeVarUint8Array","error.unexpectedCase","encoding.IntDiffOptRleEncoder","encoding.UintOptRleEncoder","encoding.RleEncoder","encoding.StringEncoder","encoding.writeUint8Array","binary.BITS5","binary.BIT6","f.callAll","map.any","logging.print","logging.ORANGE","logging.BOLD","logging.UNBOLD","logging.RED","time.getUnixTime","math.abs","error.create","iterator.iteratorFilter","iterator.iteratorMap","object.equalFlat","map.copy","binary.BIT2","binary.BIT4","binary.BIT1","binary.BIT3","Y.encodeStateVector","Y.encodeStateAsUpdate","Y.applyUpdate","readUpdate","Y.Doc","syncProtocol.writeUpdate","syncProtocol.writeSyncStep1","prng.oneOf","syncProtocol.readSyncMessage","encoding.length","prng.bool","Y.useV2Encoding","Y.useV1Encoding","Y.YXmlElement","compare","t.assert","t.compare","Y.AbstractType","Y.getStateVector","Y.createDeleteSetFromStructStore","Y.compareIDs","t.fail","Y.Item","prng.int32","OrderedMap","DOMParser","copy","doc","prototypeAccessors","prototypeAccessors$1","Transaction","keys","NodeType","prototypeAccessors$2","isVisible","Y.isDeleted","Y.createSnapshot","Y.createDeleteSet","PMSlice","PMFragment","snapshot","Y.snapshot","Y.iterateDeletedStructs","Y.typeListToArraySnapshot","Y.Snapshot","Y.XmlElement","Y.XmlText","equalAttrs","Y.ContentString","Y.ContentFormat","Y.createRelativePositionFromTypeIndex","Y.RelativePosition","Y.findRootTypeKey","createRelativePosition","Y.createID","Y.createAbsolutePositionFromRelativePosition","Y.isParentOf","Y.XmlFragment","brDOM","nodes","emDOM","strongDOM","codeDOM","marks","schema","basicSchema.schema","t.compareStrings","complexSchema","prng.word","log.createVConsole"],"mappings":";;;EAAA;EACA;EACA;EACA;EACA;AACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACO,MAAM,MAAM,GAAG,MAAM,IAAI,GAAG,GAAE;AACrC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACO,MAAM,IAAI,GAAG,CAAC,IAAI;EACzB,EAAE,MAAM,CAAC,GAAG,MAAM,GAAE;EACpB,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAC,EAAE,EAAC;EACtC,EAAE,OAAO,CAAC;EACV,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ACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AACA;EACA;EACA;EACA;EACA;EACA;AACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EC9GA;EACA;EACA;EACA;EACA;AAaA;EACA;EACA;EACA;AACA;EACA;EACO,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,KAAK,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,QAAQ,CAAC,GAAG,CAAC,IAAIjB,KAAU,CAAC,GAAG,CAAC,KAAK,GAAG;;ECvBxH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AAMA;EACA;EACA;EACA;EACO,MAAM,OAAO,CAAC;EACrB,EAAE,WAAW,CAAC,GAAG;EACjB,IAAI,IAAI,CAAC,IAAI,GAAG,EAAC;EACjB,IAAI,IAAI,CAAC,IAAI,GAAG,IAAI,UAAU,CAAC,GAAG,EAAC;EACnC;EACA;EACA;EACA,IAAI,IAAI,CAAC,IAAI,GAAG,GAAE;EAClB,GAAG;EACH,CAAC;AACD;EACA;EACA;EACA;EACA;EACO,MAAM,aAAa,GAAG,MAAM,IAAI,OAAO,GAAE;AAChD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACO,MAAMkB,QAAM,GAAG,OAAO,IAAI;EACjC,EAAE,IAAI,GAAG,GAAG,OAAO,CAAC,KAAI;EACxB,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;EAChD,IAAI,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,OAAM;EACjC,GAAG;EACH,EAAE,OAAO,GAAG;EACZ,EAAC;AACD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACO,MA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;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AACA;EACA;EACA;EACA;EACA;EACA,IAAI,MAAM,GAAG,SAAS,MAAM,CAAC,IAAI,EAAE;EACnC;EACA;EACA;EACA;EACA;EACA;EACA,EAAE,IAAI,CAAC,IAAI,GAAG,EAAE,CAAC;EACjB,EAAE,KAAK,IAAI,IAAI,IAAI,IAAI,EAAE,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE;EAC1D,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,GAAGU,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;EAChD,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,GAAGA,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAChD;EACA;EACA;EACA,EAAE,IAAI,CAAC,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,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AE;EAC/E,GAAG;EACH,EAAE,OAAO,KAAK;EACd,CAAC;AACD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AACA;EACA;EACA;EACA;EACA,IAAIC,WAAS,GAAG,SAAS,SAAS,CAAC,MAAM,EAAE,KAAK,EAAE;EAClD,EAAE,IAAI,MAAM,GAAG,IAAI,CAAC;AACpB;EACA;EACA;EACA,EAAE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;EACvB;EACA;EACA;EACA,EAAE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;EACrB,EAAE,IAAI,CAAC,IAAI,GAAG,EAAE,CAAC;EACjB,EAAE,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC;AACnB;EACA,EAAE,KAAK,CAAC,OAAO,CAAC,UAAU,IAAI,EAAE;EAChC,IAAI,IAAI,IAAI,CAAC,GAAG,EAAE,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE;EAC7C,SAAS,IA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;EAC7E;;;;;;;;;;;;;;;EC7MA,IAAI,SAAS,EAAE;EACf,EAAEqD,cAAkB,CAAC,QAAQ,CAAC,IAAI,EAAC;EACnC,CAAC;EACD,QAAQ,CAAC;EACT,EAAE,WAAW;EACb,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,IAAI;EACnB;EACA,EAAE,IAAI,MAAM,EAAE;EACd,IAAI,OAAO,CAAC,IAAI,CAAC,OAAO,GAAG,CAAC,GAAG,CAAC,EAAC;EACjC,GAAG;EACH,CAAC;;;;;;"} \ No newline at end of file diff --git a/dist/y-prosemirror.cjs b/dist/y-prosemirror.cjs new file mode 100644 index 0000000..007c338 --- /dev/null +++ b/dist/y-prosemirror.cjs @@ -0,0 +1,1381 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var Y = require('yjs'); +var prosemirrorView = require('prosemirror-view'); +var prosemirrorState = require('prosemirror-state'); +require('y-protocols/dist/awareness.cjs'); +var mutex_js = require('lib0/dist/mutex.cjs'); +var prosemirrorModel = require('prosemirror-model'); +var math = require('lib0/dist/math.cjs'); +var object_js = require('lib0/dist/object.cjs'); +var diff_js = require('lib0/dist/diff.cjs'); +var error = require('lib0/dist/error.cjs'); +var environment_js = require('lib0/dist/environment.cjs'); +var dom_js = require('lib0/dist/dom.cjs'); +var map = require('lib0/dist/map.cjs'); +var eventloop = require('lib0/dist/eventloop.cjs'); + +/** + * The unique prosemirror plugin key for syncPlugin + * + * @public + */ +const ySyncPluginKey = new prosemirrorState.PluginKey('y-sync'); + +/** + * The unique prosemirror plugin key for undoPlugin + * + * @public + */ +const yUndoPluginKey = new prosemirrorState.PluginKey('y-undo'); + +/** + * The unique prosemirror plugin key for cursorPlugin + * + * @public + */ +const yCursorPluginKey = new prosemirrorState.PluginKey('yjs-cursor'); + +/** + * @module bindings/prosemirror + */ + +/** + * @param {Y.Item} item + * @param {Y.Snapshot} [snapshot] + */ +const isVisible = (item, snapshot) => snapshot === undefined ? !item.deleted : (snapshot.sv.has(item.id.client) && /** @type {number} */ (snapshot.sv.get(item.id.client)) > item.id.clock && !Y.isDeleted(snapshot.ds, item.id)); + +/** + * Either a node if type is YXmlElement or an Array of text nodes if YXmlText + * @typedef {Map>} ProsemirrorMapping + */ + +/** + * @typedef {Object} ColorDef + * @property {string} ColorDef.light + * @property {string} ColorDef.dark + */ + +/** + * @typedef {Object} YSyncOpts + * @property {Array} [YSyncOpts.colors] + * @property {Map} [YSyncOpts.colorMapping] + * @property {Y.PermanentUserData|null} [YSyncOpts.permanentUserData] + */ + +/** + * @type {Array} + */ +const defaultColors = [{ light: '#ecd44433', dark: '#ecd444' }]; + +/** + * @param {Map} colorMapping + * @param {Array} colors + * @param {string} user + * @return {ColorDef} + */ +const getUserColor = (colorMapping, colors, user) => { + if (!colorMapping.has(user)) { + colorMapping.set(user, colors[colorMapping.size % colors.length]); + } + return /** @type {ColorDef} */ (colorMapping.get(user)); +}; + +/** + * This plugin listens to changes in prosemirror view and keeps yXmlState and view in sync. + * + * This plugin also keeps references to the type and the shared document so other plugins can access it. + * @param {Y.XmlFragment} yXmlFragment + * @param {YSyncOpts} opts + * @return {any} Returns a prosemirror plugin that binds to this type + */ +const ySyncPlugin = (yXmlFragment, { colors = defaultColors, colorMapping = new Map(), permanentUserData = null } = {}) => { + let changedInitialContent = false; + const plugin = new prosemirrorState.Plugin({ + props: { + editable: (state) => { + const syncState = ySyncPluginKey.getState(state); + return syncState.snapshot == null && syncState.prevSnapshot == null + } + }, + key: ySyncPluginKey, + state: { + init: (initargs, state) => { + return { + type: yXmlFragment, + doc: yXmlFragment.doc, + binding: null, + snapshot: null, + prevSnapshot: null, + isChangeOrigin: false, + colors, + colorMapping, + permanentUserData + } + }, + apply: (tr, pluginState) => { + const change = tr.getMeta(ySyncPluginKey); + if (change !== undefined) { + pluginState = Object.assign({}, pluginState); + for (const key in change) { + pluginState[key] = change[key]; + } + } + // always set isChangeOrigin. If undefined, this is not change origin. + pluginState.isChangeOrigin = change !== undefined && !!change.isChangeOrigin; + if (pluginState.binding !== null) { + if (change !== undefined && (change.snapshot != null || change.prevSnapshot != null)) { + // snapshot changed, rerender next + setTimeout(() => { + if (change.restore == null) { + pluginState.binding._renderSnapshot(change.snapshot, change.prevSnapshot, pluginState); + } else { + pluginState.binding._renderSnapshot(change.snapshot, change.snapshot, pluginState); + // reset to current prosemirror state + delete pluginState.restore; + delete pluginState.snapshot; + delete pluginState.prevSnapshot; + pluginState.binding._prosemirrorChanged(pluginState.binding.prosemirrorView.state.doc); + } + }, 0); + } + } + return pluginState + } + }, + view: view => { + + const binding = new ProsemirrorBinding(yXmlFragment, view); + binding._forceRerender(); + view.dispatch(view.state.tr.setMeta(ySyncPluginKey, { binding })); + + return { + update: () => { + const pluginState = plugin.getState(view.state); + if (pluginState.snapshot == null && pluginState.prevSnapshot == null) { + if (changedInitialContent || view.state.doc.content.findDiffStart(view.state.doc.type.createAndFill().content) != null) { + changedInitialContent = true; + binding._prosemirrorChanged(view.state.doc); + } + } + }, + destroy: () => { + binding.destroy(); + } + } + } + }); + return plugin +}; + +/** + * @param {any} tr + * @param {any} relSel + * @param {ProsemirrorBinding} binding + */ +const restoreRelativeSelection = (tr, relSel, binding) => { + if (relSel !== null && relSel.anchor !== null && relSel.head !== null) { + const anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping); + const head = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.head, binding.mapping); + if (anchor !== null && head !== null) { + tr = tr.setSelection(prosemirrorState.TextSelection.create(tr.doc, anchor, head)); + } + } +}; + +const getRelativeSelection = (pmbinding, state) => ({ + anchor: absolutePositionToRelativePosition(state.selection.anchor, pmbinding.type, pmbinding.mapping), + head: absolutePositionToRelativePosition(state.selection.head, pmbinding.type, pmbinding.mapping) +}); + +/** + * Binding for prosemirror. + * + * @protected + */ +class ProsemirrorBinding { + /** + * @param {Y.XmlFragment} yXmlFragment The bind source + * @param {any} prosemirrorView The target binding + */ + constructor (yXmlFragment, prosemirrorView) { + this.type = yXmlFragment; + this.prosemirrorView = prosemirrorView; + this.mux = mutex_js.createMutex(); + /** + * @type {ProsemirrorMapping} + */ + this.mapping = new Map(); + this._observeFunction = this._typeChanged.bind(this); + /** + * @type {Y.Doc} + */ + // @ts-ignore + this.doc = yXmlFragment.doc; + /** + * current selection as relative positions in the Yjs model + */ + this.beforeTransactionSelection = null; + this.beforeAllTransactions = () => { + if (this.beforeTransactionSelection === null) { + this.beforeTransactionSelection = getRelativeSelection(this, prosemirrorView.state); + } + }; + this.afterAllTransactions = () => { + this.beforeTransactionSelection = null; + }; + + this.doc.on('beforeAllTransactions', this.beforeAllTransactions); + this.doc.on('afterAllTransactions', this.afterAllTransactions); + yXmlFragment.observeDeep(this._observeFunction); + + this._domSelectionInView = null; + } + + _isLocalCursorInView () { + if (!this.prosemirrorView.hasFocus()) return false + if (environment_js.isBrowser && this._domSelectionInView === null) { + // Calculate the domSelectionInView and clear by next tick after all events are finished + setTimeout(() => { + this._domSelectionInView = null; + }, 0); + this._domSelectionInView = this._isDomSelectionInView(); + } + return this._domSelectionInView + } + + _isDomSelectionInView () { + const selection = this.prosemirrorView._root.getSelection(); + + const range = this.prosemirrorView._root.createRange(); + range.setStart(selection.anchorNode, selection.anchorOffset); + range.setEnd(selection.focusNode, selection.focusOffset); + + // This is a workaround for an edgecase where getBoundingClientRect will + // return zero values if the selection is collapsed at the start of a newline + // see reference here: https://stackoverflow.com/a/59780954 + const rects = range.getClientRects(); + if (rects.length === 0) { + // probably buggy newline behavior, explicitly select the node contents + if (range.startContainer && range.collapsed) { + range.selectNodeContents(range.startContainer); + } + } + + const bounding = range.getBoundingClientRect(); + const documentElement = dom_js.doc.documentElement; + + return bounding.bottom >= 0 && bounding.right >= 0 && + bounding.left <= (window.innerWidth || documentElement.clientWidth || 0) && + bounding.top <= (window.innerHeight || documentElement.clientHeight || 0) + } + + renderSnapshot (snapshot, prevSnapshot) { + if (!prevSnapshot) { + prevSnapshot = Y.createSnapshot(Y.createDeleteSet(), new Map()); + } + this.prosemirrorView.dispatch(this.prosemirrorView.state.tr.setMeta(ySyncPluginKey, { snapshot, prevSnapshot })); + } + + unrenderSnapshot () { + this.mapping = new Map(); + this.mux(() => { + const fragmentContent = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null); + // @ts-ignore + const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new prosemirrorModel.Slice(new prosemirrorModel.Fragment(fragmentContent), 0, 0)); + tr.setMeta(ySyncPluginKey, { snapshot: null, prevSnapshot: null }); + this.prosemirrorView.dispatch(tr); + }); + } + + _forceRerender () { + this.mapping = new Map(); + this.mux(() => { + let content = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null); + if (content.length) { + // @ts-ignore + const tr = this.prosemirrorView.state.tr.replaceWith(0, this.prosemirrorView.state.doc.content.size, new prosemirrorModel.Fragment(content)); + this.prosemirrorView.dispatch(tr); + } + }); + } + + /** + * @param {Y.Snapshot} snapshot + * @param {Y.Snapshot} prevSnapshot + * @param {Object} pluginState + */ + _renderSnapshot (snapshot, prevSnapshot, pluginState) { + if (!snapshot) { + snapshot = Y.snapshot(this.doc); + } + // clear mapping because we are going to rerender + this.mapping = new Map(); + this.mux(() => { + this.doc.transact(transaction => { + // before rendering, we are going to sanitize ops and split deleted ops + // if they were deleted by seperate users. + const pud = pluginState.permanentUserData; + if (pud) { + pud.dss.forEach(ds => { + Y.iterateDeletedStructs(transaction, ds, item => {}); + }); + } + const computeYChange = (type, id) => { + const user = type === 'added' ? pud.getUserByClientId(id.client) : pud.getUserByDeletedId(id); + return { + user, + type, + color: getUserColor(pluginState.colorMapping, pluginState.colors, user) + } + }; + // Create document fragment and render + const fragmentContent = Y.typeListToArraySnapshot(this.type, new Y.Snapshot(prevSnapshot.ds, snapshot.sv)).map(t => { + if (!t._item.deleted || isVisible(t._item, snapshot) || isVisible(t._item, prevSnapshot)) { + return createNodeFromYElement(t, this.prosemirrorView.state.schema, new Map(), snapshot, prevSnapshot, computeYChange) + } else { + // No need to render elements that are not visible by either snapshot. + // If a client adds and deletes content in the same snapshot the element is not visible by either snapshot. + return null + } + }).filter(n => n !== null); + // @ts-ignore + const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new prosemirrorModel.Slice(new prosemirrorModel.Fragment(fragmentContent), 0, 0)); + this.prosemirrorView.dispatch(tr); + }, ySyncPluginKey); + }); + } + + /** + * @param {Array} events + * @param {Y.Transaction} transaction + */ + _typeChanged (events, transaction) { + const syncState = ySyncPluginKey.getState(this.prosemirrorView.state); + if (events.length === 0 || syncState.snapshot != null || syncState.prevSnapshot != null) { + // drop out if snapshot is active + this.renderSnapshot(syncState.snapshot, syncState.prevSnapshot); + return + } + this.mux(() => { + /** + * @param {any} _ + * @param {Y.AbstractType} type + */ + const delType = (_, type) => this.mapping.delete(type); + Y.iterateDeletedStructs(transaction, transaction.deleteSet, struct => struct.constructor === Y.Item && this.mapping.delete(/** @type {Y.ContentType} */ (/** @type {Y.Item} */ (struct).content).type)); + transaction.changed.forEach(delType); + transaction.changedParentTypes.forEach(delType); + const fragmentContent = this.type.toArray().map(t => createNodeIfNotExists(/** @type {Y.XmlElement | Y.XmlHook} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null); + // @ts-ignore + let tr = this.prosemirrorView.state.tr.replaceWith(0, this.prosemirrorView.state.doc.content.size, new prosemirrorModel.Fragment(fragmentContent)); + restoreRelativeSelection(tr, this.beforeTransactionSelection, this); + tr = tr.setMeta(ySyncPluginKey, { isChangeOrigin: true }); + if (this.beforeTransactionSelection !== null && this._isLocalCursorInView()) { + tr.scrollIntoView(); + } + this.prosemirrorView.dispatch(tr); + }); + } + + _prosemirrorChanged (doc) { + this.mux(() => { + this.doc.transact(() => { + updateYFragment(this.doc, this.type, doc, this.mapping); + this.beforeTransactionSelection = getRelativeSelection(this, this.prosemirrorView.state); + }, ySyncPluginKey); + }); + } + + destroy () { + this.type.unobserveDeep(this._observeFunction); + this.doc.off('beforeAllTransactions', this.beforeAllTransactions); + this.doc.off('afterAllTransactions', this.afterAllTransactions); + } +} + +/** + * @private + * @param {Y.XmlElement | Y.XmlHook} el + * @param {PMSchema} schema + * @param {ProsemirrorMapping} mapping + * @param {Y.Snapshot} [snapshot] + * @param {Y.Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', Y.ID):any} [computeYChange] + * @return {PMNode | null} + */ +const createNodeIfNotExists = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => { + const node = /** @type {PMNode} */ (mapping.get(el)); + if (node === undefined) { + if (el instanceof Y.XmlElement) { + return createNodeFromYElement(el, schema, mapping, snapshot, prevSnapshot, computeYChange) + } else { + throw error.methodUnimplemented() // we are currently not handling hooks + } + } + return node +}; + +/** + * @private + * @param {Y.XmlElement} el + * @param {any} schema + * @param {ProsemirrorMapping} mapping + * @param {Y.Snapshot} [snapshot] + * @param {Y.Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', Y.ID):any} [computeYChange] + * @return {PMNode | null} Returns node if node could be created. Otherwise it deletes the yjs type and returns null + */ +const createNodeFromYElement = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => { + const children = []; + const createChildren = type => { + if (type.constructor === Y.XmlElement) { + const n = createNodeIfNotExists(type, schema, mapping, snapshot, prevSnapshot, computeYChange); + if (n !== null) { + children.push(n); + } + } else { + const ns = createTextNodesFromYText(type, schema, mapping, snapshot, prevSnapshot, computeYChange); + if (ns !== null) { + ns.forEach(textchild => { + if (textchild !== null) { + children.push(textchild); + } + }); + } + } + }; + if (snapshot === undefined || prevSnapshot === undefined) { + el.toArray().forEach(createChildren); + } else { + Y.typeListToArraySnapshot(el, new Y.Snapshot(prevSnapshot.ds, snapshot.sv)).forEach(createChildren); + } + try { + const attrs = el.getAttributes(snapshot); + if (snapshot !== undefined) { + if (!isVisible(/** @type {Y.Item} */ (el._item), snapshot)) { + attrs.ychange = computeYChange ? computeYChange('removed', /** @type {Y.Item} */ (el._item).id) : { type: 'removed' }; + } else if (!isVisible(/** @type {Y.Item} */ (el._item), prevSnapshot)) { + attrs.ychange = computeYChange ? computeYChange('added', /** @type {Y.Item} */ (el._item).id) : { type: 'added' }; + } + } + const node = schema.node(el.nodeName, attrs, children); + mapping.set(el, node); + return node + } catch (e) { + // an error occured while creating the node. This is probably a result of a concurrent action. + /** @type {Y.Doc} */ (el.doc).transact(transaction => { + /** @type {Y.Item} */ (el._item).delete(transaction); + }, ySyncPluginKey); + mapping.delete(el); + return null + } +}; + +/** + * @private + * @param {Y.XmlText} text + * @param {any} schema + * @param {ProsemirrorMapping} mapping + * @param {Y.Snapshot} [snapshot] + * @param {Y.Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', Y.ID):any} [computeYChange] + * @return {Array|null} + */ +const createTextNodesFromYText = (text, schema, mapping, snapshot, prevSnapshot, computeYChange) => { + const nodes = []; + const deltas = text.toDelta(snapshot, prevSnapshot, computeYChange); + try { + for (let i = 0; i < deltas.length; i++) { + const delta = deltas[i]; + const marks = []; + for (const markName in delta.attributes) { + marks.push(schema.mark(markName, delta.attributes[markName])); + } + nodes.push(schema.text(delta.insert, marks)); + } + } catch (e) { + // an error occured while creating the node. This is probably a result of a concurrent action. + /** @type {Y.Doc} */ (text.doc).transact(transaction => { + /** @type {Y.Item} */ (text._item).delete(transaction); + }, ySyncPluginKey); + return null + } + // @ts-ignore + return nodes +}; + +/** + * @private + * @param {Array} nodes prosemirror node + * @param {ProsemirrorMapping} mapping + * @return {Y.XmlText} + */ +const createTypeFromTextNodes = (nodes, mapping) => { + const type = new Y.XmlText(); + const delta = nodes.map(node => ({ + // @ts-ignore + insert: node.text, + attributes: marksToAttributes(node.marks) + })); + type.applyDelta(delta); + mapping.set(type, nodes); + return type +}; + +/** + * @private + * @param {any} node prosemirror node + * @param {ProsemirrorMapping} mapping + * @return {Y.XmlElement} + */ +const createTypeFromElementNode = (node, mapping) => { + const type = new Y.XmlElement(node.type.name); + for (const key in node.attrs) { + const val = node.attrs[key]; + if (val !== null && key !== 'ychange') { + type.setAttribute(key, val); + } + } + type.insert(0, normalizePNodeContent(node).map(n => createTypeFromTextOrElementNode(n, mapping))); + mapping.set(type, node); + return type +}; + +/** + * @private + * @param {PMNode|Array} node prosemirror text node + * @param {ProsemirrorMapping} mapping + * @return {Y.XmlElement|Y.XmlText} + */ +const createTypeFromTextOrElementNode = (node, mapping) => node instanceof Array ? createTypeFromTextNodes(node, mapping) : createTypeFromElementNode(node, mapping); + +const equalAttrs = (pattrs, yattrs) => { + const keys = Object.keys(pattrs).filter(key => pattrs[key] !== null); + let eq = keys.length === Object.keys(yattrs).filter(key => yattrs[key] !== null).length; + for (let i = 0; i < keys.length && eq; i++) { + const key = keys[i]; + const l = pattrs[key]; + const r = yattrs[key]; + eq = key === 'ychange' || l === r || (typeof l === 'object' && typeof r === 'object' && equalAttrs(l, r)); + } + return eq +}; + +/** + * @typedef {Array|PMNode>} NormalizedPNodeContent + */ + +/** + * @param {any} pnode + * @return {NormalizedPNodeContent} + */ +const normalizePNodeContent = pnode => { + const c = pnode.content.content; + const res = []; + for (let i = 0; i < c.length; i++) { + const n = c[i]; + if (n.isText) { + const textNodes = []; + for (let tnode = c[i]; i < c.length && tnode.isText; tnode = c[++i]) { + textNodes.push(tnode); + } + i--; + res.push(textNodes); + } else { + res.push(n); + } + } + return res +}; + +/** + * @param {Y.XmlText} ytext + * @param {Array} ptexts + */ +const equalYTextPText = (ytext, ptexts) => { + const delta = ytext.toDelta(); + return delta.length === ptexts.length && delta.every((d, i) => d.insert === /** @type {any} */ (ptexts[i]).text && object_js.keys(d.attributes || {}).length === ptexts[i].marks.length && ptexts[i].marks.every(mark => equalAttrs(d.attributes[mark.type.name] || {}, mark.attrs))) +}; + +/** + * @param {Y.XmlElement|Y.XmlText|Y.XmlHook} ytype + * @param {any|Array} pnode + */ +const equalYTypePNode = (ytype, pnode) => { + if (ytype instanceof Y.XmlElement && !(pnode instanceof Array) && matchNodeName(ytype, pnode)) { + const normalizedContent = normalizePNodeContent(pnode); + return ytype._length === normalizedContent.length && equalAttrs(ytype.getAttributes(), pnode.attrs) && ytype.toArray().every((ychild, i) => equalYTypePNode(ychild, normalizedContent[i])) + } + return ytype instanceof Y.XmlText && pnode instanceof Array && equalYTextPText(ytype, pnode) +}; + +/** + * @param {PMNode | Array | undefined} mapped + * @param {PMNode | Array} pcontent + */ +const mappedIdentity = (mapped, pcontent) => mapped === pcontent || (mapped instanceof Array && pcontent instanceof Array && mapped.length === pcontent.length && mapped.every((a, i) => pcontent[i] === a)); + +/** + * @param {Y.XmlElement} ytype + * @param {PMNode} pnode + * @param {ProsemirrorMapping} mapping + * @return {{ foundMappedChild: boolean, equalityFactor: number }} + */ +const computeChildEqualityFactor = (ytype, pnode, mapping) => { + const yChildren = ytype.toArray(); + const pChildren = normalizePNodeContent(pnode); + const pChildCnt = pChildren.length; + const yChildCnt = yChildren.length; + const minCnt = math.min(yChildCnt, pChildCnt); + let left = 0; + let right = 0; + let foundMappedChild = false; + for (; left < minCnt; left++) { + const leftY = yChildren[left]; + const leftP = pChildren[left]; + if (mappedIdentity(mapping.get(leftY), leftP)) { + foundMappedChild = true;// definite (good) match! + } else if (!equalYTypePNode(leftY, leftP)) { + break + } + } + for (; left + right < minCnt; right++) { + const rightY = yChildren[yChildCnt - right - 1]; + const rightP = pChildren[pChildCnt - right - 1]; + if (mappedIdentity(mapping.get(rightY), rightP)) { + foundMappedChild = true; + } else if (!equalYTypePNode(rightY, rightP)) { + break + } + } + return { + equalityFactor: left + right, + foundMappedChild + } +}; + +const ytextTrans = ytext => { + let str = ''; + /** + * @type {Y.Item|null} + */ + let n = ytext._start; + const nAttrs = {}; + while (n !== null) { + if (!n.deleted) { + if (n.countable && n.content instanceof Y.ContentString) { + str += n.content.str; + } else if (n.content instanceof Y.ContentFormat) { + nAttrs[n.content.key] = null; + } + } + n = n.right; + } + return { + str, + nAttrs + } +}; + +/** + * @todo test this more + * + * @param {Y.Text} ytext + * @param {Array} ptexts + * @param {ProsemirrorMapping} mapping + */ +const updateYText = (ytext, ptexts, mapping) => { + mapping.set(ytext, ptexts); + const { nAttrs, str } = ytextTrans(ytext); + const content = ptexts.map(p => ({ insert: /** @type {any} */ (p).text, attributes: Object.assign({}, nAttrs, marksToAttributes(p.marks)) })); + const { insert, remove, index } = diff_js.simpleDiff(str, content.map(c => c.insert).join('')); + ytext.delete(index, remove); + ytext.insert(index, insert); + ytext.applyDelta(content.map(c => ({ retain: c.insert.length, attributes: c.attributes }))); +}; + +const marksToAttributes = marks => { + const pattrs = {}; + marks.forEach(mark => { + if (mark.type.name !== 'ychange') { + pattrs[mark.type.name] = mark.attrs; + } + }); + return pattrs +}; + +/** + * @private + * @param {Y.Doc} y + * @param {Y.XmlFragment} yDomFragment + * @param {any} pNode + * @param {ProsemirrorMapping} mapping + */ +const updateYFragment = (y, yDomFragment, pNode, mapping) => { + if (yDomFragment instanceof Y.XmlElement && yDomFragment.nodeName !== pNode.type.name) { + throw new Error('node name mismatch!') + } + mapping.set(yDomFragment, pNode); + // update attributes + if (yDomFragment instanceof Y.XmlElement) { + const yDomAttrs = yDomFragment.getAttributes(); + const pAttrs = pNode.attrs; + for (const key in pAttrs) { + if (pAttrs[key] !== null) { + if (yDomAttrs[key] !== pAttrs[key] && key !== 'ychange') { + yDomFragment.setAttribute(key, pAttrs[key]); + } + } else { + yDomFragment.removeAttribute(key); + } + } + // remove all keys that are no longer in pAttrs + for (const key in yDomAttrs) { + if (pAttrs[key] === undefined) { + yDomFragment.removeAttribute(key); + } + } + } + // update children + const pChildren = normalizePNodeContent(pNode); + const pChildCnt = pChildren.length; + const yChildren = yDomFragment.toArray(); + const yChildCnt = yChildren.length; + const minCnt = math.min(pChildCnt, yChildCnt); + let left = 0; + let right = 0; + // find number of matching elements from left + for (;left < minCnt; left++) { + const leftY = yChildren[left]; + const leftP = pChildren[left]; + if (!mappedIdentity(mapping.get(leftY), leftP)) { + if (equalYTypePNode(leftY, leftP)) { + // update mapping + mapping.set(leftY, leftP); + } else { + break + } + } + } + // find number of matching elements from right + for (;right + left + 1 < minCnt; right++) { + const rightY = yChildren[yChildCnt - right - 1]; + const rightP = pChildren[pChildCnt - right - 1]; + if (!mappedIdentity(mapping.get(rightY), rightP)) { + if (equalYTypePNode(rightY, rightP)) { + // update mapping + mapping.set(rightY, rightP); + } else { + break + } + } + } + y.transact(() => { + // try to compare and update + while (yChildCnt - left - right > 0 && pChildCnt - left - right > 0) { + const leftY = yChildren[left]; + const leftP = pChildren[left]; + const rightY = yChildren[yChildCnt - right - 1]; + const rightP = pChildren[pChildCnt - right - 1]; + if (leftY instanceof Y.XmlText && leftP instanceof Array) { + if (!equalYTextPText(leftY, leftP)) { + updateYText(leftY, leftP, mapping); + } + left += 1; + } else { + let updateLeft = leftY instanceof Y.XmlElement && matchNodeName(leftY, leftP); + let updateRight = rightY instanceof Y.XmlElement && matchNodeName(rightY, rightP); + if (updateLeft && updateRight) { + // decide which which element to update + const equalityLeft = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (leftY), /** @type {PMNode} */ (leftP), mapping); + const equalityRight = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (rightY), /** @type {PMNode} */ (rightP), mapping); + if (equalityLeft.foundMappedChild && !equalityRight.foundMappedChild) { + updateRight = false; + } else if (!equalityLeft.foundMappedChild && equalityRight.foundMappedChild) { + updateLeft = false; + } else if (equalityLeft.equalityFactor < equalityRight.equalityFactor) { + updateLeft = false; + } else { + updateRight = false; + } + } + if (updateLeft) { + updateYFragment(y, /** @type {Y.XmlFragment} */ (leftY), /** @type {PMNode} */ (leftP), mapping); + left += 1; + } else if (updateRight) { + updateYFragment(y, /** @type {Y.XmlFragment} */ (rightY), /** @type {PMNode} */ (rightP), mapping); + right += 1; + } else { + yDomFragment.delete(left, 1); + yDomFragment.insert(left, [createTypeFromTextOrElementNode(leftP, mapping)]); + left += 1; + } + } + } + const yDelLen = yChildCnt - left - right; + if (yDelLen > 0) { + yDomFragment.delete(left, yDelLen); + } + if (left + right < pChildCnt) { + const ins = []; + for (let i = left; i < pChildCnt - right; i++) { + ins.push(createTypeFromTextOrElementNode(pChildren[i], mapping)); + } + yDomFragment.insert(left, ins); + } + }, ySyncPluginKey); +}; + +/** + * @function + * @param {Y.XmlElement} yElement + * @param {any} pNode Prosemirror Node + */ +const matchNodeName = (yElement, pNode) => !(pNode instanceof Array) && yElement.nodeName === pNode.type.name; + +/** + * Either a node if type is YXmlElement or an Array of text nodes if YXmlText + * @typedef {Map>} ProsemirrorMapping + */ + +/** + * Is null if no timeout is in progress. + * Is defined if a timeout is in progress. + * Maps from view + * @type {Map>|null} + */ +let viewsToUpdate = null; + +const updateMetas = () => { + const ups = /** @type {Map>} */ (viewsToUpdate); + viewsToUpdate = null; + ups.forEach((metas, view) => { + const tr = view.state.tr; + metas.forEach((val, key) => { + tr.setMeta(key, val); + }); + view.dispatch(tr); + }); +}; + +const setMeta = (view, key, value) => { + if (!viewsToUpdate) { + viewsToUpdate = new Map(); + eventloop.timeout(0, updateMetas); + } + map.setIfUndefined(viewsToUpdate, view, map.create).set(key, value); +}; + +/** + * Transforms a Prosemirror based absolute position to a Yjs Cursor (relative position in the Yjs model). + * + * @param {number} pos + * @param {Y.XmlFragment} type + * @param {ProsemirrorMapping} mapping + * @return {any} relative position + */ +const absolutePositionToRelativePosition = (pos, type, mapping) => { + if (pos === 0) { + return Y.createRelativePositionFromTypeIndex(type, 0) + } + let n = type._first === null ? null : /** @type {Y.ContentType} */ (type._first.content).type; + while (n !== null && type !== n) { + if (n.constructor === Y.XmlText) { + if (n._length >= pos) { + return Y.createRelativePositionFromTypeIndex(n, pos) + } else { + pos -= n._length; + } + if (n._item !== null && n._item.next !== null) { + n = /** @type {Y.ContentType} */ (n._item.next.content).type; + } else { + do { + n = n._item === null ? null : n._item.parent; + pos--; + } while (n !== type && n !== null && n._item !== null && n._item.next === null) + if (n !== null && n !== type) { + // @ts-gnore we know that n.next !== null because of above loop conditition + n = n._item === null ? null : /** @type {Y.ContentType} */ (/** @type Y.Item */ (n._item.next).content).type; + } + } + } else { + const pNodeSize = /** @type {any} */ (mapping.get(n) || { nodeSize: 0 }).nodeSize; + if (n._first !== null && pos < pNodeSize) { + n = /** @type {Y.ContentType} */ (n._first.content).type; + pos--; + } else { + if (pos === 1 && n._length === 0 && pNodeSize > 1) { + // edge case, should end in this paragraph + return new Y.RelativePosition(n._item === null ? null : n._item.id, n._item === null ? Y.findRootTypeKey(n) : null, null) + } + pos -= pNodeSize; + if (n._item !== null && n._item.next !== null) { + n = /** @type {Y.ContentType} */ (n._item.next.content).type; + } else { + if (pos === 0) { + // set to end of n.parent + n = n._item === null ? n : n._item.parent; + return new Y.RelativePosition(n._item === null ? null : n._item.id, n._item === null ? Y.findRootTypeKey(n) : null, null) + } + do { + n = /** @type {Y.Item} */ (n._item).parent; + pos--; + } while (n !== type && /** @type {Y.Item} */ (n._item).next === null) + // if n is null at this point, we have an unexpected case + if (n !== type) { + // We know that n._item.next is defined because of above loop condition + n = /** @type {Y.ContentType} */ (/** @type {Y.Item} */ (/** @type {Y.Item} */ (n._item).next).content).type; + } + } + } + } + if (n === null) { + throw error.unexpectedCase() + } + if (pos === 0 && n.constructor !== Y.XmlText && n !== type) { // TODO: set to <= 0 + return createRelativePosition(n._item.parent, n._item) + } + } + return Y.createRelativePositionFromTypeIndex(type, type._length) +}; + +const createRelativePosition = (type, item) => { + let typeid = null; + let tname = null; + if (type._item === null) { + tname = Y.findRootTypeKey(type); + } else { + typeid = Y.createID(type._item.id.client, type._item.id.clock); + } + return new Y.RelativePosition(typeid, tname, item.id) +}; + +/** + * @param {Y.Doc} y + * @param {Y.XmlFragment} documentType Top level type that is bound to pView + * @param {any} relPos Encoded Yjs based relative position + * @param {ProsemirrorMapping} mapping + * @return {null|number} + */ +const relativePositionToAbsolutePosition = (y, documentType, relPos, mapping) => { + const decodedPos = Y.createAbsolutePositionFromRelativePosition(relPos, y); + if (decodedPos === null || (decodedPos.type !== documentType && !Y.isParentOf(documentType, decodedPos.type._item))) { + return null + } + let type = decodedPos.type; + let pos = 0; + if (type.constructor === Y.XmlText) { + pos = decodedPos.index; + } else if (type._item === null || !type._item.deleted) { + let n = type._first; + let i = 0; + while (i < type._length && i < decodedPos.index && n !== null) { + if (!n.deleted) { + const t = /** @type {Y.ContentType} */ (n.content).type; + i++; + if (t.constructor === Y.XmlText) { + pos += t._length; + } else { + pos += /** @type {any} */ (mapping.get(t)).nodeSize; + } + } + n = /** @type {Y.Item} */ (n.right); + } + pos += 1; // increase because we go out of n + } + while (type !== documentType && type._item !== null) { + // @ts-ignore + const parent = type._item.parent; + // @ts-ignore + if (parent._item === null || !parent._item.deleted) { + pos += 1; // the start tag + let n = parent._first; + // now iterate until we found type + while (n !== null) { + const contentType = /** @type {Y.ContentType} */ (n.content).type; + if (contentType === type) { + break + } + if (!n.deleted) { + if (contentType.constructor === Y.XmlText) { + pos += contentType._length; + } else { + pos += /** @type {any} */ (mapping.get(contentType)).nodeSize; + } + } + n = n.right; + } + } + type = parent; + } + return pos - 1 // we don't count the most outer tag, because it is a fragment +}; + +/** + * Utility method to convert a Prosemirror Doc Node into a Y.Doc. + * + * This can be used when importing existing content to Y.Doc for the first time, + * note that this should not be used to rehydrate a Y.Doc from a database once + * collaboration has begun as all history will be lost + * + * @param {Node} doc + * @param {string} xmlFragment + * @return {Y.Doc} + */ +function prosemirrorToYDoc (doc, xmlFragment = 'prosemirror') { + const ydoc = new Y.Doc(); + const type = ydoc.get(xmlFragment, Y.XmlFragment); + if (!type.doc) { + return ydoc + } + + updateYFragment(type.doc, type, doc, new Map()); + return type.doc +} + +/** + * Utility method to convert Prosemirror compatible JSON into a Y.Doc. + * + * This can be used when importing existing content to Y.Doc for the first time, + * note that this should not be used to rehydrate a Y.Doc from a database once + * collaboration has begun as all history will be lost + * + * @param {Schema} schema + * @param {any} state + * @param {string} xmlFragment + * @return {Y.Doc} + */ +function prosemirrorJSONToYDoc (schema, state, xmlFragment = 'prosemirror') { + const doc = prosemirrorModel.Node.fromJSON(schema, state); + return prosemirrorToYDoc(doc, xmlFragment) +} + +/** + * Utility method to convert a Y.Doc to a Prosemirror Doc node. + * + * @param {Schema} schema + * @param {Y.Doc} ydoc + * @return {Node} + */ +function yDocToProsemirror (schema, ydoc) { + const state = yDocToProsemirrorJSON(ydoc); + return prosemirrorModel.Node.fromJSON(schema, state) +} + +/** + * Utility method to convert a Y.Doc to Prosemirror compatible JSON. + * + * @param {Y.Doc} ydoc + * @param {string} xmlFragment + * @return {Record} + */ +function yDocToProsemirrorJSON ( + ydoc, + xmlFragment = 'prosemirror' +) { + const items = ydoc.getXmlFragment(xmlFragment).toArray(); + + function serialize (item) { + /** + * @type {Object} NodeObject + * @property {string} NodeObject.type + * @property {Record=} NodeObject.attrs + * @property {Array=} NodeObject.content + */ + let response; + + // TODO: Must be a better way to detect text nodes than this + if (!item.nodeName) { + const delta = item.toDelta(); + response = delta.map((d) => { + const text = { + type: 'text', + text: d.insert + }; + + if (d.attributes) { + text.marks = Object.keys(d.attributes).map((type) => { + const attrs = d.attributes[type]; + const mark = { + type + }; + + if (Object.keys(attrs)) { + mark.attrs = attrs; + } + + return mark + }); + } + return text + }); + } else { + response = { + type: item.nodeName + }; + + const attrs = item.getAttributes(); + if (Object.keys(attrs).length) { + response.attrs = attrs; + } + + const children = item.toArray(); + if (children.length) { + response.content = children.map(serialize).flat(); + } + } + + return response + } + + return { + type: 'doc', + content: items.map(serialize) + } +} + +/** + * Default generator for a cursor element + * + * @param {any} user user data + * @return HTMLElement + */ +const defaultCursorBuilder = user => { + const cursor = document.createElement('span'); + cursor.classList.add('ProseMirror-yjs-cursor'); + cursor.setAttribute('style', `border-color: ${user.color}`); + const userDiv = document.createElement('div'); + userDiv.setAttribute('style', `background-color: ${user.color}`); + userDiv.insertBefore(document.createTextNode(user.name), null); + cursor.insertBefore(userDiv, null); + return cursor +}; + +/** + * @param {any} state + * @param {Awareness} awareness + * @return {any} DecorationSet + */ +const createDecorations = (state, awareness, createCursor) => { + const ystate = ySyncPluginKey.getState(state); + const y = ystate.doc; + const decorations = []; + if (ystate.snapshot != null || ystate.prevSnapshot != null || ystate.binding === null) { + // do not render cursors while snapshot is active + return prosemirrorView.DecorationSet.create(state.doc, []) + } + awareness.getStates().forEach((aw, clientId) => { + if (clientId === y.clientID) { + return + } + if (aw.cursor != null) { + const user = aw.user || {}; + if (user.color == null) { + user.color = '#ffa500'; + } + if (user.name == null) { + user.name = `User: ${clientId}`; + } + let anchor = relativePositionToAbsolutePosition(y, ystate.type, Y.createRelativePositionFromJSON(aw.cursor.anchor), ystate.binding.mapping); + let head = relativePositionToAbsolutePosition(y, ystate.type, Y.createRelativePositionFromJSON(aw.cursor.head), ystate.binding.mapping); + if (anchor !== null && head !== null) { + const maxsize = math.max(state.doc.content.size - 1, 0); + anchor = math.min(anchor, maxsize); + head = math.min(head, maxsize); + decorations.push(prosemirrorView.Decoration.widget(head, () => createCursor(user), { key: clientId + '', side: 10 })); + const from = math.min(anchor, head); + const to = math.max(anchor, head); + decorations.push(prosemirrorView.Decoration.inline(from, to, { style: `background-color: ${user.color}70` }, { inclusiveEnd: true, inclusiveStart: false })); + } + } + }); + return prosemirrorView.DecorationSet.create(state.doc, decorations) +}; + +/** + * A prosemirror plugin that listens to awareness information on Yjs. + * This requires that a `prosemirrorPlugin` is also bound to the prosemirror. + * + * @public + * @param {Awareness} awareness + * @param {object} [opts] + * @param {function(any):HTMLElement} [opts.cursorBuilder] + * @param {function(any):any} [opts.getSelection] + * @param {string} [opts.cursorStateField] By default all editor bindings use the awareness 'cursor' field to propagate cursor information. + * @return {any} + */ +const yCursorPlugin = (awareness, { cursorBuilder = defaultCursorBuilder, getSelection = state => state.selection } = {}, cursorStateField = 'cursor') => new prosemirrorState.Plugin({ + key: yCursorPluginKey, + state: { + init (_, state) { + return createDecorations(state, awareness, cursorBuilder) + }, + apply (tr, prevState, oldState, newState) { + const ystate = ySyncPluginKey.getState(newState); + const yCursorState = tr.getMeta(yCursorPluginKey); + if ((ystate && ystate.isChangeOrigin) || (yCursorState && yCursorState.awarenessUpdated)) { + return createDecorations(newState, awareness, cursorBuilder) + } + return prevState.map(tr.mapping, tr.doc) + } + }, + props: { + decorations: state => { + return yCursorPluginKey.getState(state) + } + }, + view: view => { + const awarenessListener = () => { + // @ts-ignore + if (view.docView) { + setMeta(view, yCursorPluginKey, { awarenessUpdated: true }); + } + }; + const updateCursorInfo = () => { + const ystate = ySyncPluginKey.getState(view.state); + // @note We make implicit checks when checking for the cursor property + const current = awareness.getLocalState() || {}; + if (view.hasFocus() && ystate.binding !== null) { + const selection = getSelection(view.state); + /** + * @type {Y.RelativePosition} + */ + const anchor = absolutePositionToRelativePosition(selection.anchor, ystate.type, ystate.binding.mapping); + /** + * @type {Y.RelativePosition} + */ + const head = absolutePositionToRelativePosition(selection.head, ystate.type, ystate.binding.mapping); + if (current.cursor == null || !Y.compareRelativePositions(Y.createRelativePositionFromJSON(current.cursor.anchor), anchor) || !Y.compareRelativePositions(Y.createRelativePositionFromJSON(current.cursor.head), head)) { + awareness.setLocalStateField(cursorStateField, { + anchor, head + }); + } + } else if (current.cursor != null && relativePositionToAbsolutePosition(ystate.doc, ystate.type, Y.createRelativePositionFromJSON(current.cursor.anchor), ystate.binding.mapping) !== null) { + // delete cursor information if current cursor information is owned by this editor binding + awareness.setLocalStateField(cursorStateField, null); + } + }; + awareness.on('change', awarenessListener); + view.dom.addEventListener('focusin', updateCursorInfo); + view.dom.addEventListener('focusout', updateCursorInfo); + return { + update: updateCursorInfo, + destroy: () => { + view.dom.removeEventListener('focusin', updateCursorInfo); + view.dom.removeEventListener('focusout', updateCursorInfo); + awareness.off('change', awarenessListener); + awareness.setLocalStateField(cursorStateField, null); + } + } + } +}); + +const undo = state => { + const undoManager = yUndoPluginKey.getState(state).undoManager; + if (undoManager != null) { + undoManager.undo(); + return true + } +}; + +const redo = state => { + const undoManager = yUndoPluginKey.getState(state).undoManager; + if (undoManager != null) { + undoManager.redo(); + return true + } +}; + +const yUndoPlugin = ({ protectedNodes = new Set(['paragraph']), trackedOrigins = [] } = {}) => new prosemirrorState.Plugin({ + key: yUndoPluginKey, + state: { + init: (initargs, state) => { + // TODO: check if plugin order matches and fix + const ystate = ySyncPluginKey.getState(state); + const undoManager = new Y.UndoManager(ystate.type, { + trackedOrigins: new Set([ySyncPluginKey].concat(trackedOrigins)), + deleteFilter: item => !(item instanceof Y.Item) || + !(item.content instanceof Y.ContentType) || + !(item.content.type instanceof Y.Text || + (item.content.type instanceof Y.XmlElement && protectedNodes.has(item.content.type.nodeName))) || + item.content.type._length === 0 + }); + return { + undoManager, + prevSel: null, + hasUndoOps: undoManager.undoStack.length > 0, + hasRedoOps: undoManager.redoStack.length > 0 + } + }, + apply: (tr, val, oldState, state) => { + const binding = ySyncPluginKey.getState(state).binding; + const undoManager = val.undoManager; + const hasUndoOps = undoManager.undoStack.length > 0; + const hasRedoOps = undoManager.redoStack.length > 0; + if (binding) { + return { + undoManager, + prevSel: getRelativeSelection(binding, oldState), + hasUndoOps, + hasRedoOps + } + } else { + if (hasUndoOps !== val.hasUndoOps || hasRedoOps !== val.hasRedoOps) { + return Object.assign({}, val, { + hasUndoOps: undoManager.undoStack.length > 0, + hasRedoOps: undoManager.redoStack.length > 0 + }) + } else { // nothing changed + return val + } + } + } + }, + view: view => { + const ystate = ySyncPluginKey.getState(view.state); + const undoManager = yUndoPluginKey.getState(view.state).undoManager; + undoManager.on('stack-item-added', ({ stackItem }) => { + const binding = ystate.binding; + if (binding) { + stackItem.meta.set(binding, yUndoPluginKey.getState(view.state).prevSel); + } + }); + undoManager.on('stack-item-popped', ({ stackItem }) => { + const binding = ystate.binding; + if (binding) { + binding.beforeTransactionSelection = stackItem.meta.get(binding) || binding.beforeTransactionSelection; + } + }); + return { + destroy: () => { + undoManager.destroy(); + } + } + } +}); + +exports.ProsemirrorBinding = ProsemirrorBinding; +exports.absolutePositionToRelativePosition = absolutePositionToRelativePosition; +exports.createDecorations = createDecorations; +exports.defaultCursorBuilder = defaultCursorBuilder; +exports.getRelativeSelection = getRelativeSelection; +exports.isVisible = isVisible; +exports.prosemirrorJSONToYDoc = prosemirrorJSONToYDoc; +exports.prosemirrorToYDoc = prosemirrorToYDoc; +exports.redo = redo; +exports.relativePositionToAbsolutePosition = relativePositionToAbsolutePosition; +exports.setMeta = setMeta; +exports.undo = undo; +exports.yCursorPlugin = yCursorPlugin; +exports.yCursorPluginKey = yCursorPluginKey; +exports.yDocToProsemirror = yDocToProsemirror; +exports.yDocToProsemirrorJSON = yDocToProsemirrorJSON; +exports.ySyncPlugin = ySyncPlugin; +exports.ySyncPluginKey = ySyncPluginKey; +exports.yUndoPlugin = yUndoPlugin; +exports.yUndoPluginKey = yUndoPluginKey; +//# sourceMappingURL=y-prosemirror.cjs.map diff --git a/dist/y-prosemirror.cjs.map b/dist/y-prosemirror.cjs.map new file mode 100644 index 0000000..76f3441 --- /dev/null +++ b/dist/y-prosemirror.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"y-prosemirror.cjs","sources":["../src/plugins/keys.js","../src/plugins/sync-plugin.js","../src/lib.js","../src/plugins/cursor-plugin.js","../src/plugins/undo-plugin.js"],"sourcesContent":["\nimport { PluginKey } from 'prosemirror-state' // eslint-disable-line\n\n/**\n * The unique prosemirror plugin key for syncPlugin\n *\n * @public\n */\nexport const ySyncPluginKey = new PluginKey('y-sync')\n\n/**\n * The unique prosemirror plugin key for undoPlugin\n *\n * @public\n */\nexport const yUndoPluginKey = new PluginKey('y-undo')\n\n/**\n * The unique prosemirror plugin key for cursorPlugin\n *\n * @public\n */\nexport const yCursorPluginKey = new PluginKey('yjs-cursor')\n","/**\n * @module bindings/prosemirror\n */\n\nimport { createMutex } from 'lib0/mutex.js'\nimport { Node as PMNode, Slice as PMSlice, Fragment as PMFragment, Schema as PMSchema } from 'prosemirror-model'\nimport { Plugin, TextSelection } from 'prosemirror-state' // eslint-disable-line\nimport { min } from 'lib0/math.js'\nimport { keys } from 'lib0/object.js'\nimport { simpleDiff } from 'lib0/diff.js'\nimport { methodUnimplemented } from 'lib0/error.js'\nimport { ySyncPluginKey } from './keys.js'\nimport * as Y from 'yjs'\nimport { absolutePositionToRelativePosition, relativePositionToAbsolutePosition } from '../lib.js'\nimport { isBrowser } from 'lib0/environment.js'\nimport { doc } from 'lib0/dom.js'\n\n/**\n * @param {Y.Item} item\n * @param {Y.Snapshot} [snapshot]\n */\nexport const isVisible = (item, snapshot) => snapshot === undefined ? !item.deleted : (snapshot.sv.has(item.id.client) && /** @type {number} */ (snapshot.sv.get(item.id.client)) > item.id.clock && !Y.isDeleted(snapshot.ds, item.id))\n\n/**\n * Either a node if type is YXmlElement or an Array of text nodes if YXmlText\n * @typedef {Map>} ProsemirrorMapping\n */\n\n/**\n * @typedef {Object} ColorDef\n * @property {string} ColorDef.light\n * @property {string} ColorDef.dark\n */\n\n/**\n * @typedef {Object} YSyncOpts\n * @property {Array} [YSyncOpts.colors]\n * @property {Map} [YSyncOpts.colorMapping]\n * @property {Y.PermanentUserData|null} [YSyncOpts.permanentUserData]\n */\n\n/**\n * @type {Array}\n */\nconst defaultColors = [{ light: '#ecd44433', dark: '#ecd444' }]\n\n/**\n * @param {Map} colorMapping\n * @param {Array} colors\n * @param {string} user\n * @return {ColorDef}\n */\nconst getUserColor = (colorMapping, colors, user) => {\n if (!colorMapping.has(user)) {\n colorMapping.set(user, colors[colorMapping.size % colors.length]);\n }\n return /** @type {ColorDef} */ (colorMapping.get(user));\n}\n\n/**\n * This plugin listens to changes in prosemirror view and keeps yXmlState and view in sync.\n *\n * This plugin also keeps references to the type and the shared document so other plugins can access it.\n * @param {Y.XmlFragment} yXmlFragment\n * @param {YSyncOpts} opts\n * @return {any} Returns a prosemirror plugin that binds to this type\n */\nexport const ySyncPlugin = (yXmlFragment, { colors = defaultColors, colorMapping = new Map(), permanentUserData = null } = {}) => {\n let changedInitialContent = false\n const plugin = new Plugin({\n props: {\n editable: (state) => {\n const syncState = ySyncPluginKey.getState(state)\n return syncState.snapshot == null && syncState.prevSnapshot == null\n }\n },\n key: ySyncPluginKey,\n state: {\n init: (initargs, state) => {\n return {\n type: yXmlFragment,\n doc: yXmlFragment.doc,\n binding: null,\n snapshot: null,\n prevSnapshot: null,\n isChangeOrigin: false,\n colors,\n colorMapping,\n permanentUserData\n }\n },\n apply: (tr, pluginState) => {\n const change = tr.getMeta(ySyncPluginKey)\n if (change !== undefined) {\n pluginState = Object.assign({}, pluginState)\n for (const key in change) {\n pluginState[key] = change[key]\n }\n }\n // always set isChangeOrigin. If undefined, this is not change origin.\n pluginState.isChangeOrigin = change !== undefined && !!change.isChangeOrigin\n if (pluginState.binding !== null) {\n if (change !== undefined && (change.snapshot != null || change.prevSnapshot != null)) {\n // snapshot changed, rerender next\n setTimeout(() => {\n if (change.restore == null) {\n pluginState.binding._renderSnapshot(change.snapshot, change.prevSnapshot, pluginState)\n } else {\n pluginState.binding._renderSnapshot(change.snapshot, change.snapshot, pluginState)\n // reset to current prosemirror state\n delete pluginState.restore\n delete pluginState.snapshot\n delete pluginState.prevSnapshot\n pluginState.binding._prosemirrorChanged(pluginState.binding.prosemirrorView.state.doc)\n }\n }, 0)\n }\n }\n return pluginState\n }\n },\n view: view => {\n\n const binding = new ProsemirrorBinding(yXmlFragment, view);\n binding._forceRerender();\n view.dispatch(view.state.tr.setMeta(ySyncPluginKey, { binding }));\n\n return {\n update: () => {\n const pluginState = plugin.getState(view.state)\n if (pluginState.snapshot == null && pluginState.prevSnapshot == null) {\n if (changedInitialContent || view.state.doc.content.findDiffStart(view.state.doc.type.createAndFill().content) != null) {\n changedInitialContent = true\n binding._prosemirrorChanged(view.state.doc)\n }\n }\n },\n destroy: () => {\n binding.destroy()\n }\n }\n }\n })\n return plugin\n}\n\n/**\n * @param {any} tr\n * @param {any} relSel\n * @param {ProsemirrorBinding} binding\n */\nconst restoreRelativeSelection = (tr, relSel, binding) => {\n if (relSel !== null && relSel.anchor !== null && relSel.head !== null) {\n const anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping)\n const head = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.head, binding.mapping)\n if (anchor !== null && head !== null) {\n tr = tr.setSelection(TextSelection.create(tr.doc, anchor, head))\n }\n }\n}\n\nexport const getRelativeSelection = (pmbinding, state) => ({\n anchor: absolutePositionToRelativePosition(state.selection.anchor, pmbinding.type, pmbinding.mapping),\n head: absolutePositionToRelativePosition(state.selection.head, pmbinding.type, pmbinding.mapping)\n})\n\n/**\n * Binding for prosemirror.\n *\n * @protected\n */\nexport class ProsemirrorBinding {\n /**\n * @param {Y.XmlFragment} yXmlFragment The bind source\n * @param {any} prosemirrorView The target binding\n */\n constructor (yXmlFragment, prosemirrorView) {\n this.type = yXmlFragment\n this.prosemirrorView = prosemirrorView\n this.mux = createMutex()\n /**\n * @type {ProsemirrorMapping}\n */\n this.mapping = new Map()\n this._observeFunction = this._typeChanged.bind(this)\n /**\n * @type {Y.Doc}\n */\n // @ts-ignore\n this.doc = yXmlFragment.doc\n /**\n * current selection as relative positions in the Yjs model\n */\n this.beforeTransactionSelection = null\n this.beforeAllTransactions = () => {\n if (this.beforeTransactionSelection === null) {\n this.beforeTransactionSelection = getRelativeSelection(this, prosemirrorView.state)\n }\n }\n this.afterAllTransactions = () => {\n this.beforeTransactionSelection = null\n }\n\n this.doc.on('beforeAllTransactions', this.beforeAllTransactions)\n this.doc.on('afterAllTransactions', this.afterAllTransactions)\n yXmlFragment.observeDeep(this._observeFunction)\n\n this._domSelectionInView = null\n }\n\n _isLocalCursorInView () {\n if (!this.prosemirrorView.hasFocus()) return false\n if (isBrowser && this._domSelectionInView === null) {\n // Calculate the domSelectionInView and clear by next tick after all events are finished\n setTimeout(() => {\n this._domSelectionInView = null\n }, 0)\n this._domSelectionInView = this._isDomSelectionInView()\n }\n return this._domSelectionInView\n }\n\n _isDomSelectionInView () {\n const selection = this.prosemirrorView._root.getSelection()\n\n const range = this.prosemirrorView._root.createRange()\n range.setStart(selection.anchorNode, selection.anchorOffset)\n range.setEnd(selection.focusNode, selection.focusOffset)\n\n // This is a workaround for an edgecase where getBoundingClientRect will\n // return zero values if the selection is collapsed at the start of a newline\n // see reference here: https://stackoverflow.com/a/59780954\n const rects = range.getClientRects()\n if (rects.length === 0) {\n // probably buggy newline behavior, explicitly select the node contents\n if (range.startContainer && range.collapsed) {\n range.selectNodeContents(range.startContainer)\n }\n }\n\n const bounding = range.getBoundingClientRect()\n const documentElement = doc.documentElement\n\n return bounding.bottom >= 0 && bounding.right >= 0 &&\n bounding.left <= (window.innerWidth || documentElement.clientWidth || 0) &&\n bounding.top <= (window.innerHeight || documentElement.clientHeight || 0)\n }\n\n renderSnapshot (snapshot, prevSnapshot) {\n if (!prevSnapshot) {\n prevSnapshot = Y.createSnapshot(Y.createDeleteSet(), new Map())\n }\n this.prosemirrorView.dispatch(this.prosemirrorView.state.tr.setMeta(ySyncPluginKey, { snapshot, prevSnapshot }))\n }\n\n unrenderSnapshot () {\n this.mapping = new Map()\n this.mux(() => {\n const fragmentContent = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null)\n // @ts-ignore\n const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new PMSlice(new PMFragment(fragmentContent), 0, 0))\n tr.setMeta(ySyncPluginKey, { snapshot: null, prevSnapshot: null })\n this.prosemirrorView.dispatch(tr)\n })\n }\n\n _forceRerender () {\n this.mapping = new Map()\n this.mux(() => {\n let content = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null);\n if (content.length) {\n // @ts-ignore\n const tr = this.prosemirrorView.state.tr.replaceWith(0, this.prosemirrorView.state.doc.content.size, new PMFragment(content));\n this.prosemirrorView.dispatch(tr);\n }\n })\n }\n\n /**\n * @param {Y.Snapshot} snapshot\n * @param {Y.Snapshot} prevSnapshot\n * @param {Object} pluginState\n */\n _renderSnapshot (snapshot, prevSnapshot, pluginState) {\n if (!snapshot) {\n snapshot = Y.snapshot(this.doc)\n }\n // clear mapping because we are going to rerender\n this.mapping = new Map()\n this.mux(() => {\n this.doc.transact(transaction => {\n // before rendering, we are going to sanitize ops and split deleted ops\n // if they were deleted by seperate users.\n const pud = pluginState.permanentUserData\n if (pud) {\n pud.dss.forEach(ds => {\n Y.iterateDeletedStructs(transaction, ds, item => {})\n })\n }\n const computeYChange = (type, id) => {\n const user = type === 'added' ? pud.getUserByClientId(id.client) : pud.getUserByDeletedId(id)\n return {\n user,\n type,\n color: getUserColor(pluginState.colorMapping, pluginState.colors, user)\n }\n }\n // Create document fragment and render\n const fragmentContent = Y.typeListToArraySnapshot(this.type, new Y.Snapshot(prevSnapshot.ds, snapshot.sv)).map(t => {\n if (!t._item.deleted || isVisible(t._item, snapshot) || isVisible(t._item, prevSnapshot)) {\n return createNodeFromYElement(t, this.prosemirrorView.state.schema, new Map(), snapshot, prevSnapshot, computeYChange)\n } else {\n // No need to render elements that are not visible by either snapshot.\n // If a client adds and deletes content in the same snapshot the element is not visible by either snapshot.\n return null\n }\n }).filter(n => n !== null)\n // @ts-ignore\n const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new PMSlice(new PMFragment(fragmentContent), 0, 0))\n this.prosemirrorView.dispatch(tr)\n }, ySyncPluginKey)\n })\n }\n\n /**\n * @param {Array} events\n * @param {Y.Transaction} transaction\n */\n _typeChanged (events, transaction) {\n const syncState = ySyncPluginKey.getState(this.prosemirrorView.state)\n if (events.length === 0 || syncState.snapshot != null || syncState.prevSnapshot != null) {\n // drop out if snapshot is active\n this.renderSnapshot(syncState.snapshot, syncState.prevSnapshot)\n return\n }\n this.mux(() => {\n /**\n * @param {any} _\n * @param {Y.AbstractType} type\n */\n const delType = (_, type) => this.mapping.delete(type)\n Y.iterateDeletedStructs(transaction, transaction.deleteSet, struct => struct.constructor === Y.Item && this.mapping.delete(/** @type {Y.ContentType} */ (/** @type {Y.Item} */ (struct).content).type))\n transaction.changed.forEach(delType)\n transaction.changedParentTypes.forEach(delType)\n const fragmentContent = this.type.toArray().map(t => createNodeIfNotExists(/** @type {Y.XmlElement | Y.XmlHook} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null)\n // @ts-ignore\n let tr = this.prosemirrorView.state.tr.replaceWith(0, this.prosemirrorView.state.doc.content.size, new PMFragment(fragmentContent));\n restoreRelativeSelection(tr, this.beforeTransactionSelection, this)\n tr = tr.setMeta(ySyncPluginKey, { isChangeOrigin: true })\n if (this.beforeTransactionSelection !== null && this._isLocalCursorInView()) {\n tr.scrollIntoView()\n }\n this.prosemirrorView.dispatch(tr)\n })\n }\n\n _prosemirrorChanged (doc) {\n this.mux(() => {\n this.doc.transact(() => {\n updateYFragment(this.doc, this.type, doc, this.mapping)\n this.beforeTransactionSelection = getRelativeSelection(this, this.prosemirrorView.state)\n }, ySyncPluginKey)\n })\n }\n\n destroy () {\n this.type.unobserveDeep(this._observeFunction)\n this.doc.off('beforeAllTransactions', this.beforeAllTransactions)\n this.doc.off('afterAllTransactions', this.afterAllTransactions)\n }\n}\n\n/**\n * @private\n * @param {Y.XmlElement | Y.XmlHook} el\n * @param {PMSchema} schema\n * @param {ProsemirrorMapping} mapping\n * @param {Y.Snapshot} [snapshot]\n * @param {Y.Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', Y.ID):any} [computeYChange]\n * @return {PMNode | null}\n */\nconst createNodeIfNotExists = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => {\n const node = /** @type {PMNode} */ (mapping.get(el))\n if (node === undefined) {\n if (el instanceof Y.XmlElement) {\n return createNodeFromYElement(el, schema, mapping, snapshot, prevSnapshot, computeYChange)\n } else {\n throw methodUnimplemented() // we are currently not handling hooks\n }\n }\n return node\n}\n\n/**\n * @private\n * @param {Y.XmlElement} el\n * @param {any} schema\n * @param {ProsemirrorMapping} mapping\n * @param {Y.Snapshot} [snapshot]\n * @param {Y.Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', Y.ID):any} [computeYChange]\n * @return {PMNode | null} Returns node if node could be created. Otherwise it deletes the yjs type and returns null\n */\nconst createNodeFromYElement = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => {\n const children = []\n const createChildren = type => {\n if (type.constructor === Y.XmlElement) {\n const n = createNodeIfNotExists(type, schema, mapping, snapshot, prevSnapshot, computeYChange)\n if (n !== null) {\n children.push(n)\n }\n } else {\n const ns = createTextNodesFromYText(type, schema, mapping, snapshot, prevSnapshot, computeYChange)\n if (ns !== null) {\n ns.forEach(textchild => {\n if (textchild !== null) {\n children.push(textchild)\n }\n })\n }\n }\n }\n if (snapshot === undefined || prevSnapshot === undefined) {\n el.toArray().forEach(createChildren)\n } else {\n Y.typeListToArraySnapshot(el, new Y.Snapshot(prevSnapshot.ds, snapshot.sv)).forEach(createChildren)\n }\n try {\n const attrs = el.getAttributes(snapshot)\n if (snapshot !== undefined) {\n if (!isVisible(/** @type {Y.Item} */ (el._item), snapshot)) {\n attrs.ychange = computeYChange ? computeYChange('removed', /** @type {Y.Item} */ (el._item).id) : { type: 'removed' }\n } else if (!isVisible(/** @type {Y.Item} */ (el._item), prevSnapshot)) {\n attrs.ychange = computeYChange ? computeYChange('added', /** @type {Y.Item} */ (el._item).id) : { type: 'added' }\n }\n }\n const node = schema.node(el.nodeName, attrs, children)\n mapping.set(el, node)\n return node\n } catch (e) {\n // an error occured while creating the node. This is probably a result of a concurrent action.\n /** @type {Y.Doc} */ (el.doc).transact(transaction => {\n /** @type {Y.Item} */ (el._item).delete(transaction)\n }, ySyncPluginKey)\n mapping.delete(el)\n return null\n }\n}\n\n/**\n * @private\n * @param {Y.XmlText} text\n * @param {any} schema\n * @param {ProsemirrorMapping} mapping\n * @param {Y.Snapshot} [snapshot]\n * @param {Y.Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', Y.ID):any} [computeYChange]\n * @return {Array|null}\n */\nconst createTextNodesFromYText = (text, schema, mapping, snapshot, prevSnapshot, computeYChange) => {\n const nodes = []\n const deltas = text.toDelta(snapshot, prevSnapshot, computeYChange)\n try {\n for (let i = 0; i < deltas.length; i++) {\n const delta = deltas[i]\n const marks = []\n for (const markName in delta.attributes) {\n marks.push(schema.mark(markName, delta.attributes[markName]))\n }\n nodes.push(schema.text(delta.insert, marks))\n }\n } catch (e) {\n // an error occured while creating the node. This is probably a result of a concurrent action.\n /** @type {Y.Doc} */ (text.doc).transact(transaction => {\n /** @type {Y.Item} */ (text._item).delete(transaction)\n }, ySyncPluginKey)\n return null\n }\n // @ts-ignore\n return nodes\n}\n\n/**\n * @private\n * @param {Array} nodes prosemirror node\n * @param {ProsemirrorMapping} mapping\n * @return {Y.XmlText}\n */\nconst createTypeFromTextNodes = (nodes, mapping) => {\n const type = new Y.XmlText()\n const delta = nodes.map(node => ({\n // @ts-ignore\n insert: node.text,\n attributes: marksToAttributes(node.marks)\n }))\n type.applyDelta(delta)\n mapping.set(type, nodes)\n return type\n}\n\n/**\n * @private\n * @param {any} node prosemirror node\n * @param {ProsemirrorMapping} mapping\n * @return {Y.XmlElement}\n */\nconst createTypeFromElementNode = (node, mapping) => {\n const type = new Y.XmlElement(node.type.name)\n for (const key in node.attrs) {\n const val = node.attrs[key]\n if (val !== null && key !== 'ychange') {\n type.setAttribute(key, val)\n }\n }\n type.insert(0, normalizePNodeContent(node).map(n => createTypeFromTextOrElementNode(n, mapping)))\n mapping.set(type, node)\n return type\n}\n\n/**\n * @private\n * @param {PMNode|Array} node prosemirror text node\n * @param {ProsemirrorMapping} mapping\n * @return {Y.XmlElement|Y.XmlText}\n */\nconst createTypeFromTextOrElementNode = (node, mapping) => node instanceof Array ? createTypeFromTextNodes(node, mapping) : createTypeFromElementNode(node, mapping)\n\nconst equalAttrs = (pattrs, yattrs) => {\n const keys = Object.keys(pattrs).filter(key => pattrs[key] !== null)\n let eq = keys.length === Object.keys(yattrs).filter(key => yattrs[key] !== null).length\n for (let i = 0; i < keys.length && eq; i++) {\n const key = keys[i]\n const l = pattrs[key]\n const r = yattrs[key]\n eq = key === 'ychange' || l === r || (typeof l === 'object' && typeof r === 'object' && equalAttrs(l, r))\n }\n return eq\n}\n\n/**\n * @typedef {Array|PMNode>} NormalizedPNodeContent\n */\n\n/**\n * @param {any} pnode\n * @return {NormalizedPNodeContent}\n */\nconst normalizePNodeContent = pnode => {\n const c = pnode.content.content\n const res = []\n for (let i = 0; i < c.length; i++) {\n const n = c[i]\n if (n.isText) {\n const textNodes = []\n for (let tnode = c[i]; i < c.length && tnode.isText; tnode = c[++i]) {\n textNodes.push(tnode)\n }\n i--\n res.push(textNodes)\n } else {\n res.push(n)\n }\n }\n return res\n}\n\n/**\n * @param {Y.XmlText} ytext\n * @param {Array} ptexts\n */\nconst equalYTextPText = (ytext, ptexts) => {\n const delta = ytext.toDelta()\n return delta.length === ptexts.length && delta.every((d, i) => d.insert === /** @type {any} */ (ptexts[i]).text && keys(d.attributes || {}).length === ptexts[i].marks.length && ptexts[i].marks.every(mark => equalAttrs(d.attributes[mark.type.name] || {}, mark.attrs)))\n}\n\n/**\n * @param {Y.XmlElement|Y.XmlText|Y.XmlHook} ytype\n * @param {any|Array} pnode\n */\nconst equalYTypePNode = (ytype, pnode) => {\n if (ytype instanceof Y.XmlElement && !(pnode instanceof Array) && matchNodeName(ytype, pnode)) {\n const normalizedContent = normalizePNodeContent(pnode)\n return ytype._length === normalizedContent.length && equalAttrs(ytype.getAttributes(), pnode.attrs) && ytype.toArray().every((ychild, i) => equalYTypePNode(ychild, normalizedContent[i]))\n }\n return ytype instanceof Y.XmlText && pnode instanceof Array && equalYTextPText(ytype, pnode)\n}\n\n/**\n * @param {PMNode | Array | undefined} mapped\n * @param {PMNode | Array} pcontent\n */\nconst mappedIdentity = (mapped, pcontent) => mapped === pcontent || (mapped instanceof Array && pcontent instanceof Array && mapped.length === pcontent.length && mapped.every((a, i) => pcontent[i] === a))\n\n/**\n * @param {Y.XmlElement} ytype\n * @param {PMNode} pnode\n * @param {ProsemirrorMapping} mapping\n * @return {{ foundMappedChild: boolean, equalityFactor: number }}\n */\nconst computeChildEqualityFactor = (ytype, pnode, mapping) => {\n const yChildren = ytype.toArray()\n const pChildren = normalizePNodeContent(pnode)\n const pChildCnt = pChildren.length\n const yChildCnt = yChildren.length\n const minCnt = min(yChildCnt, pChildCnt)\n let left = 0\n let right = 0\n let foundMappedChild = false\n for (; left < minCnt; left++) {\n const leftY = yChildren[left]\n const leftP = pChildren[left]\n if (mappedIdentity(mapping.get(leftY), leftP)) {\n foundMappedChild = true// definite (good) match!\n } else if (!equalYTypePNode(leftY, leftP)) {\n break\n }\n }\n for (; left + right < minCnt; right++) {\n const rightY = yChildren[yChildCnt - right - 1]\n const rightP = pChildren[pChildCnt - right - 1]\n if (mappedIdentity(mapping.get(rightY), rightP)) {\n foundMappedChild = true\n } else if (!equalYTypePNode(rightY, rightP)) {\n break\n }\n }\n return {\n equalityFactor: left + right,\n foundMappedChild\n }\n}\n\nconst ytextTrans = ytext => {\n let str = ''\n /**\n * @type {Y.Item|null}\n */\n let n = ytext._start\n const nAttrs = {}\n while (n !== null) {\n if (!n.deleted) {\n if (n.countable && n.content instanceof Y.ContentString) {\n str += n.content.str\n } else if (n.content instanceof Y.ContentFormat) {\n nAttrs[n.content.key] = null\n }\n }\n n = n.right\n }\n return {\n str,\n nAttrs\n }\n}\n\n/**\n * @todo test this more\n *\n * @param {Y.Text} ytext\n * @param {Array} ptexts\n * @param {ProsemirrorMapping} mapping\n */\nconst updateYText = (ytext, ptexts, mapping) => {\n mapping.set(ytext, ptexts)\n const { nAttrs, str } = ytextTrans(ytext)\n const content = ptexts.map(p => ({ insert: /** @type {any} */ (p).text, attributes: Object.assign({}, nAttrs, marksToAttributes(p.marks)) }))\n const { insert, remove, index } = simpleDiff(str, content.map(c => c.insert).join(''))\n ytext.delete(index, remove)\n ytext.insert(index, insert)\n ytext.applyDelta(content.map(c => ({ retain: c.insert.length, attributes: c.attributes })))\n}\n\nconst marksToAttributes = marks => {\n const pattrs = {}\n marks.forEach(mark => {\n if (mark.type.name !== 'ychange') {\n pattrs[mark.type.name] = mark.attrs\n }\n })\n return pattrs\n}\n\n/**\n * @private\n * @param {Y.Doc} y\n * @param {Y.XmlFragment} yDomFragment\n * @param {any} pNode\n * @param {ProsemirrorMapping} mapping\n */\nexport const updateYFragment = (y, yDomFragment, pNode, mapping) => {\n if (yDomFragment instanceof Y.XmlElement && yDomFragment.nodeName !== pNode.type.name) {\n throw new Error('node name mismatch!')\n }\n mapping.set(yDomFragment, pNode)\n // update attributes\n if (yDomFragment instanceof Y.XmlElement) {\n const yDomAttrs = yDomFragment.getAttributes()\n const pAttrs = pNode.attrs\n for (const key in pAttrs) {\n if (pAttrs[key] !== null) {\n if (yDomAttrs[key] !== pAttrs[key] && key !== 'ychange') {\n yDomFragment.setAttribute(key, pAttrs[key])\n }\n } else {\n yDomFragment.removeAttribute(key)\n }\n }\n // remove all keys that are no longer in pAttrs\n for (const key in yDomAttrs) {\n if (pAttrs[key] === undefined) {\n yDomFragment.removeAttribute(key)\n }\n }\n }\n // update children\n const pChildren = normalizePNodeContent(pNode)\n const pChildCnt = pChildren.length\n const yChildren = yDomFragment.toArray()\n const yChildCnt = yChildren.length\n const minCnt = min(pChildCnt, yChildCnt)\n let left = 0\n let right = 0\n // find number of matching elements from left\n for (;left < minCnt; left++) {\n const leftY = yChildren[left]\n const leftP = pChildren[left]\n if (!mappedIdentity(mapping.get(leftY), leftP)) {\n if (equalYTypePNode(leftY, leftP)) {\n // update mapping\n mapping.set(leftY, leftP)\n } else {\n break\n }\n }\n }\n // find number of matching elements from right\n for (;right + left + 1 < minCnt; right++) {\n const rightY = yChildren[yChildCnt - right - 1]\n const rightP = pChildren[pChildCnt - right - 1]\n if (!mappedIdentity(mapping.get(rightY), rightP)) {\n if (equalYTypePNode(rightY, rightP)) {\n // update mapping\n mapping.set(rightY, rightP)\n } else {\n break\n }\n }\n }\n y.transact(() => {\n // try to compare and update\n while (yChildCnt - left - right > 0 && pChildCnt - left - right > 0) {\n const leftY = yChildren[left]\n const leftP = pChildren[left]\n const rightY = yChildren[yChildCnt - right - 1]\n const rightP = pChildren[pChildCnt - right - 1]\n if (leftY instanceof Y.XmlText && leftP instanceof Array) {\n if (!equalYTextPText(leftY, leftP)) {\n updateYText(leftY, leftP, mapping)\n }\n left += 1\n } else {\n let updateLeft = leftY instanceof Y.XmlElement && matchNodeName(leftY, leftP)\n let updateRight = rightY instanceof Y.XmlElement && matchNodeName(rightY, rightP)\n if (updateLeft && updateRight) {\n // decide which which element to update\n const equalityLeft = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (leftY), /** @type {PMNode} */ (leftP), mapping)\n const equalityRight = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (rightY), /** @type {PMNode} */ (rightP), mapping)\n if (equalityLeft.foundMappedChild && !equalityRight.foundMappedChild) {\n updateRight = false\n } else if (!equalityLeft.foundMappedChild && equalityRight.foundMappedChild) {\n updateLeft = false\n } else if (equalityLeft.equalityFactor < equalityRight.equalityFactor) {\n updateLeft = false\n } else {\n updateRight = false\n }\n }\n if (updateLeft) {\n updateYFragment(y, /** @type {Y.XmlFragment} */ (leftY), /** @type {PMNode} */ (leftP), mapping)\n left += 1\n } else if (updateRight) {\n updateYFragment(y, /** @type {Y.XmlFragment} */ (rightY), /** @type {PMNode} */ (rightP), mapping)\n right += 1\n } else {\n yDomFragment.delete(left, 1)\n yDomFragment.insert(left, [createTypeFromTextOrElementNode(leftP, mapping)])\n left += 1\n }\n }\n }\n const yDelLen = yChildCnt - left - right\n if (yDelLen > 0) {\n yDomFragment.delete(left, yDelLen)\n }\n if (left + right < pChildCnt) {\n const ins = []\n for (let i = left; i < pChildCnt - right; i++) {\n ins.push(createTypeFromTextOrElementNode(pChildren[i], mapping))\n }\n yDomFragment.insert(left, ins)\n }\n }, ySyncPluginKey)\n}\n\n/**\n * @function\n * @param {Y.XmlElement} yElement\n * @param {any} pNode Prosemirror Node\n */\nconst matchNodeName = (yElement, pNode) => !(pNode instanceof Array) && yElement.nodeName === pNode.type.name\n","import { updateYFragment } from './plugins/sync-plugin.js' // eslint-disable-line\nimport * as Y from 'yjs'\nimport { EditorView } from 'prosemirror-view' // eslint-disable-line\nimport { Node, Schema } from 'prosemirror-model' // eslint-disable-line\nimport * as error from 'lib0/error.js'\nimport * as map from 'lib0/map.js'\nimport * as eventloop from 'lib0/eventloop.js'\n\n/**\n * Either a node if type is YXmlElement or an Array of text nodes if YXmlText\n * @typedef {Map>} ProsemirrorMapping\n */\n\n/**\n * Is null if no timeout is in progress.\n * Is defined if a timeout is in progress.\n * Maps from view\n * @type {Map>|null}\n */\nlet viewsToUpdate = null\n\nconst updateMetas = () => {\n const ups = /** @type {Map>} */ (viewsToUpdate)\n viewsToUpdate = null\n ups.forEach((metas, view) => {\n const tr = view.state.tr\n metas.forEach((val, key) => {\n tr.setMeta(key, val)\n })\n view.dispatch(tr)\n })\n}\n\nexport const setMeta = (view, key, value) => {\n if (!viewsToUpdate) {\n viewsToUpdate = new Map()\n eventloop.timeout(0, updateMetas)\n }\n map.setIfUndefined(viewsToUpdate, view, map.create).set(key, value)\n}\n\n/**\n * Transforms a Prosemirror based absolute position to a Yjs Cursor (relative position in the Yjs model).\n *\n * @param {number} pos\n * @param {Y.XmlFragment} type\n * @param {ProsemirrorMapping} mapping\n * @return {any} relative position\n */\nexport const absolutePositionToRelativePosition = (pos, type, mapping) => {\n if (pos === 0) {\n return Y.createRelativePositionFromTypeIndex(type, 0)\n }\n let n = type._first === null ? null : /** @type {Y.ContentType} */ (type._first.content).type\n while (n !== null && type !== n) {\n if (n.constructor === Y.XmlText) {\n if (n._length >= pos) {\n return Y.createRelativePositionFromTypeIndex(n, pos)\n } else {\n pos -= n._length\n }\n if (n._item !== null && n._item.next !== null) {\n n = /** @type {Y.ContentType} */ (n._item.next.content).type\n } else {\n do {\n n = n._item === null ? null : n._item.parent\n pos--\n } while (n !== type && n !== null && n._item !== null && n._item.next === null)\n if (n !== null && n !== type) {\n // @ts-gnore we know that n.next !== null because of above loop conditition\n n = n._item === null ? null : /** @type {Y.ContentType} */ (/** @type Y.Item */ (n._item.next).content).type\n }\n }\n } else {\n const pNodeSize = /** @type {any} */ (mapping.get(n) || { nodeSize: 0 }).nodeSize\n if (n._first !== null && pos < pNodeSize) {\n n = /** @type {Y.ContentType} */ (n._first.content).type\n pos--\n } else {\n if (pos === 1 && n._length === 0 && pNodeSize > 1) {\n // edge case, should end in this paragraph\n return new Y.RelativePosition(n._item === null ? null : n._item.id, n._item === null ? Y.findRootTypeKey(n) : null, null)\n }\n pos -= pNodeSize\n if (n._item !== null && n._item.next !== null) {\n n = /** @type {Y.ContentType} */ (n._item.next.content).type\n } else {\n if (pos === 0) {\n // set to end of n.parent\n n = n._item === null ? n : n._item.parent\n return new Y.RelativePosition(n._item === null ? null : n._item.id, n._item === null ? Y.findRootTypeKey(n) : null, null)\n }\n do {\n n = /** @type {Y.Item} */ (n._item).parent\n pos--\n } while (n !== type && /** @type {Y.Item} */ (n._item).next === null)\n // if n is null at this point, we have an unexpected case\n if (n !== type) {\n // We know that n._item.next is defined because of above loop condition\n n = /** @type {Y.ContentType} */ (/** @type {Y.Item} */ (/** @type {Y.Item} */ (n._item).next).content).type\n }\n }\n }\n }\n if (n === null) {\n throw error.unexpectedCase()\n }\n if (pos === 0 && n.constructor !== Y.XmlText && n !== type) { // TODO: set to <= 0\n return createRelativePosition(n._item.parent, n._item)\n }\n }\n return Y.createRelativePositionFromTypeIndex(type, type._length)\n}\n\nconst createRelativePosition = (type, item) => {\n let typeid = null\n let tname = null\n if (type._item === null) {\n tname = Y.findRootTypeKey(type)\n } else {\n typeid = Y.createID(type._item.id.client, type._item.id.clock)\n }\n return new Y.RelativePosition(typeid, tname, item.id)\n}\n\n/**\n * @param {Y.Doc} y\n * @param {Y.XmlFragment} documentType Top level type that is bound to pView\n * @param {any} relPos Encoded Yjs based relative position\n * @param {ProsemirrorMapping} mapping\n * @return {null|number}\n */\nexport const relativePositionToAbsolutePosition = (y, documentType, relPos, mapping) => {\n const decodedPos = Y.createAbsolutePositionFromRelativePosition(relPos, y)\n if (decodedPos === null || (decodedPos.type !== documentType && !Y.isParentOf(documentType, decodedPos.type._item))) {\n return null\n }\n let type = decodedPos.type\n let pos = 0\n if (type.constructor === Y.XmlText) {\n pos = decodedPos.index\n } else if (type._item === null || !type._item.deleted) {\n let n = type._first\n let i = 0\n while (i < type._length && i < decodedPos.index && n !== null) {\n if (!n.deleted) {\n const t = /** @type {Y.ContentType} */ (n.content).type\n i++\n if (t.constructor === Y.XmlText) {\n pos += t._length\n } else {\n pos += /** @type {any} */ (mapping.get(t)).nodeSize\n }\n }\n n = /** @type {Y.Item} */ (n.right)\n }\n pos += 1 // increase because we go out of n\n }\n while (type !== documentType && type._item !== null) {\n // @ts-ignore\n const parent = type._item.parent\n // @ts-ignore\n if (parent._item === null || !parent._item.deleted) {\n pos += 1 // the start tag\n let n = parent._first\n // now iterate until we found type\n while (n !== null) {\n const contentType = /** @type {Y.ContentType} */ (n.content).type\n if (contentType === type) {\n break\n }\n if (!n.deleted) {\n if (contentType.constructor === Y.XmlText) {\n pos += contentType._length\n } else {\n pos += /** @type {any} */ (mapping.get(contentType)).nodeSize\n }\n }\n n = n.right\n }\n }\n type = parent\n }\n return pos - 1 // we don't count the most outer tag, because it is a fragment\n}\n\n/**\n * Utility method to convert a Prosemirror Doc Node into a Y.Doc.\n *\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param {Node} doc\n * @param {string} xmlFragment\n * @return {Y.Doc}\n */\nexport function prosemirrorToYDoc (doc, xmlFragment = 'prosemirror') {\n const ydoc = new Y.Doc()\n const type = ydoc.get(xmlFragment, Y.XmlFragment)\n if (!type.doc) {\n return ydoc\n }\n\n updateYFragment(type.doc, type, doc, new Map())\n return type.doc\n}\n\n/**\n * Utility method to convert Prosemirror compatible JSON into a Y.Doc.\n *\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param {Schema} schema\n * @param {any} state\n * @param {string} xmlFragment\n * @return {Y.Doc}\n */\nexport function prosemirrorJSONToYDoc (schema, state, xmlFragment = 'prosemirror') {\n const doc = Node.fromJSON(schema, state)\n return prosemirrorToYDoc(doc, xmlFragment)\n}\n\n/**\n * Utility method to convert a Y.Doc to a Prosemirror Doc node.\n *\n * @param {Schema} schema\n * @param {Y.Doc} ydoc\n * @return {Node}\n */\nexport function yDocToProsemirror (schema, ydoc) {\n const state = yDocToProsemirrorJSON(ydoc)\n return Node.fromJSON(schema, state)\n}\n\n/**\n * Utility method to convert a Y.Doc to Prosemirror compatible JSON.\n *\n * @param {Y.Doc} ydoc\n * @param {string} xmlFragment\n * @return {Record}\n */\nexport function yDocToProsemirrorJSON (\n ydoc,\n xmlFragment = 'prosemirror'\n) {\n const items = ydoc.getXmlFragment(xmlFragment).toArray()\n\n function serialize (item) {\n /**\n * @type {Object} NodeObject\n * @property {string} NodeObject.type\n * @property {Record=} NodeObject.attrs\n * @property {Array=} NodeObject.content\n */\n let response\n\n // TODO: Must be a better way to detect text nodes than this\n if (!item.nodeName) {\n const delta = item.toDelta()\n response = delta.map((d) => {\n const text = {\n type: 'text',\n text: d.insert\n }\n\n if (d.attributes) {\n text.marks = Object.keys(d.attributes).map((type) => {\n const attrs = d.attributes[type]\n const mark = {\n type\n }\n\n if (Object.keys(attrs)) {\n mark.attrs = attrs\n }\n\n return mark\n })\n }\n return text\n })\n } else {\n response = {\n type: item.nodeName\n }\n\n const attrs = item.getAttributes()\n if (Object.keys(attrs).length) {\n response.attrs = attrs\n }\n\n const children = item.toArray()\n if (children.length) {\n response.content = children.map(serialize).flat()\n }\n }\n\n return response\n }\n\n return {\n type: 'doc',\n content: items.map(serialize)\n }\n}\n","\nimport * as Y from 'yjs'\nimport { Decoration, DecorationSet } from 'prosemirror-view' // eslint-disable-line\nimport { Plugin } from 'prosemirror-state' // eslint-disable-line\nimport { Awareness } from 'y-protocols/awareness.js' // eslint-disable-line\nimport { absolutePositionToRelativePosition, relativePositionToAbsolutePosition, setMeta } from '../lib.js'\nimport { yCursorPluginKey, ySyncPluginKey } from './keys.js'\n\nimport * as math from 'lib0/math.js'\n\n/**\n * Default generator for a cursor element\n *\n * @param {any} user user data\n * @return HTMLElement\n */\nexport const defaultCursorBuilder = user => {\n const cursor = document.createElement('span')\n cursor.classList.add('ProseMirror-yjs-cursor')\n cursor.setAttribute('style', `border-color: ${user.color}`)\n const userDiv = document.createElement('div')\n userDiv.setAttribute('style', `background-color: ${user.color}`)\n userDiv.insertBefore(document.createTextNode(user.name), null)\n cursor.insertBefore(userDiv, null)\n return cursor\n}\n\n/**\n * @param {any} state\n * @param {Awareness} awareness\n * @return {any} DecorationSet\n */\nexport const createDecorations = (state, awareness, createCursor) => {\n const ystate = ySyncPluginKey.getState(state)\n const y = ystate.doc\n const decorations = []\n if (ystate.snapshot != null || ystate.prevSnapshot != null || ystate.binding === null) {\n // do not render cursors while snapshot is active\n return DecorationSet.create(state.doc, [])\n }\n awareness.getStates().forEach((aw, clientId) => {\n if (clientId === y.clientID) {\n return\n }\n if (aw.cursor != null) {\n const user = aw.user || {}\n if (user.color == null) {\n user.color = '#ffa500'\n }\n if (user.name == null) {\n user.name = `User: ${clientId}`\n }\n let anchor = relativePositionToAbsolutePosition(y, ystate.type, Y.createRelativePositionFromJSON(aw.cursor.anchor), ystate.binding.mapping)\n let head = relativePositionToAbsolutePosition(y, ystate.type, Y.createRelativePositionFromJSON(aw.cursor.head), ystate.binding.mapping)\n if (anchor !== null && head !== null) {\n const maxsize = math.max(state.doc.content.size - 1, 0)\n anchor = math.min(anchor, maxsize)\n head = math.min(head, maxsize)\n decorations.push(Decoration.widget(head, () => createCursor(user), { key: clientId + '', side: 10 }))\n const from = math.min(anchor, head)\n const to = math.max(anchor, head)\n decorations.push(Decoration.inline(from, to, { style: `background-color: ${user.color}70` }, { inclusiveEnd: true, inclusiveStart: false }))\n }\n }\n })\n return DecorationSet.create(state.doc, decorations)\n}\n\n/**\n * A prosemirror plugin that listens to awareness information on Yjs.\n * This requires that a `prosemirrorPlugin` is also bound to the prosemirror.\n *\n * @public\n * @param {Awareness} awareness\n * @param {object} [opts]\n * @param {function(any):HTMLElement} [opts.cursorBuilder]\n * @param {function(any):any} [opts.getSelection]\n * @param {string} [opts.cursorStateField] By default all editor bindings use the awareness 'cursor' field to propagate cursor information.\n * @return {any}\n */\nexport const yCursorPlugin = (awareness, { cursorBuilder = defaultCursorBuilder, getSelection = state => state.selection } = {}, cursorStateField = 'cursor') => new Plugin({\n key: yCursorPluginKey,\n state: {\n init (_, state) {\n return createDecorations(state, awareness, cursorBuilder)\n },\n apply (tr, prevState, oldState, newState) {\n const ystate = ySyncPluginKey.getState(newState)\n const yCursorState = tr.getMeta(yCursorPluginKey)\n if ((ystate && ystate.isChangeOrigin) || (yCursorState && yCursorState.awarenessUpdated)) {\n return createDecorations(newState, awareness, cursorBuilder)\n }\n return prevState.map(tr.mapping, tr.doc)\n }\n },\n props: {\n decorations: state => {\n return yCursorPluginKey.getState(state)\n }\n },\n view: view => {\n const awarenessListener = () => {\n // @ts-ignore\n if (view.docView) {\n setMeta(view, yCursorPluginKey, { awarenessUpdated: true })\n }\n }\n const updateCursorInfo = () => {\n const ystate = ySyncPluginKey.getState(view.state)\n // @note We make implicit checks when checking for the cursor property\n const current = awareness.getLocalState() || {}\n if (view.hasFocus() && ystate.binding !== null) {\n const selection = getSelection(view.state)\n /**\n * @type {Y.RelativePosition}\n */\n const anchor = absolutePositionToRelativePosition(selection.anchor, ystate.type, ystate.binding.mapping)\n /**\n * @type {Y.RelativePosition}\n */\n const head = absolutePositionToRelativePosition(selection.head, ystate.type, ystate.binding.mapping)\n if (current.cursor == null || !Y.compareRelativePositions(Y.createRelativePositionFromJSON(current.cursor.anchor), anchor) || !Y.compareRelativePositions(Y.createRelativePositionFromJSON(current.cursor.head), head)) {\n awareness.setLocalStateField(cursorStateField, {\n anchor, head\n })\n }\n } else if (current.cursor != null && relativePositionToAbsolutePosition(ystate.doc, ystate.type, Y.createRelativePositionFromJSON(current.cursor.anchor), ystate.binding.mapping) !== null) {\n // delete cursor information if current cursor information is owned by this editor binding\n awareness.setLocalStateField(cursorStateField, null)\n }\n }\n awareness.on('change', awarenessListener)\n view.dom.addEventListener('focusin', updateCursorInfo)\n view.dom.addEventListener('focusout', updateCursorInfo)\n return {\n update: updateCursorInfo,\n destroy: () => {\n view.dom.removeEventListener('focusin', updateCursorInfo)\n view.dom.removeEventListener('focusout', updateCursorInfo)\n awareness.off('change', awarenessListener)\n awareness.setLocalStateField(cursorStateField, null)\n }\n }\n }\n})\n","\nimport { Plugin, PluginKey } from 'prosemirror-state' // eslint-disable-line\n\nimport { getRelativeSelection } from './sync-plugin.js'\nimport { UndoManager, Item, ContentType, XmlElement, Text } from 'yjs'\nimport { yUndoPluginKey, ySyncPluginKey } from './keys.js'\n\nexport const undo = state => {\n const undoManager = yUndoPluginKey.getState(state).undoManager\n if (undoManager != null) {\n undoManager.undo()\n return true\n }\n}\n\nexport const redo = state => {\n const undoManager = yUndoPluginKey.getState(state).undoManager\n if (undoManager != null) {\n undoManager.redo()\n return true\n }\n}\n\nexport const yUndoPlugin = ({ protectedNodes = new Set(['paragraph']), trackedOrigins = [] } = {}) => new Plugin({\n key: yUndoPluginKey,\n state: {\n init: (initargs, state) => {\n // TODO: check if plugin order matches and fix\n const ystate = ySyncPluginKey.getState(state)\n const undoManager = new UndoManager(ystate.type, {\n trackedOrigins: new Set([ySyncPluginKey].concat(trackedOrigins)),\n deleteFilter: item => !(item instanceof Item) ||\n !(item.content instanceof ContentType) ||\n !(item.content.type instanceof Text ||\n (item.content.type instanceof XmlElement && protectedNodes.has(item.content.type.nodeName))) ||\n item.content.type._length === 0\n })\n return {\n undoManager,\n prevSel: null,\n hasUndoOps: undoManager.undoStack.length > 0,\n hasRedoOps: undoManager.redoStack.length > 0\n }\n },\n apply: (tr, val, oldState, state) => {\n const binding = ySyncPluginKey.getState(state).binding\n const undoManager = val.undoManager\n const hasUndoOps = undoManager.undoStack.length > 0\n const hasRedoOps = undoManager.redoStack.length > 0\n if (binding) {\n return {\n undoManager,\n prevSel: getRelativeSelection(binding, oldState),\n hasUndoOps,\n hasRedoOps\n }\n } else {\n if (hasUndoOps !== val.hasUndoOps || hasRedoOps !== val.hasRedoOps) {\n return Object.assign({}, val, {\n hasUndoOps: undoManager.undoStack.length > 0,\n hasRedoOps: undoManager.redoStack.length > 0\n })\n } else { // nothing changed\n return val\n }\n }\n }\n },\n view: view => {\n const ystate = ySyncPluginKey.getState(view.state)\n const undoManager = yUndoPluginKey.getState(view.state).undoManager\n undoManager.on('stack-item-added', ({ stackItem }) => {\n const binding = ystate.binding\n if (binding) {\n stackItem.meta.set(binding, yUndoPluginKey.getState(view.state).prevSel)\n }\n })\n undoManager.on('stack-item-popped', ({ stackItem }) => {\n const binding = ystate.binding\n if (binding) {\n binding.beforeTransactionSelection = stackItem.meta.get(binding) || binding.beforeTransactionSelection\n }\n })\n return {\n destroy: () => {\n undoManager.destroy()\n }\n }\n }\n})\n"],"names":["PluginKey","Y.isDeleted","Plugin","TextSelection","createMutex","isBrowser","doc","Y.createSnapshot","Y.createDeleteSet","PMSlice","PMFragment","Y.snapshot","Y.iterateDeletedStructs","Y.typeListToArraySnapshot","Y.Snapshot","Y.Item","Y.XmlElement","methodUnimplemented","Y.XmlText","keys","min","Y.ContentString","Y.ContentFormat","simpleDiff","eventloop.timeout","map.setIfUndefined","map.create","Y.createRelativePositionFromTypeIndex","Y.RelativePosition","Y.findRootTypeKey","error.unexpectedCase","Y.createID","Y.createAbsolutePositionFromRelativePosition","Y.isParentOf","Y.Doc","Y.XmlFragment","Node","DecorationSet","Y.createRelativePositionFromJSON","math.max","math.min","Decoration","Y.compareRelativePositions","UndoManager","Item","ContentType","Text","XmlElement"],"mappings":";;;;;;;;;;;;;;;;;;;AAGA;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG,IAAIA,0BAAS,CAAC,QAAQ,EAAC;AACrD;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG,IAAIA,0BAAS,CAAC,QAAQ,EAAC;AACrD;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,gBAAgB,GAAG,IAAIA,0BAAS,CAAC,YAAY;;ACtB1D;AACA;AACA;AAcA;AACA;AACA;AACA;AACA;AACY,MAAC,SAAS,GAAG,CAAC,IAAI,EAAE,QAAQ,KAAK,QAAQ,KAAK,SAAS,GAAG,CAAC,IAAI,CAAC,OAAO,IAAI,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,MAAM,CAAC,0BAA0B,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC,EAAE,CAAC,KAAK,IAAI,CAACC,WAAW,CAAC,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC,EAAE,CAAC,EAAC;AACxO;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,SAAS,EAAE,EAAC;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,YAAY,GAAG,CAAC,YAAY,EAAE,MAAM,EAAE,IAAI,KAAK;AACrD,EAAE,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE;AAC/B,IAAI,YAAY,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,YAAY,CAAC,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,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AAG,MAAM,CAAC,QAAO;AACpC,MAAM,IAAI,OAAO,EAAE;AACnB,QAAQ,OAAO,CAAC,0BAA0B,GAAG,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,2BAA0B;AAC9G,OAAO;AACP,KAAK,EAAC;AACN,IAAI,OAAO;AACX,MAAM,OAAO,EAAE,MAAM;AACrB,QAAQ,WAAW,CAAC,OAAO,GAAE;AAC7B,OAAO;AACP,KAAK;AACL,GAAG;AACH,CAAC;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file From c96ec7cb05d5d31ecec316d4b545a8de7aa065ca Mon Sep 17 00:00:00 2001 From: brian hung Date: Wed, 19 May 2021 17:06:26 -0700 Subject: [PATCH 2/2] initialContent option --- demo/dist/prosemirror.js | 27629 ++++++++++++++++++++++++++++ demo/dist/prosemirror.js.map | 1 + dist/src/plugins/sync-plugin.d.ts | 3 +- dist/test.cjs | 23 +- dist/test.cjs.map | 2 +- dist/test.js | 23 +- dist/test.js.map | 2 +- dist/y-prosemirror.cjs | 23 +- dist/y-prosemirror.cjs.map | 2 +- src/plugins/sync-plugin.js | 23 +- 10 files changed, 27683 insertions(+), 48 deletions(-) create mode 100644 demo/dist/prosemirror.js create mode 100644 demo/dist/prosemirror.js.map diff --git a/demo/dist/prosemirror.js b/demo/dist/prosemirror.js new file mode 100644 index 0000000..79f976b --- /dev/null +++ b/demo/dist/prosemirror.js @@ -0,0 +1,27629 @@ +(function () { + 'use strict'; + + /** + * Utility module to work with key-value stores. + * + * @module map + */ + + /** + * Creates a new Map instance. + * + * @function + * @return {Map} + * + * @function + */ + const create = () => new Map(); + + /** + * Copy a Map object into a fresh Map object. + * + * @function + * @template X,Y + * @param {Map} m + * @return {Map} + */ + const copy = m => { + const r = create(); + m.forEach((v, k) => { r.set(k, v); }); + return r + }; + + /** + * Get map property. Create T if property is undefined and set T on map. + * + * ```js + * const listeners = map.setIfUndefined(events, 'eventName', set.create) + * listeners.add(listener) + * ``` + * + * @function + * @template T,K + * @param {Map} map + * @param {K} key + * @param {function():T} createT + * @return {T} + */ + const setIfUndefined = (map, key, createT) => { + let set = map.get(key); + if (set === undefined) { + map.set(key, set = createT()); + } + return set + }; + + /** + * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function. + * + * @function + * @template K + * @template V + * @template R + * @param {Map} m + * @param {function(V,K):R} f + * @return {Array} + */ + const map = (m, f) => { + const res = []; + for (const [key, value] of m) { + res.push(f(value, key)); + } + return res + }; + + /** + * Tests whether any key-value pairs pass the test implemented by `f(value, key)`. + * + * @todo should rename to some - similarly to Array.some + * + * @function + * @template K + * @template V + * @param {Map} m + * @param {function(V,K):boolean} f + * @return {boolean} + */ + const any = (m, f) => { + for (const [key, value] of m) { + if (f(value, key)) { + return true + } + } + return false + }; + + /** + * Utility module to work with sets. + * + * @module set + */ + + const create$1 = () => new Set(); + + /** + * Utility module to work with Arrays. + * + * @module array + */ + + /** + * Return the last element of an array. The element must exist + * + * @template L + * @param {Array} arr + * @return {L} + */ + const last = arr => arr[arr.length - 1]; + + /** + * Append elements from src to dest + * + * @template M + * @param {Array} dest + * @param {Array} src + */ + const appendTo = (dest, src) => { + for (let i = 0; i < src.length; i++) { + dest.push(src[i]); + } + }; + + /** + * Transforms something array-like to an actual Array. + * + * @function + * @template T + * @param {ArrayLike|Iterable} arraylike + * @return {T} + */ + const from = Array.from; + + /** + * Observable class prototype. + * + * @module observable + */ + + /** + * Handles named events. + * + * @template N + */ + class Observable { + constructor () { + /** + * Some desc. + * @type {Map} + */ + this._observers = create(); + } + + /** + * @param {N} name + * @param {function} f + */ + on (name, f) { + setIfUndefined(this._observers, name, create$1).add(f); + } + + /** + * @param {N} name + * @param {function} f + */ + once (name, f) { + /** + * @param {...any} args + */ + const _f = (...args) => { + this.off(name, _f); + f(...args); + }; + this.on(name, _f); + } + + /** + * @param {N} name + * @param {function} f + */ + off (name, f) { + const observers = this._observers.get(name); + if (observers !== undefined) { + observers.delete(f); + if (observers.size === 0) { + this._observers.delete(name); + } + } + } + + /** + * Emit a named event. All registered event listeners that listen to the + * specified name will receive the event. + * + * @todo This should catch exceptions + * + * @param {N} name The event name. + * @param {Array} args The arguments that are applied to the event listener. + */ + emit (name, args) { + // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called. + return from((this._observers.get(name) || create()).values()).forEach(f => f(...args)) + } + + destroy () { + this._observers = create(); + } + } + + /** + * Common Math expressions. + * + * @module math + */ + + const floor = Math.floor; + const abs = Math.abs; + const log10 = Math.log10; + + /** + * @function + * @param {number} a + * @param {number} b + * @return {number} The smaller element of a and b + */ + const min = (a, b) => a < b ? a : b; + + /** + * @function + * @param {number} a + * @param {number} b + * @return {number} The bigger element of a and b + */ + const max = (a, b) => a > b ? a : b; + + /** + * @param {number} n + * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0 + */ + const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0; + + /** + * Utility module to work with strings. + * + * @module string + */ + + const fromCharCode = String.fromCharCode; + + /** + * @param {string} s + * @return {string} + */ + const toLowerCase = s => s.toLowerCase(); + + const trimLeftRegex = /^\s*/g; + + /** + * @param {string} s + * @return {string} + */ + const trimLeft = s => s.replace(trimLeftRegex, ''); + + const fromCamelCaseRegex = /([A-Z])/g; + + /** + * @param {string} s + * @param {string} separator + * @return {string} + */ + const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`)); + + /** + * @param {string} str + * @return {Uint8Array} + */ + const _encodeUtf8Polyfill = str => { + const encodedString = unescape(encodeURIComponent(str)); + const len = encodedString.length; + const buf = new Uint8Array(len); + for (let i = 0; i < len; i++) { + buf[i] = /** @type {number} */ (encodedString.codePointAt(i)); + } + return buf + }; + + /* istanbul ignore next */ + const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null); + + /** + * @param {string} str + * @return {Uint8Array} + */ + const _encodeUtf8Native = str => utf8TextEncoder.encode(str); + + /** + * @param {string} str + * @return {Uint8Array} + */ + /* istanbul ignore next */ + const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill; + + /* istanbul ignore next */ + let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }); + + /* istanbul ignore next */ + if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) { + // Safari doesn't handle BOM correctly. + // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called. + // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and + // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call + // Another issue is that from then on no BOM chars are recognized anymore + /* istanbul ignore next */ + utf8TextDecoder = null; + } + + /** + * Often used conditions. + * + * @module conditions + */ + + /** + * @template T + * @param {T|null|undefined} v + * @return {T|null} + */ + /* istanbul ignore next */ + const undefinedToNull = v => v === undefined ? null : v; + + /* global localStorage */ + + /** + * Isomorphic variable storage. + * + * Uses LocalStorage in the browser and falls back to in-memory storage. + * + * @module storage + */ + + /* istanbul ignore next */ + class VarStoragePolyfill { + constructor () { + this.map = new Map(); + } + + /** + * @param {string} key + * @param {any} value + */ + setItem (key, value) { + this.map.set(key, value); + } + + /** + * @param {string} key + */ + getItem (key) { + return this.map.get(key) + } + } + + /* istanbul ignore next */ + /** + * @type {any} + */ + let _localStorage = new VarStoragePolyfill(); + + try { + // if the same-origin rule is violated, accessing localStorage might thrown an error + /* istanbul ignore next */ + if (typeof localStorage !== 'undefined') { + _localStorage = localStorage; + } + } catch (e) { } + + /* istanbul ignore next */ + /** + * This is basically localStorage in browser, or a polyfill in nodejs + */ + const varStorage = _localStorage; + + /** + * Isomorphic module to work access the environment (query params, env variables). + * + * @module map + */ + + /* istanbul ignore next */ + // @ts-ignore + const isNode = typeof process !== 'undefined' && process.release && /node|io\.js/.test(process.release.name); + /* istanbul ignore next */ + const isBrowser = typeof window !== 'undefined' && !isNode; + /* istanbul ignore next */ + const isMac = typeof navigator !== 'undefined' ? /Mac/.test(navigator.platform) : false; + + /** + * @type {Map} + */ + let params; + + /* istanbul ignore next */ + const computeParams = () => { + if (params === undefined) { + if (isNode) { + params = create(); + const pargs = process.argv; + let currParamName = null; + /* istanbul ignore next */ + for (let i = 0; i < pargs.length; i++) { + const parg = pargs[i]; + if (parg[0] === '-') { + if (currParamName !== null) { + params.set(currParamName, ''); + } + currParamName = parg; + } else { + if (currParamName !== null) { + params.set(currParamName, parg); + currParamName = null; + } + } + } + if (currParamName !== null) { + params.set(currParamName, ''); + } + // in ReactNative for example this would not be true (unless connected to the Remote Debugger) + } else if (typeof location === 'object') { + params = create() + // eslint-disable-next-line no-undef + ;(location.search || '?').slice(1).split('&').forEach(kv => { + if (kv.length !== 0) { + const [key, value] = kv.split('='); + params.set(`--${fromCamelCase(key, '-')}`, value); + params.set(`-${fromCamelCase(key, '-')}`, value); + } + }); + } else { + params = create(); + } + } + return params + }; + + /** + * @param {string} name + * @return {boolean} + */ + /* istanbul ignore next */ + const hasParam = name => computeParams().has(name); + // export const getArgs = name => computeParams() && args + + /** + * @param {string} name + * @return {string|null} + */ + /* istanbul ignore next */ + const getVariable = name => isNode ? undefinedToNull(process.env[name.toUpperCase()]) : undefinedToNull(varStorage.getItem(name)); + + /** + * @param {string} name + * @return {boolean} + */ + /* istanbul ignore next */ + const hasConf = name => hasParam('--' + name) || getVariable(name) !== null; + + /* istanbul ignore next */ + const production = hasConf('production'); + + /* eslint-env browser */ + + /** + * Binary data constants. + * + * @module binary + */ + + /** + * n-th bit activated. + * + * @type {number} + */ + const BIT1 = 1; + const BIT2 = 2; + const BIT3 = 4; + const BIT4 = 8; + const BIT6 = 32; + const BIT7 = 64; + const BIT8 = 128; + const BITS5 = 31; + const BITS6 = 63; + const BITS7 = 127; + /** + * @type {number} + */ + const BITS31 = 0x7FFFFFFF; + + /** + * Efficient schema-less binary decoding with support for variable length encoding. + * + * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function. + * + * Encodes numbers in little-endian order (least to most significant byte order) + * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/) + * which is also used in Protocol Buffers. + * + * ```js + * // encoding step + * const encoder = new encoding.createEncoder() + * encoding.writeVarUint(encoder, 256) + * encoding.writeVarString(encoder, 'Hello world!') + * const buf = encoding.toUint8Array(encoder) + * ``` + * + * ```js + * // decoding step + * const decoder = new decoding.createDecoder(buf) + * decoding.readVarUint(decoder) // => 256 + * decoding.readVarString(decoder) // => 'Hello world!' + * decoding.hasContent(decoder) // => false - all data is read + * ``` + * + * @module decoding + */ + + /** + * A Decoder handles the decoding of an Uint8Array. + */ + class Decoder { + /** + * @param {Uint8Array} uint8Array Binary data to decode + */ + constructor (uint8Array) { + /** + * Decoding target. + * + * @type {Uint8Array} + */ + this.arr = uint8Array; + /** + * Current decoding position. + * + * @type {number} + */ + this.pos = 0; + } + } + + /** + * @function + * @param {Uint8Array} uint8Array + * @return {Decoder} + */ + const createDecoder = uint8Array => new Decoder(uint8Array); + + /** + * @function + * @param {Decoder} decoder + * @return {boolean} + */ + const hasContent = decoder => decoder.pos !== decoder.arr.length; + + /** + * Create an Uint8Array view of the next `len` bytes and advance the position by `len`. + * + * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks. + * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array. + * + * @function + * @param {Decoder} decoder The decoder instance + * @param {number} len The length of bytes to read + * @return {Uint8Array} + */ + const readUint8Array = (decoder, len) => { + const view = createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len); + decoder.pos += len; + return view + }; + + /** + * Read variable length Uint8Array. + * + * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks. + * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array. + * + * @function + * @param {Decoder} decoder + * @return {Uint8Array} + */ + const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder)); + + /** + * Read one byte as unsigned integer. + * @function + * @param {Decoder} decoder The decoder instance + * @return {number} Unsigned 8-bit integer + */ + const readUint8 = decoder => decoder.arr[decoder.pos++]; + + /** + * Read unsigned integer (32bit) with variable length. + * 1/8th of the storage is used as encoding overhead. + * * numbers < 2^7 is stored in one bytlength + * * numbers < 2^14 is stored in two bylength + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer.length + */ + const readVarUint = decoder => { + let num = 0; + let len = 0; + while (true) { + const r = decoder.arr[decoder.pos++]; + num = num | ((r & BITS7) << len); + len += 7; + if (r < BIT8) { + return num >>> 0 // return unsigned number! + } + /* istanbul ignore if */ + if (len > 35) { + throw new Error('Integer out of range!') + } + } + }; + + /** + * Read signed integer (32bit) with variable length. + * 1/8th of the storage is used as encoding overhead. + * * numbers < 2^7 is stored in one bytlength + * * numbers < 2^14 is stored in two bylength + * @todo This should probably create the inverse ~num if unmber is negative - but this would be a breaking change. + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer.length + */ + const readVarInt = decoder => { + let r = decoder.arr[decoder.pos++]; + let num = r & BITS6; + let len = 6; + const sign = (r & BIT7) > 0 ? -1 : 1; + if ((r & BIT8) === 0) { + // don't continue reading + return sign * num + } + while (true) { + r = decoder.arr[decoder.pos++]; + num = num | ((r & BITS7) << len); + len += 7; + if (r < BIT8) { + return sign * (num >>> 0) + } + /* istanbul ignore if */ + if (len > 41) { + throw new Error('Integer out of range!') + } + } + }; + + /** + * Read string of variable length + * * varUint is used to store the length of the string + * + * Transforming utf8 to a string is pretty expensive. The code performs 10x better + * when String.fromCodePoint is fed with all characters as arguments. + * But most environments have a maximum number of arguments per functions. + * For effiency reasons we apply a maximum of 10000 characters at once. + * + * @function + * @param {Decoder} decoder + * @return {String} The read String. + */ + const readVarString = decoder => { + let remainingLen = readVarUint(decoder); + if (remainingLen === 0) { + return '' + } else { + let encodedString = String.fromCodePoint(readUint8(decoder)); // remember to decrease remainingLen + if (--remainingLen < 100) { // do not create a Uint8Array for small strings + while (remainingLen--) { + encodedString += String.fromCodePoint(readUint8(decoder)); + } + } else { + while (remainingLen > 0) { + const nextLen = remainingLen < 10000 ? remainingLen : 10000; + // this is dangerous, we create a fresh array view from the existing buffer + const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen); + decoder.pos += nextLen; + // Starting with ES5.1 we can supply a generic array-like object as arguments + encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes)); + remainingLen -= nextLen; + } + } + return decodeURIComponent(escape(encodedString)) + } + }; + + /** + * @param {Decoder} decoder + * @param {number} len + * @return {DataView} + */ + const readFromDataView = (decoder, len) => { + const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len); + decoder.pos += len; + return dv + }; + + /** + * @param {Decoder} decoder + */ + const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0); + + /** + * @param {Decoder} decoder + */ + const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0); + + /** + * @param {Decoder} decoder + */ + const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0); + + /** + * @type {Array} + */ + const readAnyLookupTable = [ + decoder => undefined, // CASE 127: undefined + decoder => null, // CASE 126: null + readVarInt, // CASE 125: integer + readFloat32, // CASE 124: float32 + readFloat64, // CASE 123: float64 + readBigInt64, // CASE 122: bigint + decoder => false, // CASE 121: boolean (false) + decoder => true, // CASE 120: boolean (true) + readVarString, // CASE 119: string + decoder => { // CASE 118: object + const len = readVarUint(decoder); + /** + * @type {Object} + */ + const obj = {}; + for (let i = 0; i < len; i++) { + const key = readVarString(decoder); + obj[key] = readAny(decoder); + } + return obj + }, + decoder => { // CASE 117: array + const len = readVarUint(decoder); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(readAny(decoder)); + } + return arr + }, + readVarUint8Array // CASE 116: Uint8Array + ]; + + /** + * @param {Decoder} decoder + */ + const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder); + + /** + * T must not be null. + * + * @template T + */ + class RleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + * @param {function(Decoder):T} reader + */ + constructor (uint8Array, reader) { + super(uint8Array); + /** + * The reader + */ + this.reader = reader; + /** + * Current state + * @type {T|null} + */ + this.s = null; + this.count = 0; + } + + read () { + if (this.count === 0) { + this.s = this.reader(this); + if (hasContent(this)) { + this.count = readVarUint(this) + 1; // see encoder implementation for the reason why this is incremented + } else { + this.count = -1; // read the current value forever + } + } + this.count--; + return /** @type {T} */ (this.s) + } + } + + class UintOptRleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + super(uint8Array); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + } + + read () { + if (this.count === 0) { + this.s = readVarInt(this); + // if the sign is negative, we read the count too, otherwise count is 1 + const isNegative = isNegativeZero(this.s); + this.count = 1; + if (isNegative) { + this.s = -this.s; + this.count = readVarUint(this) + 2; + } + } + this.count--; + return /** @type {number} */ (this.s) + } + } + + class IntDiffOptRleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + super(uint8Array); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + this.diff = 0; + } + + /** + * @return {number} + */ + read () { + if (this.count === 0) { + const diff = readVarInt(this); + // if the first bit is set, we read more data + const hasCount = diff & 1; + this.diff = diff >> 1; + this.count = 1; + if (hasCount) { + this.count = readVarUint(this) + 2; + } + } + this.s += this.diff; + this.count--; + return this.s + } + } + + class StringDecoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + this.decoder = new UintOptRleDecoder(uint8Array); + this.str = readVarString(this.decoder); + /** + * @type {number} + */ + this.spos = 0; + } + + /** + * @return {string} + */ + read () { + const end = this.spos + this.decoder.read(); + const res = this.str.slice(this.spos, end); + this.spos = end; + return res + } + } + + /** + * Utility functions to work with buffers (Uint8Array). + * + * @module buffer + */ + + /** + * @param {number} len + */ + const createUint8ArrayFromLen = len => new Uint8Array(len); + + /** + * Create Uint8Array with initial content from buffer + * + * @param {ArrayBuffer} buffer + * @param {number} byteOffset + * @param {number} length + */ + const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length); + + /** + * Create Uint8Array with initial content from buffer + * + * @param {ArrayBuffer} buffer + */ + const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer); + + /* istanbul ignore next */ + /** + * @param {Uint8Array} bytes + * @return {string} + */ + const toBase64Browser = bytes => { + let s = ''; + for (let i = 0; i < bytes.byteLength; i++) { + s += fromCharCode(bytes[i]); + } + // eslint-disable-next-line no-undef + return btoa(s) + }; + + /** + * @param {Uint8Array} bytes + * @return {string} + */ + const toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64'); + + /* istanbul ignore next */ + /** + * @param {string} s + * @return {Uint8Array} + */ + const fromBase64Browser = s => { + // eslint-disable-next-line no-undef + const a = atob(s); + const bytes = createUint8ArrayFromLen(a.length); + for (let i = 0; i < a.length; i++) { + bytes[i] = a.charCodeAt(i); + } + return bytes + }; + + /** + * @param {string} s + */ + const fromBase64Node = s => { + const buf = Buffer.from(s, 'base64'); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) + }; + + /* istanbul ignore next */ + const toBase64 = isBrowser ? toBase64Browser : toBase64Node; + + /* istanbul ignore next */ + const fromBase64 = isBrowser ? fromBase64Browser : fromBase64Node; + + /** + * Copy the content of an Uint8Array view to a new ArrayBuffer. + * + * @param {Uint8Array} uint8Array + * @return {Uint8Array} + */ + const copyUint8Array = uint8Array => { + const newBuf = createUint8ArrayFromLen(uint8Array.byteLength); + newBuf.set(uint8Array); + return newBuf + }; + + /** + * Utility helpers for working with numbers. + * + * @module number + */ + + /** + * @module number + */ + + /* istanbul ignore next */ + const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && floor(num) === num); + + /** + * Efficient schema-less binary encoding with support for variable length encoding. + * + * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function. + * + * Encodes numbers in little-endian order (least to most significant byte order) + * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/) + * which is also used in Protocol Buffers. + * + * ```js + * // encoding step + * const encoder = new encoding.createEncoder() + * encoding.writeVarUint(encoder, 256) + * encoding.writeVarString(encoder, 'Hello world!') + * const buf = encoding.toUint8Array(encoder) + * ``` + * + * ```js + * // decoding step + * const decoder = new decoding.createDecoder(buf) + * decoding.readVarUint(decoder) // => 256 + * decoding.readVarString(decoder) // => 'Hello world!' + * decoding.hasContent(decoder) // => false - all data is read + * ``` + * + * @module encoding + */ + + /** + * A BinaryEncoder handles the encoding to an Uint8Array. + */ + class Encoder { + constructor () { + this.cpos = 0; + this.cbuf = new Uint8Array(100); + /** + * @type {Array} + */ + this.bufs = []; + } + } + + /** + * @function + * @return {Encoder} + */ + const createEncoder = () => new Encoder(); + + /** + * The current length of the encoded data. + * + * @function + * @param {Encoder} encoder + * @return {number} + */ + const length = encoder => { + let len = encoder.cpos; + for (let i = 0; i < encoder.bufs.length; i++) { + len += encoder.bufs[i].length; + } + return len + }; + + /** + * Transform to Uint8Array. + * + * @function + * @param {Encoder} encoder + * @return {Uint8Array} The created ArrayBuffer. + */ + const toUint8Array = encoder => { + const uint8arr = new Uint8Array(length(encoder)); + let curPos = 0; + for (let i = 0; i < encoder.bufs.length; i++) { + const d = encoder.bufs[i]; + uint8arr.set(d, curPos); + curPos += d.length; + } + uint8arr.set(createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos); + return uint8arr + }; + + /** + * Verify that it is possible to write `len` bytes wtihout checking. If + * necessary, a new Buffer with the required length is attached. + * + * @param {Encoder} encoder + * @param {number} len + */ + const verifyLen = (encoder, len) => { + const bufferLen = encoder.cbuf.length; + if (bufferLen - encoder.cpos < len) { + encoder.bufs.push(createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos)); + encoder.cbuf = new Uint8Array(max(bufferLen, len) * 2); + encoder.cpos = 0; + } + }; + + /** + * Write one byte to the encoder. + * + * @function + * @param {Encoder} encoder + * @param {number} num The byte that is to be encoded. + */ + const write = (encoder, num) => { + const bufferLen = encoder.cbuf.length; + if (encoder.cpos === bufferLen) { + encoder.bufs.push(encoder.cbuf); + encoder.cbuf = new Uint8Array(bufferLen * 2); + encoder.cpos = 0; + } + encoder.cbuf[encoder.cpos++] = num; + }; + + /** + * Write one byte as an unsigned integer. + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ + const writeUint8 = write; + + /** + * Write a variable length unsigned integer. + * + * Encodes integers in the range from [0, 4294967295] / [0, 0xffffffff]. (max 32 bit unsigned integer) + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ + const writeVarUint = (encoder, num) => { + while (num > BITS7) { + write(encoder, BIT8 | (BITS7 & num)); + num >>>= 7; + } + write(encoder, BITS7 & num); + }; + + /** + * Write a variable length integer. + * + * Encodes integers in the range from [-2147483648, -2147483647]. + * + * We don't use zig-zag encoding because we want to keep the option open + * to use the same function for BigInt and 53bit integers (doubles). + * + * We use the 7th bit instead for signaling that this is a negative number. + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ + const writeVarInt = (encoder, num) => { + const isNegative = isNegativeZero(num); + if (isNegative) { + num = -num; + } + // |- whether to continue reading |- whether is negative |- number + write(encoder, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | (BITS6 & num)); + num >>>= 6; + // We don't need to consider the case of num === 0 so we can use a different + // pattern here than above. + while (num > 0) { + write(encoder, (num > BITS7 ? BIT8 : 0) | (BITS7 & num)); + num >>>= 7; + } + }; + + /** + * Write a variable length string. + * + * @function + * @param {Encoder} encoder + * @param {String} str The string that is to be encoded. + */ + const writeVarString = (encoder, str) => { + const encodedString = unescape(encodeURIComponent(str)); + const len = encodedString.length; + writeVarUint(encoder, len); + for (let i = 0; i < len; i++) { + write(encoder, /** @type {number} */ (encodedString.codePointAt(i))); + } + }; + + /** + * Append fixed-length Uint8Array to the encoder. + * + * @function + * @param {Encoder} encoder + * @param {Uint8Array} uint8Array + */ + const writeUint8Array = (encoder, uint8Array) => { + const bufferLen = encoder.cbuf.length; + const cpos = encoder.cpos; + const leftCopyLen = min(bufferLen - cpos, uint8Array.length); + const rightCopyLen = uint8Array.length - leftCopyLen; + encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos); + encoder.cpos += leftCopyLen; + if (rightCopyLen > 0) { + // Still something to write, write right half.. + // Append new buffer + encoder.bufs.push(encoder.cbuf); + // must have at least size of remaining buffer + encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen)); + // copy array + encoder.cbuf.set(uint8Array.subarray(leftCopyLen)); + encoder.cpos = rightCopyLen; + } + }; + + /** + * Append an Uint8Array to Encoder. + * + * @function + * @param {Encoder} encoder + * @param {Uint8Array} uint8Array + */ + const writeVarUint8Array = (encoder, uint8Array) => { + writeVarUint(encoder, uint8Array.byteLength); + writeUint8Array(encoder, uint8Array); + }; + + /** + * Create an DataView of the next `len` bytes. Use it to write data after + * calling this function. + * + * ```js + * // write float32 using DataView + * const dv = writeOnDataView(encoder, 4) + * dv.setFloat32(0, 1.1) + * // read float32 using DataView + * const dv = readFromDataView(encoder, 4) + * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result) + * ``` + * + * @param {Encoder} encoder + * @param {number} len + * @return {DataView} + */ + const writeOnDataView = (encoder, len) => { + verifyLen(encoder, len); + const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len); + encoder.cpos += len; + return dview + }; + + /** + * @param {Encoder} encoder + * @param {number} num + */ + const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num); + + /** + * @param {Encoder} encoder + * @param {number} num + */ + const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num); + + /** + * @param {Encoder} encoder + * @param {bigint} num + */ + const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num); + + const floatTestBed = new DataView(new ArrayBuffer(4)); + /** + * Check if a number can be encoded as a 32 bit float. + * + * @param {number} num + * @return {boolean} + */ + const isFloat32 = num => { + floatTestBed.setFloat32(0, num); + return floatTestBed.getFloat32(0) === num + }; + + /** + * Encode data with efficient binary format. + * + * Differences to JSON: + * • Transforms data to a binary format (not to a string) + * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON) + * • Numbers are efficiently encoded either as a variable length integer, as a + * 32 bit float, as a 64 bit float, or as a 64 bit bigint. + * + * Encoding table: + * + * | Data Type | Prefix | Encoding Method | Comment | + * | ------------------- | -------- | ------------------ | ------- | + * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined | + * | null | 126 | | | + * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers | + * | float32 | 124 | writeFloat32 | | + * | float64 | 123 | writeFloat64 | | + * | bigint | 122 | writeBigInt64 | | + * | boolean (false) | 121 | | True and false are different data types so we save the following byte | + * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false | + * | string | 119 | writeVarString | | + * | object | 118 | custom | Writes {length} then {length} key-value pairs | + * | array | 117 | custom | Writes {length} then {length} json values | + * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data | + * + * Reasons for the decreasing prefix: + * We need the first bit for extendability (later we may want to encode the + * prefix with writeVarUint). The remaining 7 bits are divided as follows: + * [0-30] the beginning of the data range is used for custom purposes + * (defined by the function that uses this library) + * [31-127] the end of the data range is used for data encoding by + * lib0/encoding.js + * + * @param {Encoder} encoder + * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data + */ + const writeAny = (encoder, data) => { + switch (typeof data) { + case 'string': + // TYPE 119: STRING + write(encoder, 119); + writeVarString(encoder, data); + break + case 'number': + if (isInteger(data) && data <= BITS31) { + // TYPE 125: INTEGER + write(encoder, 125); + writeVarInt(encoder, data); + } else if (isFloat32(data)) { + // TYPE 124: FLOAT32 + write(encoder, 124); + writeFloat32(encoder, data); + } else { + // TYPE 123: FLOAT64 + write(encoder, 123); + writeFloat64(encoder, data); + } + break + case 'bigint': + // TYPE 122: BigInt + write(encoder, 122); + writeBigInt64(encoder, data); + break + case 'object': + if (data === null) { + // TYPE 126: null + write(encoder, 126); + } else if (data instanceof Array) { + // TYPE 117: Array + write(encoder, 117); + writeVarUint(encoder, data.length); + for (let i = 0; i < data.length; i++) { + writeAny(encoder, data[i]); + } + } else if (data instanceof Uint8Array) { + // TYPE 116: ArrayBuffer + write(encoder, 116); + writeVarUint8Array(encoder, data); + } else { + // TYPE 118: Object + write(encoder, 118); + const keys = Object.keys(data); + writeVarUint(encoder, keys.length); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + writeVarString(encoder, key); + writeAny(encoder, data[key]); + } + } + break + case 'boolean': + // TYPE 120/121: boolean (true/false) + write(encoder, data ? 120 : 121); + break + default: + // TYPE 127: undefined + write(encoder, 127); + } + }; + + /** + * Now come a few stateful encoder that have their own classes. + */ + + /** + * Basic Run Length Encoder - a basic compression implementation. + * + * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated. + * + * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf + * + * @note T must not be null! + * + * @template T + */ + class RleEncoder extends Encoder { + /** + * @param {function(Encoder, T):void} writer + */ + constructor (writer) { + super(); + /** + * The writer + */ + this.w = writer; + /** + * Current state + * @type {T|null} + */ + this.s = null; + this.count = 0; + } + + /** + * @param {T} v + */ + write (v) { + if (this.s === v) { + this.count++; + } else { + if (this.count > 0) { + // flush counter, unless this is the first value (count = 0) + writeVarUint(this, this.count - 1); // since count is always > 0, we can decrement by one. non-standard encoding ftw + } + this.count = 1; + // write first value + this.w(this, v); + this.s = v; + } + } + } + + /** + * @param {UintOptRleEncoder} encoder + */ + const flushUintOptRleEncoder = encoder => { + if (encoder.count > 0) { + // flush counter, unless this is the first value (count = 0) + // case 1: just a single value. set sign to positive + // case 2: write several values. set sign to negative to indicate that there is a length coming + writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s); + if (encoder.count > 1) { + writeVarUint(encoder.encoder, encoder.count - 2); // since count is always > 1, we can decrement by one. non-standard encoding ftw + } + } + }; + + /** + * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder. + * + * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write + * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count. + * + * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3) + */ + class UintOptRleEncoder { + constructor () { + this.encoder = new Encoder(); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + } + + /** + * @param {number} v + */ + write (v) { + if (this.s === v) { + this.count++; + } else { + flushUintOptRleEncoder(this); + this.count = 1; + this.s = v; + } + } + + toUint8Array () { + flushUintOptRleEncoder(this); + return toUint8Array(this.encoder) + } + } + + /** + * @param {IntDiffOptRleEncoder} encoder + */ + const flushIntDiffOptRleEncoder = encoder => { + if (encoder.count > 0) { + // 31 bit making up the diff | wether to write the counter + const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1); + // flush counter, unless this is the first value (count = 0) + // case 1: just a single value. set first bit to positive + // case 2: write several values. set first bit to negative to indicate that there is a length coming + writeVarInt(encoder.encoder, encodedDiff); + if (encoder.count > 1) { + writeVarUint(encoder.encoder, encoder.count - 2); // since count is always > 1, we can decrement by one. non-standard encoding ftw + } + } + }; + + /** + * A combination of the IntDiffEncoder and the UintOptRleEncoder. + * + * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes + * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers! + * + * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1]) + * + * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains: + * * 1 bit that denotes whether the next value is a count (LSB) + * * 1 bit that denotes whether this value is negative (MSB - 1) + * * 1 bit that denotes whether to continue reading the variable length integer (MSB) + * + * Therefore, only five bits remain to encode diff ranges. + * + * Use this Encoder only when appropriate. In most cases, this is probably a bad idea. + */ + class IntDiffOptRleEncoder { + constructor () { + this.encoder = new Encoder(); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + this.diff = 0; + } + + /** + * @param {number} v + */ + write (v) { + if (this.diff === v - this.s) { + this.s = v; + this.count++; + } else { + flushIntDiffOptRleEncoder(this); + this.count = 1; + this.diff = v - this.s; + this.s = v; + } + } + + toUint8Array () { + flushIntDiffOptRleEncoder(this); + return toUint8Array(this.encoder) + } + } + + /** + * Optimized String Encoder. + * + * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted. + * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?). + * + * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call. + * + * The lengths are encoded using a UintOptRleEncoder. + */ + class StringEncoder { + constructor () { + /** + * @type {Array} + */ + this.sarr = []; + this.s = ''; + this.lensE = new UintOptRleEncoder(); + } + + /** + * @param {string} string + */ + write (string) { + this.s += string; + if (this.s.length > 19) { + this.sarr.push(this.s); + this.s = ''; + } + this.lensE.write(string.length); + } + + toUint8Array () { + const encoder = new Encoder(); + this.sarr.push(this.s); + this.s = ''; + writeVarString(encoder, this.sarr.join('')); + writeUint8Array(encoder, this.lensE.toUint8Array()); + return toUint8Array(encoder) + } + } + + /* eslint-env browser */ + const perf = typeof performance === 'undefined' ? null : performance; + + const isoCrypto = typeof crypto === 'undefined' ? null : crypto; + + /** + * @type {function(number):ArrayBuffer} + */ + const cryptoRandomBuffer = isoCrypto !== null + ? len => { + // browser + const buf = new ArrayBuffer(len); + const arr = new Uint8Array(buf); + isoCrypto.getRandomValues(arr); + return buf + } + : len => { + // polyfill + const buf = new ArrayBuffer(len); + const arr = new Uint8Array(buf); + for (let i = 0; i < len; i++) { + arr[i] = Math.ceil((Math.random() * 0xFFFFFFFF) >>> 0); + } + return buf + }; + + var performance_1 = perf; + var cryptoRandomBuffer_1 = cryptoRandomBuffer; + + var isoBrowser = { + performance: performance_1, + cryptoRandomBuffer: cryptoRandomBuffer_1 + }; + + /** + * Isomorphic library exports from isomorphic.js. + * + * @module isomorphic + */ + const cryptoRandomBuffer$1 = /** @type {any} */ (isoBrowser.cryptoRandomBuffer); + + const rand = Math.random; + + /* istanbul ignore next */ + const uint32 = () => new Uint32Array(cryptoRandomBuffer$1(4))[0]; + + // @ts-ignore + const uuidv4Template = [1e7] + -1e3 + -4e3 + -8e3 + -1e11; + const uuidv4 = () => uuidv4Template.replace(/[018]/g, /** @param {number} c */ c => + (c ^ uint32() & 15 >> c / 4).toString(16) + ); + + /** + * Error helpers. + * + * @module error + */ + + /** + * @param {string} s + * @return {Error} + */ + /* istanbul ignore next */ + const create$2 = s => new Error(s); + + /** + * @throws {Error} + * @return {never} + */ + /* istanbul ignore next */ + const methodUnimplemented = () => { + throw create$2('Method unimplemented') + }; + + /** + * @throws {Error} + * @return {never} + */ + /* istanbul ignore next */ + const unexpectedCase = () => { + throw create$2('Unexpected case') + }; + + /** + * Utility functions for working with EcmaScript objects. + * + * @module object + */ + + /** + * @param {Object} obj + */ + const keys = Object.keys; + + /** + * @param {Object} obj + * @return {number} + */ + const length$1 = obj => keys(obj).length; + + /** + * @param {Object} obj + * @param {function(any,string):boolean} f + * @return {boolean} + */ + const every = (obj, f) => { + for (const key in obj) { + if (!f(obj[key], key)) { + return false + } + } + return true + }; + + /** + * Calls `Object.prototype.hasOwnProperty`. + * + * @param {any} obj + * @param {string|symbol} key + * @return {boolean} + */ + const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key); + + /** + * @param {Object} a + * @param {Object} b + * @return {boolean} + */ + const equalFlat = (a, b) => a === b || (length$1(a) === length$1(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val)); + + /** + * Common functions and function call helpers. + * + * @module function + */ + + /** + * Calls all functions in `fs` with args. Only throws after all functions were called. + * + * @param {Array} fs + * @param {Array} args + */ + const callAll = (fs, args, i = 0) => { + try { + for (; i < fs.length; i++) { + fs[i](...args); + } + } finally { + if (i < fs.length) { + callAll(fs, args, i + 1); + } + } + }; + + const nop = () => {}; + + /** + * @template T + * + * @param {T} a + * @param {T} b + * @return {boolean} + */ + const equalityStrict = (a, b) => a === b; + + /** + * @param {any} a + * @param {any} b + * @return {boolean} + */ + const equalityDeep = (a, b) => { + if (a == null || b == null) { + return equalityStrict(a, b) + } + if (a.constructor !== b.constructor) { + return false + } + if (a === b) { + return true + } + switch (a.constructor) { + case ArrayBuffer: + a = new Uint8Array(a); + b = new Uint8Array(b); + // eslint-disable-next-line no-fallthrough + case Uint8Array: { + if (a.byteLength !== b.byteLength) { + return false + } + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { + return false + } + } + break + } + case Set: { + if (a.size !== b.size) { + return false + } + for (const value of a) { + if (!b.has(value)) { + return false + } + } + break + } + case Map: { + if (a.size !== b.size) { + return false + } + for (const key of a.keys()) { + if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) { + return false + } + } + break + } + case Object: + if (length$1(a) !== length$1(b)) { + return false + } + for (const key in a) { + if (!hasProperty(a, key) || !equalityDeep(a[key], b[key])) { + return false + } + } + break + case Array: + if (a.length !== b.length) { + return false + } + for (let i = 0; i < a.length; i++) { + if (!equalityDeep(a[i], b[i])) { + return false + } + } + break + default: + return false + } + return true + }; + + /** + * Utility module to work with EcmaScript Symbols. + * + * @module symbol + */ + + /** + * Return fresh symbol. + * + * @return {Symbol} + */ + const create$3 = Symbol; + + /** + * Working with value pairs. + * + * @module pair + */ + + /** + * @template L,R + */ + class Pair { + /** + * @param {L} left + * @param {R} right + */ + constructor (left, right) { + this.left = left; + this.right = right; + } + } + + /** + * @template L,R + * @param {L} left + * @param {R} right + * @return {Pair} + */ + const create$4 = (left, right) => new Pair(left, right); + + /* eslint-env browser */ + + /* istanbul ignore next */ + /** + * @type {Document} + */ + const doc = /** @type {Document} */ (typeof document !== 'undefined' ? document : {}); + + /* istanbul ignore next */ + const domParser = /** @type {DOMParser} */ (typeof DOMParser !== 'undefined' ? new DOMParser() : null); + + /** + * @param {Map} m + * @return {string} + */ + /* istanbul ignore next */ + const mapToStyleString = m => map(m, (value, key) => `${key}:${value};`).join(''); + + /* global requestIdleCallback, requestAnimationFrame, cancelIdleCallback, cancelAnimationFrame */ + + /** + * @typedef {Object} TimeoutObject + * @property {function} TimeoutObject.destroy + */ + + /** + * @param {function(number):void} clearFunction + */ + const createTimeoutClass = clearFunction => class TT { + /** + * @param {number} timeoutId + */ + constructor (timeoutId) { + this._ = timeoutId; + } + + destroy () { + clearFunction(this._); + } + }; + + const Timeout = createTimeoutClass(clearTimeout); + + /** + * @param {number} timeout + * @param {function} callback + * @return {TimeoutObject} + */ + const timeout = (timeout, callback) => new Timeout(setTimeout(callback, timeout)); + + /** + * Utility module to work with time. + * + * @module time + */ + + /** + * Return current unix time. + * + * @return {number} + */ + const getUnixTime = Date.now; + + /** + * Isomorphic logging module with support for colors! + * + * @module logging + */ + + const BOLD = create$3(); + const UNBOLD = create$3(); + const BLUE = create$3(); + const GREY = create$3(); + const GREEN = create$3(); + const RED = create$3(); + const PURPLE = create$3(); + const ORANGE = create$3(); + const UNCOLOR = create$3(); + + /** + * @type {Object>} + */ + const _browserStyleMap = { + [BOLD]: create$4('font-weight', 'bold'), + [UNBOLD]: create$4('font-weight', 'normal'), + [BLUE]: create$4('color', 'blue'), + [GREEN]: create$4('color', 'green'), + [GREY]: create$4('color', 'grey'), + [RED]: create$4('color', 'red'), + [PURPLE]: create$4('color', 'purple'), + [ORANGE]: create$4('color', 'orange'), // not well supported in chrome when debugging node with inspector - TODO: deprecate + [UNCOLOR]: create$4('color', 'black') + }; + + const _nodeStyleMap = { + [BOLD]: '\u001b[1m', + [UNBOLD]: '\u001b[2m', + [BLUE]: '\x1b[34m', + [GREEN]: '\x1b[32m', + [GREY]: '\u001b[37m', + [RED]: '\x1b[31m', + [PURPLE]: '\x1b[35m', + [ORANGE]: '\x1b[38;5;208m', + [UNCOLOR]: '\x1b[0m' + }; + + /* istanbul ignore next */ + /** + * @param {Array} args + * @return {Array} + */ + const computeBrowserLoggingArgs = args => { + const strBuilder = []; + const styles = []; + const currentStyle = create(); + /** + * @type {Array} + */ + let logArgs = []; + // try with formatting until we find something unsupported + let i = 0; + + for (; i < args.length; i++) { + const arg = args[i]; + // @ts-ignore + const style = _browserStyleMap[arg]; + if (style !== undefined) { + currentStyle.set(style.left, style.right); + } else { + if (arg.constructor === String || arg.constructor === Number) { + const style = mapToStyleString(currentStyle); + if (i > 0 || style.length > 0) { + strBuilder.push('%c' + arg); + styles.push(style); + } else { + strBuilder.push(arg); + } + } else { + break + } + } + } + + if (i > 0) { + // create logArgs with what we have so far + logArgs = styles; + logArgs.unshift(strBuilder.join('')); + } + // append the rest + for (; i < args.length; i++) { + const arg = args[i]; + if (!(arg instanceof Symbol)) { + logArgs.push(arg); + } + } + return logArgs + }; + + /** + * @param {Array} args + * @return {Array} + */ + const computeNodeLoggingArgs = args => { + const strBuilder = []; + const logArgs = []; + + // try with formatting until we find something unsupported + let i = 0; + + for (; i < args.length; i++) { + const arg = args[i]; + // @ts-ignore + const style = _nodeStyleMap[arg]; + if (style !== undefined) { + strBuilder.push(style); + } else { + if (arg.constructor === String || arg.constructor === Number) { + strBuilder.push(arg); + } else { + break + } + } + } + if (i > 0) { + // create logArgs with what we have so far + strBuilder.push('\x1b[0m'); + logArgs.push(strBuilder.join('')); + } + // append the rest + for (; i < args.length; i++) { + const arg = args[i]; + /* istanbul ignore else */ + if (!(arg instanceof Symbol)) { + logArgs.push(arg); + } + } + return logArgs + }; + + /* istanbul ignore next */ + const computeLoggingArgs = isNode ? computeNodeLoggingArgs : computeBrowserLoggingArgs; + + /** + * @param {Array} args + */ + const print = (...args) => { + console.log(...computeLoggingArgs(args)); + /* istanbul ignore next */ + vconsoles.forEach(vc => vc.print(args)); + }; + + const vconsoles = new Set(); + + const loggingColors = [GREEN, PURPLE, ORANGE, BLUE]; + let nextColor = 0; + let lastLoggingTime = getUnixTime(); + + /** + * @param {string} moduleName + * @return {function(...any)} + */ + const createModuleLogger = moduleName => { + const color = loggingColors[nextColor]; + const debugRegexVar = getVariable('log'); + const doLogging = debugRegexVar !== null && (debugRegexVar === '*' || debugRegexVar === 'true' || new RegExp(debugRegexVar, 'gi').test(moduleName)); + nextColor = (nextColor + 1) % loggingColors.length; + moduleName += ': '; + + return !doLogging ? nop : (...args) => { + const timeNow = getUnixTime(); + const timeDiff = timeNow - lastLoggingTime; + lastLoggingTime = timeNow; + print(color, moduleName, UNCOLOR, ...args.map(arg => (typeof arg === 'string' || typeof arg === 'symbol') ? arg : JSON.stringify(arg)), color, ' +' + timeDiff + 'ms'); + } + }; + + /** + * Utility module to create and manipulate Iterators. + * + * @module iterator + */ + + /** + * @template T + * @param {function():IteratorResult} next + * @return {IterableIterator} + */ + const createIterator = next => ({ + /** + * @return {IterableIterator} + */ + [Symbol.iterator] () { + return this + }, + // @ts-ignore + next + }); + + /** + * @template T + * @param {Iterator} iterator + * @param {function(T):boolean} filter + */ + const iteratorFilter = (iterator, filter) => createIterator(() => { + let res; + do { + res = iterator.next(); + } while (!res.done && !filter(res.value)) + return res + }); + + /** + * @template T,M + * @param {Iterator} iterator + * @param {function(T):M} fmap + */ + const iteratorMap = (iterator, fmap) => createIterator(() => { + const { done, value } = iterator.next(); + return { done, value: done ? undefined : fmap(value) } + }); + + class DeleteItem { + /** + * @param {number} clock + * @param {number} len + */ + constructor (clock, len) { + /** + * @type {number} + */ + this.clock = clock; + /** + * @type {number} + */ + this.len = len; + } + } + + /** + * We no longer maintain a DeleteStore. DeleteSet is a temporary object that is created when needed. + * - When created in a transaction, it must only be accessed after sorting, and merging + * - This DeleteSet is send to other clients + * - We do not create a DeleteSet when we send a sync message. The DeleteSet message is created directly from StructStore + * - We read a DeleteSet as part of a sync/update message. In this case the DeleteSet is already sorted and merged. + */ + class DeleteSet { + constructor () { + /** + * @type {Map>} + */ + this.clients = new Map(); + } + } + + /** + * Iterate over all structs that the DeleteSet gc's. + * + * @param {Transaction} transaction + * @param {DeleteSet} ds + * @param {function(GC|Item):void} f + * + * @function + */ + const iterateDeletedStructs = (transaction, ds, f) => + ds.clients.forEach((deletes, clientid) => { + const structs = /** @type {Array} */ (transaction.doc.store.clients.get(clientid)); + for (let i = 0; i < deletes.length; i++) { + const del = deletes[i]; + iterateStructs(transaction, structs, del.clock, del.len, f); + } + }); + + /** + * @param {Array} dis + * @param {number} clock + * @return {number|null} + * + * @private + * @function + */ + const findIndexDS = (dis, clock) => { + let left = 0; + let right = dis.length - 1; + while (left <= right) { + const midindex = floor((left + right) / 2); + const mid = dis[midindex]; + const midclock = mid.clock; + if (midclock <= clock) { + if (clock < midclock + mid.len) { + return midindex + } + left = midindex + 1; + } else { + right = midindex - 1; + } + } + return null + }; + + /** + * @param {DeleteSet} ds + * @param {ID} id + * @return {boolean} + * + * @private + * @function + */ + const isDeleted = (ds, id) => { + const dis = ds.clients.get(id.client); + return dis !== undefined && findIndexDS(dis, id.clock) !== null + }; + + /** + * @param {DeleteSet} ds + * + * @private + * @function + */ + const sortAndMergeDeleteSet = ds => { + ds.clients.forEach(dels => { + dels.sort((a, b) => a.clock - b.clock); + // merge items without filtering or splicing the array + // i is the current pointer + // j refers to the current insert position for the pointed item + // try to merge dels[i] into dels[j-1] or set dels[j]=dels[i] + let i, j; + for (i = 1, j = 1; i < dels.length; i++) { + const left = dels[j - 1]; + const right = dels[i]; + if (left.clock + left.len === right.clock) { + left.len += right.len; + } else { + if (j < i) { + dels[j] = right; + } + j++; + } + } + dels.length = j; + }); + }; + + /** + * @param {Array} dss + * @return {DeleteSet} A fresh DeleteSet + */ + const mergeDeleteSets = dss => { + const merged = new DeleteSet(); + for (let dssI = 0; dssI < dss.length; dssI++) { + dss[dssI].clients.forEach((delsLeft, client) => { + if (!merged.clients.has(client)) { + // Write all missing keys from current ds and all following. + // If merged already contains `client` current ds has already been added. + /** + * @type {Array} + */ + const dels = delsLeft.slice(); + for (let i = dssI + 1; i < dss.length; i++) { + appendTo(dels, dss[i].clients.get(client) || []); + } + merged.clients.set(client, dels); + } + }); + } + sortAndMergeDeleteSet(merged); + return merged + }; + + /** + * @param {DeleteSet} ds + * @param {number} client + * @param {number} clock + * @param {number} length + * + * @private + * @function + */ + const addToDeleteSet = (ds, client, clock, length) => { + setIfUndefined(ds.clients, client, () => []).push(new DeleteItem(clock, length)); + }; + + const createDeleteSet = () => new DeleteSet(); + + /** + * @param {StructStore} ss + * @return {DeleteSet} Merged and sorted DeleteSet + * + * @private + * @function + */ + const createDeleteSetFromStructStore = ss => { + const ds = createDeleteSet(); + ss.clients.forEach((structs, client) => { + /** + * @type {Array} + */ + const dsitems = []; + for (let i = 0; i < structs.length; i++) { + const struct = structs[i]; + if (struct.deleted) { + const clock = struct.id.clock; + let len = struct.length; + if (i + 1 < structs.length) { + for (let next = structs[i + 1]; i + 1 < structs.length && next.id.clock === clock + len && next.deleted; next = structs[++i + 1]) { + len += next.length; + } + } + dsitems.push(new DeleteItem(clock, len)); + } + } + if (dsitems.length > 0) { + ds.clients.set(client, dsitems); + } + }); + return ds + }; + + /** + * @param {AbstractDSEncoder} encoder + * @param {DeleteSet} ds + * + * @private + * @function + */ + const writeDeleteSet = (encoder, ds) => { + writeVarUint(encoder.restEncoder, ds.clients.size); + ds.clients.forEach((dsitems, client) => { + encoder.resetDsCurVal(); + writeVarUint(encoder.restEncoder, client); + const len = dsitems.length; + writeVarUint(encoder.restEncoder, len); + for (let i = 0; i < len; i++) { + const item = dsitems[i]; + encoder.writeDsClock(item.clock); + encoder.writeDsLen(item.len); + } + }); + }; + + /** + * @todo YDecoder also contains references to String and other Decoders. Would make sense to exchange YDecoder.toUint8Array for YDecoder.DsToUint8Array().. + */ + + /** + * @param {AbstractDSDecoder} decoder + * @param {Transaction} transaction + * @param {StructStore} store + * + * @private + * @function + */ + const readAndApplyDeleteSet = (decoder, transaction, store) => { + const unappliedDS = new DeleteSet(); + const numClients = readVarUint(decoder.restDecoder); + for (let i = 0; i < numClients; i++) { + decoder.resetDsCurVal(); + const client = readVarUint(decoder.restDecoder); + const numberOfDeletes = readVarUint(decoder.restDecoder); + const structs = store.clients.get(client) || []; + const state = getState(store, client); + for (let i = 0; i < numberOfDeletes; i++) { + const clock = decoder.readDsClock(); + const clockEnd = clock + decoder.readDsLen(); + if (clock < state) { + if (state < clockEnd) { + addToDeleteSet(unappliedDS, client, state, clockEnd - state); + } + let index = findIndexSS(structs, clock); + /** + * We can ignore the case of GC and Delete structs, because we are going to skip them + * @type {Item} + */ + // @ts-ignore + let struct = structs[index]; + // split the first item if necessary + if (!struct.deleted && struct.id.clock < clock) { + structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); + index++; // increase we now want to use the next struct + } + while (index < structs.length) { + // @ts-ignore + struct = structs[index++]; + if (struct.id.clock < clockEnd) { + if (!struct.deleted) { + if (clockEnd < struct.id.clock + struct.length) { + structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock)); + } + struct.delete(transaction); + } + } else { + break + } + } + } else { + addToDeleteSet(unappliedDS, client, clock, clockEnd - clock); + } + } + } + if (unappliedDS.clients.size > 0) { + // TODO: no need for encoding+decoding ds anymore + const unappliedDSEncoder = new DSEncoderV2(); + writeDeleteSet(unappliedDSEncoder, unappliedDS); + store.pendingDeleteReaders.push(new DSDecoderV2(createDecoder((unappliedDSEncoder.toUint8Array())))); + } + }; + + /** + * @module Y + */ + + const generateNewClientId = uint32; + + /** + * @typedef {Object} DocOpts + * @property {boolean} [DocOpts.gc=true] Disable garbage collection (default: gc=true) + * @property {function(Item):boolean} [DocOpts.gcFilter] Will be called before an Item is garbage collected. Return false to keep the Item. + * @property {string} [DocOpts.guid] Define a globally unique identifier for this document + * @property {any} [DocOpts.meta] Any kind of meta information you want to associate with this document. If this is a subdocument, remote peers will store the meta information as well. + * @property {boolean} [DocOpts.autoLoad] If a subdocument, automatically load document. If this is a subdocument, remote peers will load the document as well automatically. + */ + + /** + * A Yjs instance handles the state of shared data. + * @extends Observable + */ + class Doc extends Observable { + /** + * @param {DocOpts} [opts] configuration + */ + constructor ({ guid = uuidv4(), gc = true, gcFilter = () => true, meta = null, autoLoad = false } = {}) { + super(); + this.gc = gc; + this.gcFilter = gcFilter; + this.clientID = generateNewClientId(); + this.guid = guid; + /** + * @type {Map>} + */ + this.share = new Map(); + this.store = new StructStore(); + /** + * @type {Transaction | null} + */ + this._transaction = null; + /** + * @type {Array} + */ + this._transactionCleanups = []; + /** + * @type {Set} + */ + this.subdocs = new Set(); + /** + * If this document is a subdocument - a document integrated into another document - then _item is defined. + * @type {Item?} + */ + this._item = null; + this.shouldLoad = autoLoad; + this.autoLoad = autoLoad; + this.meta = meta; + } + + /** + * Notify the parent document that you request to load data into this subdocument (if it is a subdocument). + * + * `load()` might be used in the future to request any provider to load the most current data. + * + * It is safe to call `load()` multiple times. + */ + load () { + const item = this._item; + if (item !== null && !this.shouldLoad) { + transact(/** @type {any} */ (item.parent).doc, transaction => { + transaction.subdocsLoaded.add(this); + }, null, true); + } + this.shouldLoad = true; + } + + getSubdocs () { + return this.subdocs + } + + getSubdocGuids () { + return new Set(Array.from(this.subdocs).map(doc => doc.guid)) + } + + /** + * Changes that happen inside of a transaction are bundled. This means that + * the observer fires _after_ the transaction is finished and that all changes + * that happened inside of the transaction are sent as one message to the + * other peers. + * + * @param {function(Transaction):void} f The function that should be executed as a transaction + * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin + * + * @public + */ + transact (f, origin = null) { + transact(this, f, origin); + } + + /** + * Define a shared data type. + * + * Multiple calls of `y.get(name, TypeConstructor)` yield the same result + * and do not overwrite each other. I.e. + * `y.define(name, Y.Array) === y.define(name, Y.Array)` + * + * After this method is called, the type is also available on `y.share.get(name)`. + * + * *Best Practices:* + * Define all types right after the Yjs instance is created and store them in a separate object. + * Also use the typed methods `getText(name)`, `getArray(name)`, .. + * + * @example + * const y = new Y(..) + * const appState = { + * document: y.getText('document') + * comments: y.getArray('comments') + * } + * + * @param {string} name + * @param {Function} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ... + * @return {AbstractType} The created type. Constructed with TypeConstructor + * + * @public + */ + get (name, TypeConstructor = AbstractType) { + const type = setIfUndefined(this.share, name, () => { + // @ts-ignore + const t = new TypeConstructor(); + t._integrate(this, null); + return t + }); + const Constr = type.constructor; + if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) { + if (Constr === AbstractType) { + // @ts-ignore + const t = new TypeConstructor(); + t._map = type._map; + type._map.forEach(/** @param {Item?} n */ n => { + for (; n !== null; n = n.left) { + // @ts-ignore + n.parent = t; + } + }); + t._start = type._start; + for (let n = t._start; n !== null; n = n.right) { + n.parent = t; + } + t._length = type._length; + this.share.set(name, t); + t._integrate(this, null); + return t + } else { + throw new Error(`Type with the name ${name} has already been defined with a different constructor`) + } + } + return type + } + + /** + * @template T + * @param {string} [name] + * @return {YArray} + * + * @public + */ + getArray (name = '') { + // @ts-ignore + return this.get(name, YArray) + } + + /** + * @param {string} [name] + * @return {YText} + * + * @public + */ + getText (name = '') { + // @ts-ignore + return this.get(name, YText) + } + + /** + * @param {string} [name] + * @return {YMap} + * + * @public + */ + getMap (name = '') { + // @ts-ignore + return this.get(name, YMap) + } + + /** + * @param {string} [name] + * @return {YXmlFragment} + * + * @public + */ + getXmlFragment (name = '') { + // @ts-ignore + return this.get(name, YXmlFragment) + } + + /** + * Converts the entire document into a js object, recursively traversing each yjs type + * + * @return {Object} + */ + toJSON () { + /** + * @type {Object} + */ + const doc = {}; + + this.share.forEach((value, key) => { + doc[key] = value.toJSON(); + }); + + return doc + } + + /** + * Emit `destroy` event and unregister all event handlers. + */ + destroy () { + from(this.subdocs).forEach(subdoc => subdoc.destroy()); + const item = this._item; + if (item !== null) { + this._item = null; + const content = /** @type {ContentDoc} */ (item.content); + if (item.deleted) { + // @ts-ignore + content.doc = null; + } else { + content.doc = new Doc({ guid: this.guid, ...content.opts }); + content.doc._item = item; + } + transact(/** @type {any} */ (item).parent.doc, transaction => { + if (!item.deleted) { + transaction.subdocsAdded.add(content.doc); + } + transaction.subdocsRemoved.add(this); + }, null, true); + } + this.emit('destroyed', [true]); + super.destroy(); + } + + /** + * @param {string} eventName + * @param {function(...any):any} f + */ + on (eventName, f) { + super.on(eventName, f); + } + + /** + * @param {string} eventName + * @param {function} f + */ + off (eventName, f) { + super.off(eventName, f); + } + } + + class DSDecoderV1 { + /** + * @param {decoding.Decoder} decoder + */ + constructor (decoder) { + this.restDecoder = decoder; + } + + resetDsCurVal () { + // nop + } + + /** + * @return {number} + */ + readDsClock () { + return readVarUint(this.restDecoder) + } + + /** + * @return {number} + */ + readDsLen () { + return readVarUint(this.restDecoder) + } + } + + class UpdateDecoderV1 extends DSDecoderV1 { + /** + * @return {ID} + */ + readLeftID () { + return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)) + } + + /** + * @return {ID} + */ + readRightID () { + return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)) + } + + /** + * Read the next client id. + * Use this in favor of readID whenever possible to reduce the number of objects created. + */ + readClient () { + return readVarUint(this.restDecoder) + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readInfo () { + return readUint8(this.restDecoder) + } + + /** + * @return {string} + */ + readString () { + return readVarString(this.restDecoder) + } + + /** + * @return {boolean} isKey + */ + readParentInfo () { + return readVarUint(this.restDecoder) === 1 + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readTypeRef () { + return readVarUint(this.restDecoder) + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @return {number} len + */ + readLen () { + return readVarUint(this.restDecoder) + } + + /** + * @return {any} + */ + readAny () { + return readAny(this.restDecoder) + } + + /** + * @return {Uint8Array} + */ + readBuf () { + return copyUint8Array(readVarUint8Array(this.restDecoder)) + } + + /** + * Legacy implementation uses JSON parse. We use any-decoding in v2. + * + * @return {any} + */ + readJSON () { + return JSON.parse(readVarString(this.restDecoder)) + } + + /** + * @return {string} + */ + readKey () { + return readVarString(this.restDecoder) + } + } + + class DSDecoderV2 { + /** + * @param {decoding.Decoder} decoder + */ + constructor (decoder) { + this.dsCurrVal = 0; + this.restDecoder = decoder; + } + + resetDsCurVal () { + this.dsCurrVal = 0; + } + + readDsClock () { + this.dsCurrVal += readVarUint(this.restDecoder); + return this.dsCurrVal + } + + readDsLen () { + const diff = readVarUint(this.restDecoder) + 1; + this.dsCurrVal += diff; + return diff + } + } + + class UpdateDecoderV2 extends DSDecoderV2 { + /** + * @param {decoding.Decoder} decoder + */ + constructor (decoder) { + super(decoder); + /** + * List of cached keys. If the keys[id] does not exist, we read a new key + * from stringEncoder and push it to keys. + * + * @type {Array} + */ + this.keys = []; + readUint8(decoder); // read feature flag - currently unused + this.keyClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); + this.clientDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); + this.leftClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); + this.rightClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); + this.infoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); + this.stringDecoder = new StringDecoder(readVarUint8Array(decoder)); + this.parentInfoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); + this.typeRefDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); + this.lenDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); + } + + /** + * @return {ID} + */ + readLeftID () { + return new ID(this.clientDecoder.read(), this.leftClockDecoder.read()) + } + + /** + * @return {ID} + */ + readRightID () { + return new ID(this.clientDecoder.read(), this.rightClockDecoder.read()) + } + + /** + * Read the next client id. + * Use this in favor of readID whenever possible to reduce the number of objects created. + */ + readClient () { + return this.clientDecoder.read() + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readInfo () { + return /** @type {number} */ (this.infoDecoder.read()) + } + + /** + * @return {string} + */ + readString () { + return this.stringDecoder.read() + } + + /** + * @return {boolean} + */ + readParentInfo () { + return this.parentInfoDecoder.read() === 1 + } + + /** + * @return {number} An unsigned 8-bit integer + */ + readTypeRef () { + return this.typeRefDecoder.read() + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @return {number} + */ + readLen () { + return this.lenDecoder.read() + } + + /** + * @return {any} + */ + readAny () { + return readAny(this.restDecoder) + } + + /** + * @return {Uint8Array} + */ + readBuf () { + return readVarUint8Array(this.restDecoder) + } + + /** + * This is mainly here for legacy purposes. + * + * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder. + * + * @return {any} + */ + readJSON () { + return readAny(this.restDecoder) + } + + /** + * @return {string} + */ + readKey () { + const keyClock = this.keyClockDecoder.read(); + if (keyClock < this.keys.length) { + return this.keys[keyClock] + } else { + const key = this.stringDecoder.read(); + this.keys.push(key); + return key + } + } + } + + class DSEncoderV1 { + constructor () { + this.restEncoder = new Encoder(); + } + + toUint8Array () { + return toUint8Array(this.restEncoder) + } + + resetDsCurVal () { + // nop + } + + /** + * @param {number} clock + */ + writeDsClock (clock) { + writeVarUint(this.restEncoder, clock); + } + + /** + * @param {number} len + */ + writeDsLen (len) { + writeVarUint(this.restEncoder, len); + } + } + + class UpdateEncoderV1 extends DSEncoderV1 { + /** + * @param {ID} id + */ + writeLeftID (id) { + writeVarUint(this.restEncoder, id.client); + writeVarUint(this.restEncoder, id.clock); + } + + /** + * @param {ID} id + */ + writeRightID (id) { + writeVarUint(this.restEncoder, id.client); + writeVarUint(this.restEncoder, id.clock); + } + + /** + * Use writeClient and writeClock instead of writeID if possible. + * @param {number} client + */ + writeClient (client) { + writeVarUint(this.restEncoder, client); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeInfo (info) { + writeUint8(this.restEncoder, info); + } + + /** + * @param {string} s + */ + writeString (s) { + writeVarString(this.restEncoder, s); + } + + /** + * @param {boolean} isYKey + */ + writeParentInfo (isYKey) { + writeVarUint(this.restEncoder, isYKey ? 1 : 0); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeTypeRef (info) { + writeVarUint(this.restEncoder, info); + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @param {number} len + */ + writeLen (len) { + writeVarUint(this.restEncoder, len); + } + + /** + * @param {any} any + */ + writeAny (any) { + writeAny(this.restEncoder, any); + } + + /** + * @param {Uint8Array} buf + */ + writeBuf (buf) { + writeVarUint8Array(this.restEncoder, buf); + } + + /** + * @param {any} embed + */ + writeJSON (embed) { + writeVarString(this.restEncoder, JSON.stringify(embed)); + } + + /** + * @param {string} key + */ + writeKey (key) { + writeVarString(this.restEncoder, key); + } + } + + class DSEncoderV2 { + constructor () { + this.restEncoder = new Encoder(); // encodes all the rest / non-optimized + this.dsCurrVal = 0; + } + + toUint8Array () { + return toUint8Array(this.restEncoder) + } + + resetDsCurVal () { + this.dsCurrVal = 0; + } + + /** + * @param {number} clock + */ + writeDsClock (clock) { + const diff = clock - this.dsCurrVal; + this.dsCurrVal = clock; + writeVarUint(this.restEncoder, diff); + } + + /** + * @param {number} len + */ + writeDsLen (len) { + if (len === 0) { + unexpectedCase(); + } + writeVarUint(this.restEncoder, len - 1); + this.dsCurrVal += len; + } + } + + class UpdateEncoderV2 extends DSEncoderV2 { + constructor () { + super(); + /** + * @type {Map} + */ + this.keyMap = new Map(); + /** + * Refers to the next uniqe key-identifier to me used. + * See writeKey method for more information. + * + * @type {number} + */ + this.keyClock = 0; + this.keyClockEncoder = new IntDiffOptRleEncoder(); + this.clientEncoder = new UintOptRleEncoder(); + this.leftClockEncoder = new IntDiffOptRleEncoder(); + this.rightClockEncoder = new IntDiffOptRleEncoder(); + this.infoEncoder = new RleEncoder(writeUint8); + this.stringEncoder = new StringEncoder(); + this.parentInfoEncoder = new RleEncoder(writeUint8); + this.typeRefEncoder = new UintOptRleEncoder(); + this.lenEncoder = new UintOptRleEncoder(); + } + + toUint8Array () { + const encoder = createEncoder(); + writeUint8(encoder, 0); // this is a feature flag that we might use in the future + writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array()); + writeVarUint8Array(encoder, this.clientEncoder.toUint8Array()); + writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array()); + writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array()); + writeVarUint8Array(encoder, toUint8Array(this.infoEncoder)); + writeVarUint8Array(encoder, this.stringEncoder.toUint8Array()); + writeVarUint8Array(encoder, toUint8Array(this.parentInfoEncoder)); + writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array()); + writeVarUint8Array(encoder, this.lenEncoder.toUint8Array()); + // @note The rest encoder is appended! (note the missing var) + writeUint8Array(encoder, toUint8Array(this.restEncoder)); + return toUint8Array(encoder) + } + + /** + * @param {ID} id + */ + writeLeftID (id) { + this.clientEncoder.write(id.client); + this.leftClockEncoder.write(id.clock); + } + + /** + * @param {ID} id + */ + writeRightID (id) { + this.clientEncoder.write(id.client); + this.rightClockEncoder.write(id.clock); + } + + /** + * @param {number} client + */ + writeClient (client) { + this.clientEncoder.write(client); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeInfo (info) { + this.infoEncoder.write(info); + } + + /** + * @param {string} s + */ + writeString (s) { + this.stringEncoder.write(s); + } + + /** + * @param {boolean} isYKey + */ + writeParentInfo (isYKey) { + this.parentInfoEncoder.write(isYKey ? 1 : 0); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeTypeRef (info) { + this.typeRefEncoder.write(info); + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @param {number} len + */ + writeLen (len) { + this.lenEncoder.write(len); + } + + /** + * @param {any} any + */ + writeAny (any) { + writeAny(this.restEncoder, any); + } + + /** + * @param {Uint8Array} buf + */ + writeBuf (buf) { + writeVarUint8Array(this.restEncoder, buf); + } + + /** + * This is mainly here for legacy purposes. + * + * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder. + * + * @param {any} embed + */ + writeJSON (embed) { + writeAny(this.restEncoder, embed); + } + + /** + * Property keys are often reused. For example, in y-prosemirror the key `bold` might + * occur very often. For a 3d application, the key `position` might occur very often. + * + * We cache these keys in a Map and refer to them via a unique number. + * + * @param {string} key + */ + writeKey (key) { + const clock = this.keyMap.get(key); + if (clock === undefined) { + this.keyClockEncoder.write(this.keyClock++); + this.stringEncoder.write(key); + } else { + this.keyClockEncoder.write(this.keyClock++); + } + } + } + + let DefaultDSEncoder = DSEncoderV1; + let DefaultDSDecoder = DSDecoderV1; + let DefaultUpdateEncoder = UpdateEncoderV1; + let DefaultUpdateDecoder = UpdateDecoderV1; + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {Array} structs All structs by `client` + * @param {number} client + * @param {number} clock write structs starting with `ID(client,clock)` + * + * @function + */ + const writeStructs = (encoder, structs, client, clock) => { + // write first id + const startNewStructs = findIndexSS(structs, clock); + // write # encoded structs + writeVarUint(encoder.restEncoder, structs.length - startNewStructs); + encoder.writeClient(client); + writeVarUint(encoder.restEncoder, clock); + const firstStruct = structs[startNewStructs]; + // write first struct with an offset + firstStruct.write(encoder, clock - firstStruct.id.clock); + for (let i = startNewStructs + 1; i < structs.length; i++) { + structs[i].write(encoder, 0); + } + }; + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {StructStore} store + * @param {Map} _sm + * + * @private + * @function + */ + const writeClientsStructs = (encoder, store, _sm) => { + // we filter all valid _sm entries into sm + const sm = new Map(); + _sm.forEach((clock, client) => { + // only write if new structs are available + if (getState(store, client) > clock) { + sm.set(client, clock); + } + }); + getStateVector(store).forEach((clock, client) => { + if (!_sm.has(client)) { + sm.set(client, 0); + } + }); + // write # states that were updated + writeVarUint(encoder.restEncoder, sm.size); + // Write items with higher client ids first + // This heavily improves the conflict algorithm. + Array.from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => { + // @ts-ignore + writeStructs(encoder, store.clients.get(client), client, clock); + }); + }; + + /** + * @param {AbstractUpdateDecoder} decoder The decoder object to read data from. + * @param {Map>} clientRefs + * @param {Doc} doc + * @return {Map>} + * + * @private + * @function + */ + const readClientsStructRefs = (decoder, clientRefs, doc) => { + const numOfStateUpdates = readVarUint(decoder.restDecoder); + for (let i = 0; i < numOfStateUpdates; i++) { + const numberOfStructs = readVarUint(decoder.restDecoder); + /** + * @type {Array} + */ + const refs = new Array(numberOfStructs); + const client = decoder.readClient(); + let clock = readVarUint(decoder.restDecoder); + // const start = performance.now() + clientRefs.set(client, refs); + for (let i = 0; i < numberOfStructs; i++) { + const info = decoder.readInfo(); + if ((BITS5 & info) !== 0) { + /** + * The optimized implementation doesn't use any variables because inlining variables is faster. + * Below a non-optimized version is shown that implements the basic algorithm with + * a few comments + */ + const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0; + // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y` + // and we read the next string as parentYKey. + // It indicates how we store/retrieve parent from `y.share` + // @type {string|null} + const struct = new Item( + createID(client, clock), + null, // leftd + (info & BIT8) === BIT8 ? decoder.readLeftID() : null, // origin + null, // right + (info & BIT7) === BIT7 ? decoder.readRightID() : null, // right origin + cantCopyParentInfo ? (decoder.readParentInfo() ? doc.get(decoder.readString()) : decoder.readLeftID()) : null, // parent + cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null, // parentSub + readItemContent(decoder, info) // item content + ); + /* A non-optimized implementation of the above algorithm: + + // The item that was originally to the left of this item. + const origin = (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null + // The item that was originally to the right of this item. + const rightOrigin = (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null + const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0 + const hasParentYKey = cantCopyParentInfo ? decoder.readParentInfo() : false + // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y` + // and we read the next string as parentYKey. + // It indicates how we store/retrieve parent from `y.share` + // @type {string|null} + const parentYKey = cantCopyParentInfo && hasParentYKey ? decoder.readString() : null + + const struct = new Item( + createID(client, clock), + null, // leftd + origin, // origin + null, // right + rightOrigin, // right origin + cantCopyParentInfo && !hasParentYKey ? decoder.readLeftID() : (parentYKey !== null ? doc.get(parentYKey) : null), // parent + cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub + readItemContent(decoder, info) // item content + ) + */ + refs[i] = struct; + clock += struct.length; + } else { + const len = decoder.readLen(); + refs[i] = new GC(createID(client, clock), len); + clock += len; + } + } + // console.log('time to read: ', performance.now() - start) // @todo remove + } + return clientRefs + }; + + /** + * Resume computing structs generated by struct readers. + * + * While there is something to do, we integrate structs in this order + * 1. top element on stack, if stack is not empty + * 2. next element from current struct reader (if empty, use next struct reader) + * + * If struct causally depends on another struct (ref.missing), we put next reader of + * `ref.id.client` on top of stack. + * + * At some point we find a struct that has no causal dependencies, + * then we start emptying the stack. + * + * It is not possible to have circles: i.e. struct1 (from client1) depends on struct2 (from client2) + * depends on struct3 (from client1). Therefore the max stack size is eqaul to `structReaders.length`. + * + * This method is implemented in a way so that we can resume computation if this update + * causally depends on another update. + * + * @param {Transaction} transaction + * @param {StructStore} store + * + * @private + * @function + */ + const resumeStructIntegration = (transaction, store) => { + const stack = store.pendingStack; // @todo don't forget to append stackhead at the end + const clientsStructRefs = store.pendingClientsStructRefs; + // sort them so that we take the higher id first, in case of conflicts the lower id will probably not conflict with the id from the higher user. + const clientsStructRefsIds = Array.from(clientsStructRefs.keys()).sort((a, b) => a - b); + if (clientsStructRefsIds.length === 0) { + return + } + const getNextStructTarget = () => { + let nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1])); + while (nextStructsTarget.refs.length === nextStructsTarget.i) { + clientsStructRefsIds.pop(); + if (clientsStructRefsIds.length > 0) { + nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1])); + } else { + store.pendingClientsStructRefs.clear(); + return null + } + } + return nextStructsTarget + }; + let curStructsTarget = getNextStructTarget(); + if (curStructsTarget === null && stack.length === 0) { + return + } + /** + * @type {GC|Item} + */ + let stackHead = stack.length > 0 + ? /** @type {GC|Item} */ (stack.pop()) + : /** @type {any} */ (curStructsTarget).refs[/** @type {any} */ (curStructsTarget).i++]; + // caching the state because it is used very often + const state = new Map(); + // iterate over all struct readers until we are done + while (true) { + const localClock = setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client)); + const offset = stackHead.id.clock < localClock ? localClock - stackHead.id.clock : 0; + if (stackHead.id.clock + offset !== localClock) { + // A previous message from this client is missing + // check if there is a pending structRef with a smaller clock and switch them + /** + * @type {{ refs: Array, i: number }} + */ + const structRefs = clientsStructRefs.get(stackHead.id.client) || { refs: [], i: 0 }; + if (structRefs.refs.length !== structRefs.i) { + const r = structRefs.refs[structRefs.i]; + if (r.id.clock < stackHead.id.clock) { + // put ref with smaller clock on stack instead and continue + structRefs.refs[structRefs.i] = stackHead; + stackHead = r; + // sort the set because this approach might bring the list out of order + structRefs.refs = structRefs.refs.slice(structRefs.i).sort((r1, r2) => r1.id.clock - r2.id.clock); + structRefs.i = 0; + continue + } + } + // wait until missing struct is available + stack.push(stackHead); + return + } + const missing = stackHead.getMissing(transaction, store); + if (missing === null) { + if (offset === 0 || offset < stackHead.length) { + stackHead.integrate(transaction, offset); + state.set(stackHead.id.client, stackHead.id.clock + stackHead.length); + } + // iterate to next stackHead + if (stack.length > 0) { + stackHead = /** @type {GC|Item} */ (stack.pop()); + } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) { + stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++]); + } else { + curStructsTarget = getNextStructTarget(); + if (curStructsTarget === null) { + // we are done! + break + } else { + stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++]); + } + } + } else { + // get the struct reader that has the missing struct + /** + * @type {{ refs: Array, i: number }} + */ + const structRefs = clientsStructRefs.get(missing) || { refs: [], i: 0 }; + if (structRefs.refs.length === structRefs.i) { + // This update message causally depends on another update message. + stack.push(stackHead); + return + } + stack.push(stackHead); + stackHead = structRefs.refs[structRefs.i++]; + } + } + store.pendingClientsStructRefs.clear(); + }; + + /** + * @param {Transaction} transaction + * @param {StructStore} store + * + * @private + * @function + */ + const tryResumePendingDeleteReaders = (transaction, store) => { + const pendingReaders = store.pendingDeleteReaders; + store.pendingDeleteReaders = []; + for (let i = 0; i < pendingReaders.length; i++) { + readAndApplyDeleteSet(pendingReaders[i], transaction, store); + } + }; + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {Transaction} transaction + * + * @private + * @function + */ + const writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState); + + /** + * @param {StructStore} store + * @param {Map>} clientsStructsRefs + * + * @private + * @function + */ + const mergeReadStructsIntoPendingReads = (store, clientsStructsRefs) => { + const pendingClientsStructRefs = store.pendingClientsStructRefs; + clientsStructsRefs.forEach((structRefs, client) => { + const pendingStructRefs = pendingClientsStructRefs.get(client); + if (pendingStructRefs === undefined) { + pendingClientsStructRefs.set(client, { refs: structRefs, i: 0 }); + } else { + // merge into existing structRefs + const merged = pendingStructRefs.i > 0 ? pendingStructRefs.refs.slice(pendingStructRefs.i) : pendingStructRefs.refs; + for (let i = 0; i < structRefs.length; i++) { + merged.push(structRefs[i]); + } + pendingStructRefs.i = 0; + pendingStructRefs.refs = merged.sort((r1, r2) => r1.id.clock - r2.id.clock); + } + }); + }; + + /** + * @param {Map,i:number}>} pendingClientsStructRefs + */ + const cleanupPendingStructs = pendingClientsStructRefs => { + // cleanup pendingClientsStructs if not fully finished + pendingClientsStructRefs.forEach((refs, client) => { + if (refs.i === refs.refs.length) { + pendingClientsStructRefs.delete(client); + } else { + refs.refs.splice(0, refs.i); + refs.i = 0; + } + }); + }; + + /** + * Read the next Item in a Decoder and fill this Item with the read data. + * + * This is called when data is received from a remote peer. + * + * @param {AbstractUpdateDecoder} decoder The decoder object to read data from. + * @param {Transaction} transaction + * @param {StructStore} store + * + * @private + * @function + */ + const readStructs = (decoder, transaction, store) => { + const clientsStructRefs = new Map(); + // let start = performance.now() + readClientsStructRefs(decoder, clientsStructRefs, transaction.doc); + // console.log('time to read structs: ', performance.now() - start) // @todo remove + // start = performance.now() + mergeReadStructsIntoPendingReads(store, clientsStructRefs); + // console.log('time to merge: ', performance.now() - start) // @todo remove + // start = performance.now() + resumeStructIntegration(transaction, store); + // console.log('time to integrate: ', performance.now() - start) // @todo remove + // start = performance.now() + cleanupPendingStructs(store.pendingClientsStructRefs); + // console.log('time to cleanup: ', performance.now() - start) // @todo remove + // start = performance.now() + tryResumePendingDeleteReaders(transaction, store); + // console.log('time to resume delete readers: ', performance.now() - start) // @todo remove + // start = performance.now() + }; + + /** + * Read and apply a document update. + * + * This function has the same effect as `applyUpdate` but accepts an decoder. + * + * @param {decoding.Decoder} decoder + * @param {Doc} ydoc + * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))` + * @param {AbstractUpdateDecoder} [structDecoder] + * + * @function + */ + const readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) => + transact(ydoc, transaction => { + readStructs(structDecoder, transaction, ydoc.store); + readAndApplyDeleteSet(structDecoder, transaction, ydoc.store); + }, transactionOrigin, false); + + /** + * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`. + * + * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder. + * + * @param {Doc} ydoc + * @param {Uint8Array} update + * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))` + * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder] + * + * @function + */ + const applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => { + const decoder = createDecoder(update); + readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder)); + }; + + /** + * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`. + * + * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder. + * + * @param {Doc} ydoc + * @param {Uint8Array} update + * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))` + * + * @function + */ + const applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, DefaultUpdateDecoder); + + /** + * Write all the document as a single update message. If you specify the state of the remote client (`targetStateVector`) it will + * only write the operations that are missing. + * + * @param {AbstractUpdateEncoder} encoder + * @param {Doc} doc + * @param {Map} [targetStateVector] The state of the target that receives the update. Leave empty to write all known structs + * + * @function + */ + const writeStateAsUpdate = (encoder, doc, targetStateVector = new Map()) => { + writeClientsStructs(encoder, doc.store, targetStateVector); + writeDeleteSet(encoder, createDeleteSetFromStructStore(doc.store)); + }; + + /** + * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will + * only write the operations that are missing. + * + * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder + * + * @param {Doc} doc + * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs + * @param {AbstractUpdateEncoder} [encoder] + * @return {Uint8Array} + * + * @function + */ + const encodeStateAsUpdateV2 = (doc, encodedTargetStateVector, encoder = new UpdateEncoderV2()) => { + const targetStateVector = encodedTargetStateVector == null ? new Map() : decodeStateVector(encodedTargetStateVector); + writeStateAsUpdate(encoder, doc, targetStateVector); + return encoder.toUint8Array() + }; + + /** + * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will + * only write the operations that are missing. + * + * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder + * + * @param {Doc} doc + * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs + * @return {Uint8Array} + * + * @function + */ + const encodeStateAsUpdate = (doc, encodedTargetStateVector) => encodeStateAsUpdateV2(doc, encodedTargetStateVector, new DefaultUpdateEncoder()); + + /** + * Read state vector from Decoder and return as Map + * + * @param {AbstractDSDecoder} decoder + * @return {Map} Maps `client` to the number next expected `clock` from that client. + * + * @function + */ + const readStateVector = decoder => { + const ss = new Map(); + const ssLength = readVarUint(decoder.restDecoder); + for (let i = 0; i < ssLength; i++) { + const client = readVarUint(decoder.restDecoder); + const clock = readVarUint(decoder.restDecoder); + ss.set(client, clock); + } + return ss + }; + + /** + * Read decodedState and return State as Map. + * + * @param {Uint8Array} decodedState + * @return {Map} Maps `client` to the number next expected `clock` from that client. + * + * @function + */ + const decodeStateVector = decodedState => readStateVector(new DefaultDSDecoder(createDecoder(decodedState))); + + /** + * @param {AbstractDSEncoder} encoder + * @param {Map} sv + * @function + */ + const writeStateVector = (encoder, sv) => { + writeVarUint(encoder.restEncoder, sv.size); + sv.forEach((clock, client) => { + writeVarUint(encoder.restEncoder, client); // @todo use a special client decoder that is based on mapping + writeVarUint(encoder.restEncoder, clock); + }); + return encoder + }; + + /** + * @param {AbstractDSEncoder} encoder + * @param {Doc} doc + * + * @function + */ + const writeDocumentStateVector = (encoder, doc) => writeStateVector(encoder, getStateVector(doc.store)); + + /** + * Encode State as Uint8Array. + * + * @param {Doc} doc + * @param {AbstractDSEncoder} [encoder] + * @return {Uint8Array} + * + * @function + */ + const encodeStateVectorV2 = (doc, encoder = new DSEncoderV2()) => { + writeDocumentStateVector(encoder, doc); + return encoder.toUint8Array() + }; + + /** + * Encode State as Uint8Array. + * + * @param {Doc} doc + * @return {Uint8Array} + * + * @function + */ + const encodeStateVector = doc => encodeStateVectorV2(doc, new DefaultDSEncoder()); + + /** + * General event handler implementation. + * + * @template ARG0, ARG1 + * + * @private + */ + class EventHandler { + constructor () { + /** + * @type {Array} + */ + this.l = []; + } + } + + /** + * @template ARG0,ARG1 + * @returns {EventHandler} + * + * @private + * @function + */ + const createEventHandler = () => new EventHandler(); + + /** + * Adds an event listener that is called when + * {@link EventHandler#callEventListeners} is called. + * + * @template ARG0,ARG1 + * @param {EventHandler} eventHandler + * @param {function(ARG0,ARG1):void} f The event handler. + * + * @private + * @function + */ + const addEventHandlerListener = (eventHandler, f) => + eventHandler.l.push(f); + + /** + * Removes an event listener. + * + * @template ARG0,ARG1 + * @param {EventHandler} eventHandler + * @param {function(ARG0,ARG1):void} f The event handler that was added with + * {@link EventHandler#addEventListener} + * + * @private + * @function + */ + const removeEventHandlerListener = (eventHandler, f) => { + const l = eventHandler.l; + const len = l.length; + eventHandler.l = l.filter(g => f !== g); + if (len === eventHandler.l.length) { + console.error('[yjs] Tried to remove event handler that doesn\'t exist.'); + } + }; + + /** + * Call all event listeners that were added via + * {@link EventHandler#addEventListener}. + * + * @template ARG0,ARG1 + * @param {EventHandler} eventHandler + * @param {ARG0} arg0 + * @param {ARG1} arg1 + * + * @private + * @function + */ + const callEventHandlerListeners = (eventHandler, arg0, arg1) => + callAll(eventHandler.l, [arg0, arg1]); + + class ID { + /** + * @param {number} client client id + * @param {number} clock unique per client id, continuous number + */ + constructor (client, clock) { + /** + * Client id + * @type {number} + */ + this.client = client; + /** + * unique per client id, continuous number + * @type {number} + */ + this.clock = clock; + } + } + + /** + * @param {ID | null} a + * @param {ID | null} b + * @return {boolean} + * + * @function + */ + const compareIDs = (a, b) => a === b || (a !== null && b !== null && a.client === b.client && a.clock === b.clock); + + /** + * @param {number} client + * @param {number} clock + * + * @private + * @function + */ + const createID = (client, clock) => new ID(client, clock); + + /** + * The top types are mapped from y.share.get(keyname) => type. + * `type` does not store any information about the `keyname`. + * This function finds the correct `keyname` for `type` and throws otherwise. + * + * @param {AbstractType} type + * @return {string} + * + * @private + * @function + */ + const findRootTypeKey = type => { + // @ts-ignore _y must be defined, otherwise unexpected case + for (const [key, value] of type.doc.share.entries()) { + if (value === type) { + return key + } + } + throw unexpectedCase() + }; + + /** + * Check if `parent` is a parent of `child`. + * + * @param {AbstractType} parent + * @param {Item|null} child + * @return {Boolean} Whether `parent` is a parent of `child`. + * + * @private + * @function + */ + const isParentOf = (parent, child) => { + while (child !== null) { + if (child.parent === parent) { + return true + } + child = /** @type {AbstractType} */ (child.parent)._item; + } + return false + }; + + /** + * A relative position is based on the Yjs model and is not affected by document changes. + * E.g. If you place a relative position before a certain character, it will always point to this character. + * If you place a relative position at the end of a type, it will always point to the end of the type. + * + * A numeric position is often unsuited for user selections, because it does not change when content is inserted + * before or after. + * + * ```Insert(0, 'x')('a|bc') = 'xa|bc'``` Where | is the relative position. + * + * One of the properties must be defined. + * + * @example + * // Current cursor position is at position 10 + * const relativePosition = createRelativePositionFromIndex(yText, 10) + * // modify yText + * yText.insert(0, 'abc') + * yText.delete(3, 10) + * // Compute the cursor position + * const absolutePosition = createAbsolutePositionFromRelativePosition(y, relativePosition) + * absolutePosition.type === yText // => true + * console.log('cursor location is ' + absolutePosition.index) // => cursor location is 3 + * + */ + class RelativePosition { + /** + * @param {ID|null} type + * @param {string|null} tname + * @param {ID|null} item + */ + constructor (type, tname, item) { + /** + * @type {ID|null} + */ + this.type = type; + /** + * @type {string|null} + */ + this.tname = tname; + /** + * @type {ID | null} + */ + this.item = item; + } + } + + /** + * @param {any} json + * @return {RelativePosition} + * + * @function + */ + const createRelativePositionFromJSON = json => new RelativePosition(json.type == null ? null : createID(json.type.client, json.type.clock), json.tname || null, json.item == null ? null : createID(json.item.client, json.item.clock)); + + class AbsolutePosition { + /** + * @param {AbstractType} type + * @param {number} index + */ + constructor (type, index) { + /** + * @type {AbstractType} + */ + this.type = type; + /** + * @type {number} + */ + this.index = index; + } + } + + /** + * @param {AbstractType} type + * @param {number} index + * + * @function + */ + const createAbsolutePosition = (type, index) => new AbsolutePosition(type, index); + + /** + * @param {AbstractType} type + * @param {ID|null} item + * + * @function + */ + const createRelativePosition = (type, item) => { + let typeid = null; + let tname = null; + if (type._item === null) { + tname = findRootTypeKey(type); + } else { + typeid = createID(type._item.id.client, type._item.id.clock); + } + return new RelativePosition(typeid, tname, item) + }; + + /** + * Create a relativePosition based on a absolute position. + * + * @param {AbstractType} type The base type (e.g. YText or YArray). + * @param {number} index The absolute position. + * @return {RelativePosition} + * + * @function + */ + const createRelativePositionFromTypeIndex = (type, index) => { + let t = type._start; + while (t !== null) { + if (!t.deleted && t.countable) { + if (t.length > index) { + // case 1: found position somewhere in the linked list + return createRelativePosition(type, createID(t.id.client, t.id.clock + index)) + } + index -= t.length; + } + t = t.right; + } + return createRelativePosition(type, null) + }; + + /** + * @param {RelativePosition} rpos + * @param {Doc} doc + * @return {AbsolutePosition|null} + * + * @function + */ + const createAbsolutePositionFromRelativePosition = (rpos, doc) => { + const store = doc.store; + const rightID = rpos.item; + const typeID = rpos.type; + const tname = rpos.tname; + let type = null; + let index = 0; + if (rightID !== null) { + if (getState(store, rightID.client) <= rightID.clock) { + return null + } + const res = followRedone(store, rightID); + const right = res.item; + if (!(right instanceof Item)) { + return null + } + type = /** @type {AbstractType} */ (right.parent); + if (type._item === null || !type._item.deleted) { + index = right.deleted || !right.countable ? 0 : res.diff; + let n = right.left; + while (n !== null) { + if (!n.deleted && n.countable) { + index += n.length; + } + n = n.left; + } + } + } else { + if (tname !== null) { + type = doc.get(tname); + } else if (typeID !== null) { + if (getState(store, typeID.client) <= typeID.clock) { + // type does not exist yet + return null + } + const { item } = followRedone(store, typeID); + if (item instanceof Item && item.content instanceof ContentType) { + type = item.content.type; + } else { + // struct is garbage collected + return null + } + } else { + throw unexpectedCase() + } + index = type._length; + } + return createAbsolutePosition(type, index) + }; + + /** + * @param {RelativePosition|null} a + * @param {RelativePosition|null} b + * + * @function + */ + const compareRelativePositions = (a, b) => a === b || ( + a !== null && b !== null && a.tname === b.tname && compareIDs(a.item, b.item) && compareIDs(a.type, b.type) + ); + + class Snapshot { + /** + * @param {DeleteSet} ds + * @param {Map} sv state map + */ + constructor (ds, sv) { + /** + * @type {DeleteSet} + */ + this.ds = ds; + /** + * State Map + * @type {Map} + */ + this.sv = sv; + } + } + + /** + * @param {DeleteSet} ds + * @param {Map} sm + * @return {Snapshot} + */ + const createSnapshot = (ds, sm) => new Snapshot(ds, sm); + + /** + * @param {Doc} doc + * @return {Snapshot} + */ + const snapshot = doc => createSnapshot(createDeleteSetFromStructStore(doc.store), getStateVector(doc.store)); + + /** + * @param {Item} item + * @param {Snapshot|undefined} snapshot + * + * @protected + * @function + */ + const isVisible = (item, snapshot) => snapshot === undefined ? !item.deleted : ( + snapshot.sv.has(item.id.client) && (snapshot.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot.ds, item.id) + ); + + /** + * @param {Transaction} transaction + * @param {Snapshot} snapshot + */ + const splitSnapshotAffectedStructs = (transaction, snapshot) => { + const meta = setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, create$1); + const store = transaction.doc.store; + // check if we already split for this snapshot + if (!meta.has(snapshot)) { + snapshot.sv.forEach((clock, client) => { + if (clock < getState(store, client)) { + getItemCleanStart(transaction, createID(client, clock)); + } + }); + iterateDeletedStructs(transaction, snapshot.ds, item => {}); + meta.add(snapshot); + } + }; + + class StructStore { + constructor () { + /** + * @type {Map>} + */ + this.clients = new Map(); + /** + * Store incompleted struct reads here + * `i` denotes to the next read operation + * We could shift the array of refs instead, but shift is incredible + * slow in Chrome for arrays with more than 100k elements + * @see tryResumePendingStructRefs + * @type {Map}>} + */ + this.pendingClientsStructRefs = new Map(); + /** + * Stack of pending structs waiting for struct dependencies + * Maximum length of stack is structReaders.size + * @type {Array} + */ + this.pendingStack = []; + /** + * @type {Array} + */ + this.pendingDeleteReaders = []; + } + } + + /** + * Return the states as a Map. + * Note that clock refers to the next expected clock id. + * + * @param {StructStore} store + * @return {Map} + * + * @public + * @function + */ + const getStateVector = store => { + const sm = new Map(); + store.clients.forEach((structs, client) => { + const struct = structs[structs.length - 1]; + sm.set(client, struct.id.clock + struct.length); + }); + return sm + }; + + /** + * @param {StructStore} store + * @param {number} client + * @return {number} + * + * @public + * @function + */ + const getState = (store, client) => { + const structs = store.clients.get(client); + if (structs === undefined) { + return 0 + } + const lastStruct = structs[structs.length - 1]; + return lastStruct.id.clock + lastStruct.length + }; + + /** + * @param {StructStore} store + * @param {GC|Item} struct + * + * @private + * @function + */ + const addStruct = (store, struct) => { + let structs = store.clients.get(struct.id.client); + if (structs === undefined) { + structs = []; + store.clients.set(struct.id.client, structs); + } else { + const lastStruct = structs[structs.length - 1]; + if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) { + throw unexpectedCase() + } + } + structs.push(struct); + }; + + /** + * Perform a binary search on a sorted array + * @param {Array} structs + * @param {number} clock + * @return {number} + * + * @private + * @function + */ + const findIndexSS = (structs, clock) => { + let left = 0; + let right = structs.length - 1; + let mid = structs[right]; + let midclock = mid.id.clock; + if (midclock === clock) { + return right + } + // @todo does it even make sense to pivot the search? + // If a good split misses, it might actually increase the time to find the correct item. + // Currently, the only advantage is that search with pivoting might find the item on the first try. + let midindex = floor((clock / (midclock + mid.length - 1)) * right); // pivoting the search + while (left <= right) { + mid = structs[midindex]; + midclock = mid.id.clock; + if (midclock <= clock) { + if (clock < midclock + mid.length) { + return midindex + } + left = midindex + 1; + } else { + right = midindex - 1; + } + midindex = floor((left + right) / 2); + } + // Always check state before looking for a struct in StructStore + // Therefore the case of not finding a struct is unexpected + throw unexpectedCase() + }; + + /** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * + * @param {StructStore} store + * @param {ID} id + * @return {GC|Item} + * + * @private + * @function + */ + const find = (store, id) => { + /** + * @type {Array} + */ + // @ts-ignore + const structs = store.clients.get(id.client); + return structs[findIndexSS(structs, id.clock)] + }; + + /** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * @private + * @function + */ + const getItem = /** @type {function(StructStore,ID):Item} */ (find); + + /** + * @param {Transaction} transaction + * @param {Array} structs + * @param {number} clock + */ + const findIndexCleanStart = (transaction, structs, clock) => { + const index = findIndexSS(structs, clock); + const struct = structs[index]; + if (struct.id.clock < clock && struct instanceof Item) { + structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); + return index + 1 + } + return index + }; + + /** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * + * @param {Transaction} transaction + * @param {ID} id + * @return {Item} + * + * @private + * @function + */ + const getItemCleanStart = (transaction, id) => { + const structs = /** @type {Array} */ (transaction.doc.store.clients.get(id.client)); + return structs[findIndexCleanStart(transaction, structs, id.clock)] + }; + + /** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * + * @param {Transaction} transaction + * @param {StructStore} store + * @param {ID} id + * @return {Item} + * + * @private + * @function + */ + const getItemCleanEnd = (transaction, store, id) => { + /** + * @type {Array} + */ + // @ts-ignore + const structs = store.clients.get(id.client); + const index = findIndexSS(structs, id.clock); + const struct = structs[index]; + if (id.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) { + structs.splice(index + 1, 0, splitItem(transaction, struct, id.clock - struct.id.clock + 1)); + } + return struct + }; + + /** + * Replace `item` with `newitem` in store + * @param {StructStore} store + * @param {GC|Item} struct + * @param {GC|Item} newStruct + * + * @private + * @function + */ + const replaceStruct = (store, struct, newStruct) => { + const structs = /** @type {Array} */ (store.clients.get(struct.id.client)); + structs[findIndexSS(structs, struct.id.clock)] = newStruct; + }; + + /** + * Iterate over a range of structs + * + * @param {Transaction} transaction + * @param {Array} structs + * @param {number} clockStart Inclusive start + * @param {number} len + * @param {function(GC|Item):void} f + * + * @function + */ + const iterateStructs = (transaction, structs, clockStart, len, f) => { + if (len === 0) { + return + } + const clockEnd = clockStart + len; + let index = findIndexCleanStart(transaction, structs, clockStart); + let struct; + do { + struct = structs[index++]; + if (clockEnd < struct.id.clock + struct.length) { + findIndexCleanStart(transaction, structs, clockEnd); + } + f(struct); + } while (index < structs.length && structs[index].id.clock < clockEnd) + }; + + /** + * A transaction is created for every change on the Yjs model. It is possible + * to bundle changes on the Yjs model in a single transaction to + * minimize the number on messages sent and the number of observer calls. + * If possible the user of this library should bundle as many changes as + * possible. Here is an example to illustrate the advantages of bundling: + * + * @example + * const map = y.define('map', YMap) + * // Log content when change is triggered + * map.observe(() => { + * console.log('change triggered') + * }) + * // Each change on the map type triggers a log message: + * map.set('a', 0) // => "change triggered" + * map.set('b', 0) // => "change triggered" + * // When put in a transaction, it will trigger the log after the transaction: + * y.transact(() => { + * map.set('a', 1) + * map.set('b', 1) + * }) // => "change triggered" + * + * @public + */ + class Transaction { + /** + * @param {Doc} doc + * @param {any} origin + * @param {boolean} local + */ + constructor (doc, origin, local) { + /** + * The Yjs instance. + * @type {Doc} + */ + this.doc = doc; + /** + * Describes the set of deleted items by ids + * @type {DeleteSet} + */ + this.deleteSet = new DeleteSet(); + /** + * Holds the state before the transaction started. + * @type {Map} + */ + this.beforeState = getStateVector(doc.store); + /** + * Holds the state after the transaction. + * @type {Map} + */ + this.afterState = new Map(); + /** + * All types that were directly modified (property added or child + * inserted/deleted). New types are not included in this Set. + * Maps from type to parentSubs (`item.parentSub = null` for YArray) + * @type {Map,Set>} + */ + this.changed = new Map(); + /** + * Stores the events for the types that observe also child elements. + * It is mainly used by `observeDeep`. + * @type {Map,Array>} + */ + this.changedParentTypes = new Map(); + /** + * @type {Array} + */ + this._mergeStructs = []; + /** + * @type {any} + */ + this.origin = origin; + /** + * Stores meta information on the transaction + * @type {Map} + */ + this.meta = new Map(); + /** + * Whether this change originates from this doc. + * @type {boolean} + */ + this.local = local; + /** + * @type {Set} + */ + this.subdocsAdded = new Set(); + /** + * @type {Set} + */ + this.subdocsRemoved = new Set(); + /** + * @type {Set} + */ + this.subdocsLoaded = new Set(); + } + } + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {Transaction} transaction + * @return {boolean} Whether data was written. + */ + const writeUpdateMessageFromTransaction = (encoder, transaction) => { + if (transaction.deleteSet.clients.size === 0 && !any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) { + return false + } + sortAndMergeDeleteSet(transaction.deleteSet); + writeStructsFromTransaction(encoder, transaction); + writeDeleteSet(encoder, transaction.deleteSet); + return true + }; + + /** + * If `type.parent` was added in current transaction, `type` technically + * did not change, it was just added and we should not fire events for `type`. + * + * @param {Transaction} transaction + * @param {AbstractType} type + * @param {string|null} parentSub + */ + const addChangedTypeToTransaction = (transaction, type, parentSub) => { + const item = type._item; + if (item === null || (item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted)) { + setIfUndefined(transaction.changed, type, create$1).add(parentSub); + } + }; + + /** + * @param {Array} structs + * @param {number} pos + */ + const tryToMergeWithLeft = (structs, pos) => { + const left = structs[pos - 1]; + const right = structs[pos]; + if (left.deleted === right.deleted && left.constructor === right.constructor) { + if (left.mergeWith(right)) { + structs.splice(pos, 1); + if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType} */ (right.parent)._map.get(right.parentSub) === right) { + /** @type {AbstractType} */ (right.parent)._map.set(right.parentSub, /** @type {Item} */ (left)); + } + } + } + }; + + /** + * @param {DeleteSet} ds + * @param {StructStore} store + * @param {function(Item):boolean} gcFilter + */ + const tryGcDeleteSet = (ds, store, gcFilter) => { + for (const [client, deleteItems] of ds.clients.entries()) { + const structs = /** @type {Array} */ (store.clients.get(client)); + for (let di = deleteItems.length - 1; di >= 0; di--) { + const deleteItem = deleteItems[di]; + const endDeleteItemClock = deleteItem.clock + deleteItem.len; + for ( + let si = findIndexSS(structs, deleteItem.clock), struct = structs[si]; + si < structs.length && struct.id.clock < endDeleteItemClock; + struct = structs[++si] + ) { + const struct = structs[si]; + if (deleteItem.clock + deleteItem.len <= struct.id.clock) { + break + } + if (struct instanceof Item && struct.deleted && !struct.keep && gcFilter(struct)) { + struct.gc(store, false); + } + } + } + } + }; + + /** + * @param {DeleteSet} ds + * @param {StructStore} store + */ + const tryMergeDeleteSet = (ds, store) => { + // try to merge deleted / gc'd items + // merge from right to left for better efficiecy and so we don't miss any merge targets + ds.clients.forEach((deleteItems, client) => { + const structs = /** @type {Array} */ (store.clients.get(client)); + for (let di = deleteItems.length - 1; di >= 0; di--) { + const deleteItem = deleteItems[di]; + // start with merging the item next to the last deleted item + const mostRightIndexToCheck = min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1)); + for ( + let si = mostRightIndexToCheck, struct = structs[si]; + si > 0 && struct.id.clock >= deleteItem.clock; + struct = structs[--si] + ) { + tryToMergeWithLeft(structs, si); + } + } + }); + }; + + /** + * @param {Array} transactionCleanups + * @param {number} i + */ + const cleanupTransactions = (transactionCleanups, i) => { + if (i < transactionCleanups.length) { + const transaction = transactionCleanups[i]; + const doc = transaction.doc; + const store = doc.store; + const ds = transaction.deleteSet; + const mergeStructs = transaction._mergeStructs; + try { + sortAndMergeDeleteSet(ds); + transaction.afterState = getStateVector(transaction.doc.store); + doc._transaction = null; + doc.emit('beforeObserverCalls', [transaction, doc]); + /** + * An array of event callbacks. + * + * Each callback is called even if the other ones throw errors. + * + * @type {Array} + */ + const fs = []; + // observe events on changed types + transaction.changed.forEach((subs, itemtype) => + fs.push(() => { + if (itemtype._item === null || !itemtype._item.deleted) { + itemtype._callObserver(transaction, subs); + } + }) + ); + fs.push(() => { + // deep observe events + transaction.changedParentTypes.forEach((events, type) => + fs.push(() => { + // We need to think about the possibility that the user transforms the + // Y.Doc in the event. + if (type._item === null || !type._item.deleted) { + events = events + .filter(event => + event.target._item === null || !event.target._item.deleted + ); + events + .forEach(event => { + event.currentTarget = type; + }); + // sort events by path length so that top-level events are fired first. + events + .sort((event1, event2) => event1.path.length - event2.path.length); + // We don't need to check for events.length + // because we know it has at least one element + callEventHandlerListeners(type._dEH, events, transaction); + } + }) + ); + fs.push(() => doc.emit('afterTransaction', [transaction, doc])); + }); + callAll(fs, []); + } finally { + // Replace deleted items with ItemDeleted / GC. + // This is where content is actually remove from the Yjs Doc. + if (doc.gc) { + tryGcDeleteSet(ds, store, doc.gcFilter); + } + tryMergeDeleteSet(ds, store); + + // on all affected store.clients props, try to merge + transaction.afterState.forEach((clock, client) => { + const beforeClock = transaction.beforeState.get(client) || 0; + if (beforeClock !== clock) { + const structs = /** @type {Array} */ (store.clients.get(client)); + // we iterate from right to left so we can safely remove entries + const firstChangePos = max(findIndexSS(structs, beforeClock), 1); + for (let i = structs.length - 1; i >= firstChangePos; i--) { + tryToMergeWithLeft(structs, i); + } + } + }); + // try to merge mergeStructs + // @todo: it makes more sense to transform mergeStructs to a DS, sort it, and merge from right to left + // but at the moment DS does not handle duplicates + for (let i = 0; i < mergeStructs.length; i++) { + const { client, clock } = mergeStructs[i].id; + const structs = /** @type {Array} */ (store.clients.get(client)); + const replacedStructPos = findIndexSS(structs, clock); + if (replacedStructPos + 1 < structs.length) { + tryToMergeWithLeft(structs, replacedStructPos + 1); + } + if (replacedStructPos > 0) { + tryToMergeWithLeft(structs, replacedStructPos); + } + } + if (!transaction.local && transaction.afterState.get(doc.clientID) !== transaction.beforeState.get(doc.clientID)) { + doc.clientID = generateNewClientId(); + print(ORANGE, BOLD, '[yjs] ', UNBOLD, RED, 'Changed the client-id because another client seems to be using it.'); + } + // @todo Merge all the transactions into one and provide send the data as a single update message + doc.emit('afterTransactionCleanup', [transaction, doc]); + if (doc._observers.has('update')) { + const encoder = new DefaultUpdateEncoder(); + const hasContent = writeUpdateMessageFromTransaction(encoder, transaction); + if (hasContent) { + doc.emit('update', [encoder.toUint8Array(), transaction.origin, doc]); + } + } + if (doc._observers.has('updateV2')) { + const encoder = new UpdateEncoderV2(); + const hasContent = writeUpdateMessageFromTransaction(encoder, transaction); + if (hasContent) { + doc.emit('updateV2', [encoder.toUint8Array(), transaction.origin, doc]); + } + } + transaction.subdocsAdded.forEach(subdoc => doc.subdocs.add(subdoc)); + transaction.subdocsRemoved.forEach(subdoc => doc.subdocs.delete(subdoc)); + + doc.emit('subdocs', [{ loaded: transaction.subdocsLoaded, added: transaction.subdocsAdded, removed: transaction.subdocsRemoved }]); + transaction.subdocsRemoved.forEach(subdoc => subdoc.destroy()); + + if (transactionCleanups.length <= i + 1) { + doc._transactionCleanups = []; + doc.emit('afterAllTransactions', [doc, transactionCleanups]); + } else { + cleanupTransactions(transactionCleanups, i + 1); + } + } + } + }; + + /** + * Implements the functionality of `y.transact(()=>{..})` + * + * @param {Doc} doc + * @param {function(Transaction):void} f + * @param {any} [origin=true] + * + * @function + */ + const transact = (doc, f, origin = null, local = true) => { + const transactionCleanups = doc._transactionCleanups; + let initialCall = false; + if (doc._transaction === null) { + initialCall = true; + doc._transaction = new Transaction(doc, origin, local); + transactionCleanups.push(doc._transaction); + if (transactionCleanups.length === 1) { + doc.emit('beforeAllTransactions', [doc]); + } + doc.emit('beforeTransaction', [doc._transaction, doc]); + } + try { + f(doc._transaction); + } finally { + if (initialCall && transactionCleanups[0] === doc._transaction) { + // The first transaction ended, now process observer calls. + // Observer call may create new transactions for which we need to call the observers and do cleanup. + // We don't want to nest these calls, so we execute these calls one after + // another. + // Also we need to ensure that all cleanups are called, even if the + // observes throw errors. + // This file is full of hacky try {} finally {} blocks to ensure that an + // event can throw errors and also that the cleanup is called. + cleanupTransactions(transactionCleanups, 0); + } + } + }; + + class StackItem { + /** + * @param {DeleteSet} ds + * @param {Map} beforeState + * @param {Map} afterState + */ + constructor (ds, beforeState, afterState) { + this.ds = ds; + this.beforeState = beforeState; + this.afterState = afterState; + /** + * Use this to save and restore metadata like selection range + */ + this.meta = new Map(); + } + } + + /** + * @param {UndoManager} undoManager + * @param {Array} stack + * @param {string} eventType + * @return {StackItem?} + */ + const popStackItem = (undoManager, stack, eventType) => { + /** + * Whether a change happened + * @type {StackItem?} + */ + let result = null; + const doc = undoManager.doc; + const scope = undoManager.scope; + transact(doc, transaction => { + while (stack.length > 0 && result === null) { + const store = doc.store; + const stackItem = /** @type {StackItem} */ (stack.pop()); + /** + * @type {Set} + */ + const itemsToRedo = new Set(); + /** + * @type {Array} + */ + const itemsToDelete = []; + let performedChange = false; + stackItem.afterState.forEach((endClock, client) => { + const startClock = stackItem.beforeState.get(client) || 0; + const len = endClock - startClock; + // @todo iterateStructs should not need the structs parameter + const structs = /** @type {Array} */ (store.clients.get(client)); + if (startClock !== endClock) { + // make sure structs don't overlap with the range of created operations [stackItem.start, stackItem.start + stackItem.end) + // this must be executed before deleted structs are iterated. + getItemCleanStart(transaction, createID(client, startClock)); + if (endClock < getState(doc.store, client)) { + getItemCleanStart(transaction, createID(client, endClock)); + } + iterateStructs(transaction, structs, startClock, len, struct => { + if (struct instanceof Item) { + if (struct.redone !== null) { + let { item, diff } = followRedone(store, struct.id); + if (diff > 0) { + item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff)); + } + if (item.length > len) { + getItemCleanStart(transaction, createID(item.id.client, endClock)); + } + struct = item; + } + if (!struct.deleted && scope.some(type => isParentOf(type, /** @type {Item} */ (struct)))) { + itemsToDelete.push(struct); + } + } + }); + } + }); + iterateDeletedStructs(transaction, stackItem.ds, struct => { + const id = struct.id; + const clock = id.clock; + const client = id.client; + const startClock = stackItem.beforeState.get(client) || 0; + const endClock = stackItem.afterState.get(client) || 0; + if ( + struct instanceof Item && + scope.some(type => isParentOf(type, struct)) && + // Never redo structs in [stackItem.start, stackItem.start + stackItem.end) because they were created and deleted in the same capture interval. + !(clock >= startClock && clock < endClock) + ) { + itemsToRedo.add(struct); + } + }); + itemsToRedo.forEach(struct => { + performedChange = redoItem(transaction, struct, itemsToRedo) !== null || performedChange; + }); + // We want to delete in reverse order so that children are deleted before + // parents, so we have more information available when items are filtered. + for (let i = itemsToDelete.length - 1; i >= 0; i--) { + const item = itemsToDelete[i]; + if (undoManager.deleteFilter(item)) { + item.delete(transaction); + performedChange = true; + } + } + result = stackItem; + if (result != null) { + undoManager.emit('stack-item-popped', [{ stackItem: result, type: eventType }, undoManager]); + } + } + transaction.changed.forEach((subProps, type) => { + // destroy search marker if necessary + if (subProps.has(null) && type._searchMarker) { + type._searchMarker.length = 0; + } + }); + }, undoManager); + return result + }; + + /** + * @typedef {Object} UndoManagerOptions + * @property {number} [UndoManagerOptions.captureTimeout=500] + * @property {function(Item):boolean} [UndoManagerOptions.deleteFilter=()=>true] Sometimes + * it is necessary to filter whan an Undo/Redo operation can delete. If this + * filter returns false, the type/item won't be deleted even it is in the + * undo/redo scope. + * @property {Set} [UndoManagerOptions.trackedOrigins=new Set([null])] + */ + + /** + * Fires 'stack-item-added' event when a stack item was added to either the undo- or + * the redo-stack. You may store additional stack information via the + * metadata property on `event.stackItem.meta` (it is a `Map` of metadata properties). + * Fires 'stack-item-popped' event when a stack item was popped from either the + * undo- or the redo-stack. You may restore the saved stack information from `event.stackItem.meta`. + * + * @extends {Observable<'stack-item-added'|'stack-item-popped'>} + */ + class UndoManager extends Observable { + /** + * @param {AbstractType|Array>} typeScope Accepts either a single type, or an array of types + * @param {UndoManagerOptions} options + */ + constructor (typeScope, { captureTimeout = 500, deleteFilter = () => true, trackedOrigins = new Set([null]) } = {}) { + super(); + this.scope = typeScope instanceof Array ? typeScope : [typeScope]; + this.deleteFilter = deleteFilter; + trackedOrigins.add(this); + this.trackedOrigins = trackedOrigins; + /** + * @type {Array} + */ + this.undoStack = []; + /** + * @type {Array} + */ + this.redoStack = []; + /** + * Whether the client is currently undoing (calling UndoManager.undo) + * + * @type {boolean} + */ + this.undoing = false; + this.redoing = false; + this.doc = /** @type {Doc} */ (this.scope[0].doc); + this.lastChange = 0; + this.doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => { + // Only track certain transactions + if (!this.scope.some(type => transaction.changedParentTypes.has(type)) || (!this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor)))) { + return + } + const undoing = this.undoing; + const redoing = this.redoing; + const stack = undoing ? this.redoStack : this.undoStack; + if (undoing) { + this.stopCapturing(); // next undo should not be appended to last stack item + } else if (!redoing) { + // neither undoing nor redoing: delete redoStack + this.redoStack = []; + } + const beforeState = transaction.beforeState; + const afterState = transaction.afterState; + const now = getUnixTime(); + if (now - this.lastChange < captureTimeout && stack.length > 0 && !undoing && !redoing) { + // append change to last stack op + const lastOp = stack[stack.length - 1]; + lastOp.ds = mergeDeleteSets([lastOp.ds, transaction.deleteSet]); + lastOp.afterState = afterState; + } else { + // create a new stack op + stack.push(new StackItem(transaction.deleteSet, beforeState, afterState)); + } + if (!undoing && !redoing) { + this.lastChange = now; + } + // make sure that deleted structs are not gc'd + iterateDeletedStructs(transaction, transaction.deleteSet, /** @param {Item|GC} item */ item => { + if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) { + keepItem(item, true); + } + }); + this.emit('stack-item-added', [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? 'redo' : 'undo' }, this]); + }); + } + + clear () { + this.doc.transact(transaction => { + /** + * @param {StackItem} stackItem + */ + const clearItem = stackItem => { + iterateDeletedStructs(transaction, stackItem.ds, item => { + if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) { + keepItem(item, false); + } + }); + }; + this.undoStack.forEach(clearItem); + this.redoStack.forEach(clearItem); + }); + this.undoStack = []; + this.redoStack = []; + } + + /** + * UndoManager merges Undo-StackItem if they are created within time-gap + * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next + * StackItem won't be merged. + * + * + * @example + * // without stopCapturing + * ytext.insert(0, 'a') + * ytext.insert(1, 'b') + * um.undo() + * ytext.toString() // => '' (note that 'ab' was removed) + * // with stopCapturing + * ytext.insert(0, 'a') + * um.stopCapturing() + * ytext.insert(0, 'b') + * um.undo() + * ytext.toString() // => 'a' (note that only 'b' was removed) + * + */ + stopCapturing () { + this.lastChange = 0; + } + + /** + * Undo last changes on type. + * + * @return {StackItem?} Returns StackItem if a change was applied + */ + undo () { + this.undoing = true; + let res; + try { + res = popStackItem(this, this.undoStack, 'undo'); + } finally { + this.undoing = false; + } + return res + } + + /** + * Redo last undo operation. + * + * @return {StackItem?} Returns StackItem if a change was applied + */ + redo () { + this.redoing = true; + let res; + try { + res = popStackItem(this, this.redoStack, 'redo'); + } finally { + this.redoing = false; + } + return res + } + } + + /** + * YEvent describes the changes on a YType. + */ + class YEvent { + /** + * @param {AbstractType} target The changed type. + * @param {Transaction} transaction + */ + constructor (target, transaction) { + /** + * The type on which this event was created on. + * @type {AbstractType} + */ + this.target = target; + /** + * The current target on which the observe callback is called. + * @type {AbstractType} + */ + this.currentTarget = target; + /** + * The transaction that triggered this event. + * @type {Transaction} + */ + this.transaction = transaction; + /** + * @type {Object|null} + */ + this._changes = null; + } + + /** + * Computes the path from `y` to the changed type. + * + * The following property holds: + * @example + * let type = y + * event.path.forEach(dir => { + * type = type.get(dir) + * }) + * type === event.target // => true + */ + get path () { + // @ts-ignore _item is defined because target is integrated + return getPathTo(this.currentTarget, this.target) + } + + /** + * Check if a struct is deleted by this event. + * + * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. + * + * @param {AbstractStruct} struct + * @return {boolean} + */ + deletes (struct) { + return isDeleted(this.transaction.deleteSet, struct.id) + } + + /** + * Check if a struct is added by this event. + * + * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. + * + * @param {AbstractStruct} struct + * @return {boolean} + */ + adds (struct) { + return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0) + } + + /** + * @return {{added:Set,deleted:Set,keys:Map,delta:Array<{insert:Array}|{delete:number}|{retain:number}>}} + */ + get changes () { + let changes = this._changes; + if (changes === null) { + const target = this.target; + const added = create$1(); + const deleted = create$1(); + /** + * @type {Array<{insert:Array}|{delete:number}|{retain:number}>} + */ + const delta = []; + /** + * @type {Map} + */ + const keys = new Map(); + changes = { + added, deleted, delta, keys + }; + const changed = /** @type Set */ (this.transaction.changed.get(target)); + if (changed.has(null)) { + /** + * @type {any} + */ + let lastOp = null; + const packOp = () => { + if (lastOp) { + delta.push(lastOp); + } + }; + for (let item = target._start; item !== null; item = item.right) { + if (item.deleted) { + if (this.deletes(item) && !this.adds(item)) { + if (lastOp === null || lastOp.delete === undefined) { + packOp(); + lastOp = { delete: 0 }; + } + lastOp.delete += item.length; + deleted.add(item); + } // else nop + } else { + if (this.adds(item)) { + if (lastOp === null || lastOp.insert === undefined) { + packOp(); + lastOp = { insert: [] }; + } + lastOp.insert = lastOp.insert.concat(item.content.getContent()); + added.add(item); + } else { + if (lastOp === null || lastOp.retain === undefined) { + packOp(); + lastOp = { retain: 0 }; + } + lastOp.retain += item.length; + } + } + } + if (lastOp !== null && lastOp.retain === undefined) { + packOp(); + } + } + changed.forEach(key => { + if (key !== null) { + const item = /** @type {Item} */ (target._map.get(key)); + /** + * @type {'delete' | 'add' | 'update'} + */ + let action; + let oldValue; + if (this.adds(item)) { + let prev = item.left; + while (prev !== null && this.adds(prev)) { + prev = prev.left; + } + if (this.deletes(item)) { + if (prev !== null && this.deletes(prev)) { + action = 'delete'; + oldValue = last(prev.content.getContent()); + } else { + return + } + } else { + if (prev !== null && this.deletes(prev)) { + action = 'update'; + oldValue = last(prev.content.getContent()); + } else { + action = 'add'; + oldValue = undefined; + } + } + } else { + if (this.deletes(item)) { + action = 'delete'; + oldValue = last(/** @type {Item} */ item.content.getContent()); + } else { + return // nop + } + } + keys.set(key, { action, oldValue }); + } + }); + this._changes = changes; + } + return /** @type {any} */ (changes) + } + } + + /** + * Compute the path from this type to the specified target. + * + * @example + * // `child` should be accessible via `type.get(path[0]).get(path[1])..` + * const path = type.getPathTo(child) + * // assuming `type instanceof YArray` + * console.log(path) // might look like => [2, 'key1'] + * child === type.get(path[0]).get(path[1]) + * + * @param {AbstractType} parent + * @param {AbstractType} child target + * @return {Array} Path to the target + * + * @private + * @function + */ + const getPathTo = (parent, child) => { + const path = []; + while (child._item !== null && child !== parent) { + if (child._item.parentSub !== null) { + // parent is map-ish + path.unshift(child._item.parentSub); + } else { + // parent is array-ish + let i = 0; + let c = /** @type {AbstractType} */ (child._item.parent)._start; + while (c !== child._item && c !== null) { + if (!c.deleted) { + i++; + } + c = c.right; + } + path.unshift(i); + } + child = /** @type {AbstractType} */ (child._item.parent); + } + return path + }; + + const maxSearchMarker = 80; + + /** + * A unique timestamp that identifies each marker. + * + * Time is relative,.. this is more like an ever-increasing clock. + * + * @type {number} + */ + let globalSearchMarkerTimestamp = 0; + + class ArraySearchMarker { + /** + * @param {Item} p + * @param {number} index + */ + constructor (p, index) { + p.marker = true; + this.p = p; + this.index = index; + this.timestamp = globalSearchMarkerTimestamp++; + } + } + + /** + * @param {ArraySearchMarker} marker + */ + const refreshMarkerTimestamp = marker => { marker.timestamp = globalSearchMarkerTimestamp++; }; + + /** + * This is rather complex so this function is the only thing that should overwrite a marker + * + * @param {ArraySearchMarker} marker + * @param {Item} p + * @param {number} index + */ + const overwriteMarker = (marker, p, index) => { + marker.p.marker = false; + marker.p = p; + p.marker = true; + marker.index = index; + marker.timestamp = globalSearchMarkerTimestamp++; + }; + + /** + * @param {Array} searchMarker + * @param {Item} p + * @param {number} index + */ + const markPosition = (searchMarker, p, index) => { + if (searchMarker.length >= maxSearchMarker) { + // override oldest marker (we don't want to create more objects) + const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b); + overwriteMarker(marker, p, index); + return marker + } else { + // create new marker + const pm = new ArraySearchMarker(p, index); + searchMarker.push(pm); + return pm + } + }; + + /** + * Search marker help us to find positions in the associative array faster. + * + * They speed up the process of finding a position without much bookkeeping. + * + * A maximum of `maxSearchMarker` objects are created. + * + * This function always returns a refreshed marker (updated timestamp) + * + * @param {AbstractType} yarray + * @param {number} index + */ + const findMarker = (yarray, index) => { + if (yarray._start === null || index === 0 || yarray._searchMarker === null) { + return null + } + const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => abs(index - a.index) < abs(index - b.index) ? a : b); + let p = yarray._start; + let pindex = 0; + if (marker !== null) { + p = marker.p; + pindex = marker.index; + refreshMarkerTimestamp(marker); // we used it, we might need to use it again + } + // iterate to right if possible + while (p.right !== null && pindex < index) { + if (!p.deleted && p.countable) { + if (index < pindex + p.length) { + break + } + pindex += p.length; + } + p = p.right; + } + // iterate to left if necessary (might be that pindex > index) + while (p.left !== null && pindex > index) { + p = p.left; + if (!p.deleted && p.countable) { + pindex -= p.length; + } + } + // we want to make sure that p can't be merged with left, because that would screw up everything + // in that cas just return what we have (it is most likely the best marker anyway) + // iterate to left until p can't be merged with left + while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) { + p = p.left; + if (!p.deleted && p.countable) { + pindex -= p.length; + } + } + + // @todo remove! + // assure position + // { + // let start = yarray._start + // let pos = 0 + // while (start !== p) { + // if (!start.deleted && start.countable) { + // pos += start.length + // } + // start = /** @type {Item} */ (start.right) + // } + // if (pos !== pindex) { + // debugger + // throw new Error('Gotcha position fail!') + // } + // } + // if (marker) { + // if (window.lengthes == null) { + // window.lengthes = [] + // window.getLengthes = () => window.lengthes.sort((a, b) => a - b) + // } + // window.lengthes.push(marker.index - pindex) + // console.log('distance', marker.index - pindex, 'len', p && p.parent.length) + // } + if (marker !== null && abs(marker.index - pindex) < /** @type {YText|YArray} */ (p.parent).length / maxSearchMarker) { + // adjust existing marker + overwriteMarker(marker, p, pindex); + return marker + } else { + // create new marker + return markPosition(yarray._searchMarker, p, pindex) + } + }; + + /** + * Update markers when a change happened. + * + * This should be called before doing a deletion! + * + * @param {Array} searchMarker + * @param {number} index + * @param {number} len If insertion, len is positive. If deletion, len is negative. + */ + const updateMarkerChanges = (searchMarker, index, len) => { + for (let i = searchMarker.length - 1; i >= 0; i--) { + const m = searchMarker[i]; + if (len > 0) { + /** + * @type {Item|null} + */ + let p = m.p; + p.marker = false; + // Ideally we just want to do a simple position comparison, but this will only work if + // search markers don't point to deleted items for formats. + // Iterate marker to prev undeleted countable position so we know what to do when updating a position + while (p && (p.deleted || !p.countable)) { + p = p.left; + if (p && !p.deleted && p.countable) { + // adjust position. the loop should break now + m.index -= p.length; + } + } + if (p === null || p.marker === true) { + // remove search marker if updated position is null or if position is already marked + searchMarker.splice(i, 1); + continue + } + m.p = p; + p.marker = true; + } + if (index < m.index || (len > 0 && index === m.index)) { // a simple index <= m.index check would actually suffice + m.index = max(index, m.index + len); + } + } + }; + + /** + * Call event listeners with an event. This will also add an event to all + * parents (for `.observeDeep` handlers). + * + * @template EventType + * @param {AbstractType} type + * @param {Transaction} transaction + * @param {EventType} event + */ + const callTypeObservers = (type, transaction, event) => { + const changedType = type; + const changedParentTypes = transaction.changedParentTypes; + while (true) { + // @ts-ignore + setIfUndefined(changedParentTypes, type, () => []).push(event); + if (type._item === null) { + break + } + type = /** @type {AbstractType} */ (type._item.parent); + } + callEventHandlerListeners(changedType._eH, event, transaction); + }; + + /** + * @template EventType + * Abstract Yjs Type class + */ + class AbstractType { + constructor () { + /** + * @type {Item|null} + */ + this._item = null; + /** + * @type {Map} + */ + this._map = new Map(); + /** + * @type {Item|null} + */ + this._start = null; + /** + * @type {Doc|null} + */ + this.doc = null; + this._length = 0; + /** + * Event handlers + * @type {EventHandler} + */ + this._eH = createEventHandler(); + /** + * Deep event handlers + * @type {EventHandler,Transaction>} + */ + this._dEH = createEventHandler(); + /** + * @type {null | Array} + */ + this._searchMarker = null; + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item|null} item + */ + _integrate (y, item) { + this.doc = y; + this._item = item; + } + + /** + * @return {AbstractType} + */ + _copy () { + throw methodUnimplemented() + } + + /** + * @param {AbstractUpdateEncoder} encoder + */ + _write (encoder) { } + + /** + * The first non-deleted item + */ + get _first () { + let n = this._start; + while (n !== null && n.deleted) { + n = n.right; + } + return n + } + + /** + * Creates YEvent and calls all type observers. + * Must be implemented by each type. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + if (!transaction.local && this._searchMarker) { + this._searchMarker.length = 0; + } + } + + /** + * Observe all events that are created on this type. + * + * @param {function(EventType, Transaction):void} f Observer function + */ + observe (f) { + addEventHandlerListener(this._eH, f); + } + + /** + * Observe all events that are created by this type and its children. + * + * @param {function(Array,Transaction):void} f Observer function + */ + observeDeep (f) { + addEventHandlerListener(this._dEH, f); + } + + /** + * Unregister an observer function. + * + * @param {function(EventType,Transaction):void} f Observer function + */ + unobserve (f) { + removeEventHandlerListener(this._eH, f); + } + + /** + * Unregister an observer function. + * + * @param {function(Array,Transaction):void} f Observer function + */ + unobserveDeep (f) { + removeEventHandlerListener(this._dEH, f); + } + + /** + * @abstract + * @return {any} + */ + toJSON () {} + } + + /** + * @param {AbstractType} type + * @return {Array} + * + * @private + * @function + */ + const typeListToArray = type => { + const cs = []; + let n = type._start; + while (n !== null) { + if (n.countable && !n.deleted) { + const c = n.content.getContent(); + for (let i = 0; i < c.length; i++) { + cs.push(c[i]); + } + } + n = n.right; + } + return cs + }; + + /** + * @param {AbstractType} type + * @param {Snapshot} snapshot + * @return {Array} + * + * @private + * @function + */ + const typeListToArraySnapshot = (type, snapshot) => { + const cs = []; + let n = type._start; + while (n !== null) { + if (n.countable && isVisible(n, snapshot)) { + const c = n.content.getContent(); + for (let i = 0; i < c.length; i++) { + cs.push(c[i]); + } + } + n = n.right; + } + return cs + }; + + /** + * Executes a provided function on once on overy element of this YArray. + * + * @param {AbstractType} type + * @param {function(any,number,any):void} f A function to execute on every element of this YArray. + * + * @private + * @function + */ + const typeListForEach = (type, f) => { + let index = 0; + let n = type._start; + while (n !== null) { + if (n.countable && !n.deleted) { + const c = n.content.getContent(); + for (let i = 0; i < c.length; i++) { + f(c[i], index++, type); + } + } + n = n.right; + } + }; + + /** + * @template C,R + * @param {AbstractType} type + * @param {function(C,number,AbstractType):R} f + * @return {Array} + * + * @private + * @function + */ + const typeListMap = (type, f) => { + /** + * @type {Array} + */ + const result = []; + typeListForEach(type, (c, i) => { + result.push(f(c, i, type)); + }); + return result + }; + + /** + * @param {AbstractType} type + * @return {IterableIterator} + * + * @private + * @function + */ + const typeListCreateIterator = type => { + let n = type._start; + /** + * @type {Array|null} + */ + let currentContent = null; + let currentContentIndex = 0; + return { + [Symbol.iterator] () { + return this + }, + next: () => { + // find some content + if (currentContent === null) { + while (n !== null && n.deleted) { + n = n.right; + } + // check if we reached the end, no need to check currentContent, because it does not exist + if (n === null) { + return { + done: true, + value: undefined + } + } + // we found n, so we can set currentContent + currentContent = n.content.getContent(); + currentContentIndex = 0; + n = n.right; // we used the content of n, now iterate to next + } + const value = currentContent[currentContentIndex++]; + // check if we need to empty currentContent + if (currentContent.length <= currentContentIndex) { + currentContent = null; + } + return { + done: false, + value + } + } + } + }; + + /** + * @param {AbstractType} type + * @param {number} index + * @return {any} + * + * @private + * @function + */ + const typeListGet = (type, index) => { + const marker = findMarker(type, index); + let n = type._start; + if (marker !== null) { + n = marker.p; + index -= marker.index; + } + for (; n !== null; n = n.right) { + if (!n.deleted && n.countable) { + if (index < n.length) { + return n.content.getContent()[index] + } + index -= n.length; + } + } + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {Item?} referenceItem + * @param {Array|Array|boolean|number|string|Uint8Array>} content + * + * @private + * @function + */ + const typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => { + let left = referenceItem; + const doc = transaction.doc; + const ownClientId = doc.clientID; + const store = doc.store; + const right = referenceItem === null ? parent._start : referenceItem.right; + /** + * @type {Array|number>} + */ + let jsonContent = []; + const packJsonContent = () => { + if (jsonContent.length > 0) { + left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent)); + left.integrate(transaction, 0); + jsonContent = []; + } + }; + content.forEach(c => { + switch (c.constructor) { + case Number: + case Object: + case Boolean: + case Array: + case String: + jsonContent.push(c); + break + default: + packJsonContent(); + switch (c.constructor) { + case Uint8Array: + case ArrayBuffer: + left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array(/** @type {Uint8Array} */ (c)))); + left.integrate(transaction, 0); + break + case Doc: + left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc(/** @type {Doc} */ (c))); + left.integrate(transaction, 0); + break + default: + if (c instanceof AbstractType) { + left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c)); + left.integrate(transaction, 0); + } else { + throw new Error('Unexpected content type in insert operation') + } + } + } + }); + packJsonContent(); + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {number} index + * @param {Array|Array|number|string|Uint8Array>} content + * + * @private + * @function + */ + const typeListInsertGenerics = (transaction, parent, index, content) => { + if (index === 0) { + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, index, content.length); + } + return typeListInsertGenericsAfter(transaction, parent, null, content) + } + const startIndex = index; + const marker = findMarker(parent, index); + let n = parent._start; + if (marker !== null) { + n = marker.p; + index -= marker.index; + // we need to iterate one to the left so that the algorithm works + if (index === 0) { + // @todo refactor this as it actually doesn't consider formats + n = n.prev; // important! get the left undeleted item so that we can actually decrease index + index += (n && n.countable && !n.deleted) ? n.length : 0; + } + } + for (; n !== null; n = n.right) { + if (!n.deleted && n.countable) { + if (index <= n.length) { + if (index < n.length) { + // insert in-between + getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index)); + } + break + } + index -= n.length; + } + } + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, startIndex, content.length); + } + return typeListInsertGenericsAfter(transaction, parent, n, content) + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {number} index + * @param {number} length + * + * @private + * @function + */ + const typeListDelete = (transaction, parent, index, length) => { + if (length === 0) { return } + const startIndex = index; + const startLength = length; + const marker = findMarker(parent, index); + let n = parent._start; + if (marker !== null) { + n = marker.p; + index -= marker.index; + } + // compute the first item to be deleted + for (; n !== null && index > 0; n = n.right) { + if (!n.deleted && n.countable) { + if (index < n.length) { + getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index)); + } + index -= n.length; + } + } + // delete all items until done + while (length > 0 && n !== null) { + if (!n.deleted) { + if (length < n.length) { + getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length)); + } + n.delete(transaction); + length -= n.length; + } + n = n.right; + } + if (length > 0) { + throw create$2('array length exceeded') + } + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, startIndex, -startLength + length /* in case we remove the above exception */); + } + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {string} key + * + * @private + * @function + */ + const typeMapDelete = (transaction, parent, key) => { + const c = parent._map.get(key); + if (c !== undefined) { + c.delete(transaction); + } + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {string} key + * @param {Object|number|Array|string|Uint8Array|AbstractType} value + * + * @private + * @function + */ + const typeMapSet = (transaction, parent, key, value) => { + const left = parent._map.get(key) || null; + const doc = transaction.doc; + const ownClientId = doc.clientID; + let content; + if (value == null) { + content = new ContentAny([value]); + } else { + switch (value.constructor) { + case Number: + case Object: + case Boolean: + case Array: + case String: + content = new ContentAny([value]); + break + case Uint8Array: + content = new ContentBinary(/** @type {Uint8Array} */ (value)); + break + case Doc: + content = new ContentDoc(/** @type {Doc} */ (value)); + break + default: + if (value instanceof AbstractType) { + content = new ContentType(value); + } else { + throw new Error('Unexpected content type') + } + } + } + new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0); + }; + + /** + * @param {AbstractType} parent + * @param {string} key + * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined} + * + * @private + * @function + */ + const typeMapGet = (parent, key) => { + const val = parent._map.get(key); + return val !== undefined && !val.deleted ? val.content.getContent()[val.length - 1] : undefined + }; + + /** + * @param {AbstractType} parent + * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined>} + * + * @private + * @function + */ + const typeMapGetAll = (parent) => { + /** + * @type {Object} + */ + const res = {}; + parent._map.forEach((value, key) => { + if (!value.deleted) { + res[key] = value.content.getContent()[value.length - 1]; + } + }); + return res + }; + + /** + * @param {AbstractType} parent + * @param {string} key + * @return {boolean} + * + * @private + * @function + */ + const typeMapHas = (parent, key) => { + const val = parent._map.get(key); + return val !== undefined && !val.deleted + }; + + /** + * @param {Map} map + * @return {IterableIterator>} + * + * @private + * @function + */ + const createMapIterator = map => iteratorFilter(map.entries(), /** @param {any} entry */ entry => !entry[1].deleted); + + /** + * @module YArray + */ + + /** + * Event that describes the changes on a YArray + * @template T + */ + class YArrayEvent extends YEvent { + /** + * @param {YArray} yarray The changed type + * @param {Transaction} transaction The transaction object + */ + constructor (yarray, transaction) { + super(yarray, transaction); + this._transaction = transaction; + } + } + + /** + * A shared Array implementation. + * @template T + * @extends AbstractType> + * @implements {Iterable} + */ + class YArray extends AbstractType { + constructor () { + super(); + /** + * @type {Array?} + * @private + */ + this._prelimContent = []; + /** + * @type {Array} + */ + this._searchMarker = []; + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item); + this.insert(0, /** @type {Array} */ (this._prelimContent)); + this._prelimContent = null; + } + + _copy () { + return new YArray() + } + + get length () { + return this._prelimContent === null ? this._length : this._prelimContent.length + } + + /** + * Creates YArrayEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + super._callObserver(transaction, parentSubs); + callTypeObservers(this, transaction, new YArrayEvent(this, transaction)); + } + + /** + * Inserts new content at an index. + * + * Important: This function expects an array of content. Not just a content + * object. The reason for this "weirdness" is that inserting several elements + * is very efficient when it is done as a single operation. + * + * @example + * // Insert character 'a' at position 0 + * yarray.insert(0, ['a']) + * // Insert numbers 1, 2 at position 1 + * yarray.insert(1, [1, 2]) + * + * @param {number} index The index to insert content at. + * @param {Array} content The array of content + */ + insert (index, content) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListInsertGenerics(transaction, this, index, content); + }); + } else { + /** @type {Array} */ (this._prelimContent).splice(index, 0, ...content); + } + } + + /** + * Appends content to this YArray. + * + * @param {Array} content Array of content to append. + */ + push (content) { + this.insert(this.length, content); + } + + /** + * Preppends content to this YArray. + * + * @param {Array} content Array of content to preppend. + */ + unshift (content) { + this.insert(0, content); + } + + /** + * Deletes elements starting from an index. + * + * @param {number} index Index at which to start deleting elements + * @param {number} length The number of elements to remove. Defaults to 1. + */ + delete (index, length = 1) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListDelete(transaction, this, index, length); + }); + } else { + /** @type {Array} */ (this._prelimContent).splice(index, length); + } + } + + /** + * Returns the i-th element from a YArray. + * + * @param {number} index The index of the element to return from the YArray + * @return {T} + */ + get (index) { + return typeListGet(this, index) + } + + /** + * Transforms this YArray to a JavaScript Array. + * + * @return {Array} + */ + toArray () { + return typeListToArray(this) + } + + /** + * Transforms this Shared Type to a JSON object. + * + * @return {Array} + */ + toJSON () { + return this.map(c => c instanceof AbstractType ? c.toJSON() : c) + } + + /** + * Returns an Array with the result of calling a provided function on every + * element of this YArray. + * + * @template T,M + * @param {function(T,number,YArray):M} f Function that produces an element of the new Array + * @return {Array} A new array with each element being the result of the + * callback function + */ + map (f) { + return typeListMap(this, /** @type {any} */ (f)) + } + + /** + * Executes a provided function on once on overy element of this YArray. + * + * @param {function(T,number,YArray):void} f A function to execute on every element of this YArray. + */ + forEach (f) { + typeListForEach(this, f); + } + + /** + * @return {IterableIterator} + */ + [Symbol.iterator] () { + return typeListCreateIterator(this) + } + + /** + * @param {AbstractUpdateEncoder} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YArrayRefID); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * + * @private + * @function + */ + const readYArray = decoder => new YArray(); + + /** + * @template T + * Event that describes the changes on a YMap. + */ + class YMapEvent extends YEvent { + /** + * @param {YMap} ymap The YArray that changed. + * @param {Transaction} transaction + * @param {Set} subs The keys that changed. + */ + constructor (ymap, transaction, subs) { + super(ymap, transaction); + this.keysChanged = subs; + } + } + + /** + * @template T number|string|Object|Array|Uint8Array + * A shared Map implementation. + * + * @extends AbstractType> + * @implements {Iterable} + */ + class YMap extends AbstractType { + /** + * + * @param {Iterable=} entries - an optional iterable to initialize the YMap + */ + constructor (entries) { + super(); + /** + * @type {Map?} + * @private + */ + this._prelimContent = null; + + if (entries === undefined) { + this._prelimContent = new Map(); + } else { + this._prelimContent = new Map(entries); + } + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item) + ;/** @type {Map} */ (this._prelimContent).forEach((value, key) => { + this.set(key, value); + }); + this._prelimContent = null; + } + + _copy () { + return new YMap() + } + + /** + * Creates YMapEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs)); + } + + /** + * Transforms this Shared Type to a JSON object. + * + * @return {Object} + */ + toJSON () { + /** + * @type {Object} + */ + const map = {}; + this._map.forEach((item, key) => { + if (!item.deleted) { + const v = item.content.getContent()[item.length - 1]; + map[key] = v instanceof AbstractType ? v.toJSON() : v; + } + }); + return map + } + + /** + * Returns the size of the YMap (count of key/value pairs) + * + * @return {number} + */ + get size () { + return [...createMapIterator(this._map)].length + } + + /** + * Returns the keys for each element in the YMap Type. + * + * @return {IterableIterator} + */ + keys () { + return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[0]) + } + + /** + * Returns the values for each element in the YMap Type. + * + * @return {IterableIterator} + */ + values () { + return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[1].content.getContent()[v[1].length - 1]) + } + + /** + * Returns an Iterator of [key, value] pairs + * + * @return {IterableIterator} + */ + entries () { + return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => [v[0], v[1].content.getContent()[v[1].length - 1]]) + } + + /** + * Executes a provided function on once on every key-value pair. + * + * @param {function(T,string,YMap):void} f A function to execute on every element of this YArray. + */ + forEach (f) { + /** + * @type {Object} + */ + const map = {}; + this._map.forEach((item, key) => { + if (!item.deleted) { + f(item.content.getContent()[item.length - 1], key, this); + } + }); + return map + } + + /** + * @return {IterableIterator} + */ + [Symbol.iterator] () { + return this.entries() + } + + /** + * Remove a specified element from this YMap. + * + * @param {string} key The key of the element to remove. + */ + delete (key) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapDelete(transaction, this, key); + }); + } else { + /** @type {Map} */ (this._prelimContent).delete(key); + } + } + + /** + * Adds or updates an element with a specified key and value. + * + * @param {string} key The key of the element to add to this YMap + * @param {T} value The value of the element to add + */ + set (key, value) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapSet(transaction, this, key, value); + }); + } else { + /** @type {Map} */ (this._prelimContent).set(key, value); + } + return value + } + + /** + * Returns a specified element from this YMap. + * + * @param {string} key + * @return {T|undefined} + */ + get (key) { + return /** @type {any} */ (typeMapGet(this, key)) + } + + /** + * Returns a boolean indicating whether the specified key exists or not. + * + * @param {string} key The key to test. + * @return {boolean} + */ + has (key) { + return typeMapHas(this, key) + } + + /** + * @param {AbstractUpdateEncoder} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YMapRefID); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * + * @private + * @function + */ + const readYMap = decoder => new YMap(); + + /** + * @param {any} a + * @param {any} b + * @return {boolean} + */ + const equalAttrs = (a, b) => a === b || (typeof a === 'object' && typeof b === 'object' && a && b && equalFlat(a, b)); + + class ItemTextListPosition { + /** + * @param {Item|null} left + * @param {Item|null} right + * @param {number} index + * @param {Map} currentAttributes + */ + constructor (left, right, index, currentAttributes) { + this.left = left; + this.right = right; + this.index = index; + this.currentAttributes = currentAttributes; + } + + /** + * Only call this if you know that this.right is defined + */ + forward () { + if (this.right === null) { + unexpectedCase(); + } + switch (this.right.content.constructor) { + case ContentEmbed: + case ContentString: + if (!this.right.deleted) { + this.index += this.right.length; + } + break + case ContentFormat: + if (!this.right.deleted) { + updateCurrentAttributes(this.currentAttributes, /** @type {ContentFormat} */ (this.right.content)); + } + break + } + this.left = this.right; + this.right = this.right.right; + } + } + + /** + * @param {Transaction} transaction + * @param {ItemTextListPosition} pos + * @param {number} count steps to move forward + * @return {ItemTextListPosition} + * + * @private + * @function + */ + const findNextPosition = (transaction, pos, count) => { + while (pos.right !== null && count > 0) { + switch (pos.right.content.constructor) { + case ContentEmbed: + case ContentString: + if (!pos.right.deleted) { + if (count < pos.right.length) { + // split right + getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count)); + } + pos.index += pos.right.length; + count -= pos.right.length; + } + break + case ContentFormat: + if (!pos.right.deleted) { + updateCurrentAttributes(pos.currentAttributes, /** @type {ContentFormat} */ (pos.right.content)); + } + break + } + pos.left = pos.right; + pos.right = pos.right.right; + // pos.forward() - we don't forward because that would halve the performance because we already do the checks above + } + return pos + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {number} index + * @return {ItemTextListPosition} + * + * @private + * @function + */ + const findPosition = (transaction, parent, index) => { + const currentAttributes = new Map(); + const marker = findMarker(parent, index); + if (marker) { + const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes); + return findNextPosition(transaction, pos, index - marker.index) + } else { + const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes); + return findNextPosition(transaction, pos, index) + } + }; + + /** + * Negate applied formats + * + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {Map} negatedAttributes + * + * @private + * @function + */ + const insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => { + // check if we really need to remove attributes + while ( + currPos.right !== null && ( + currPos.right.deleted === true || ( + currPos.right.content.constructor === ContentFormat && + equalAttrs(negatedAttributes.get(/** @type {ContentFormat} */ (currPos.right.content).key), /** @type {ContentFormat} */ (currPos.right.content).value) + ) + ) + ) { + if (!currPos.right.deleted) { + negatedAttributes.delete(/** @type {ContentFormat} */ (currPos.right.content).key); + } + currPos.forward(); + } + const doc = transaction.doc; + const ownClientId = doc.clientID; + let left = currPos.left; + const right = currPos.right; + negatedAttributes.forEach((val, key) => { + left = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val)); + left.integrate(transaction, 0); + }); + }; + + /** + * @param {Map} currentAttributes + * @param {ContentFormat} format + * + * @private + * @function + */ + const updateCurrentAttributes = (currentAttributes, format) => { + const { key, value } = format; + if (value === null) { + currentAttributes.delete(key); + } else { + currentAttributes.set(key, value); + } + }; + + /** + * @param {ItemTextListPosition} currPos + * @param {Object} attributes + * + * @private + * @function + */ + const minimizeAttributeChanges = (currPos, attributes) => { + // go right while attributes[right.key] === right.value (or right is deleted) + while (true) { + if (currPos.right === null) { + break + } else if (currPos.right.deleted || (currPos.right.content.constructor === ContentFormat && equalAttrs(attributes[(/** @type {ContentFormat} */ (currPos.right.content)).key] || null, /** @type {ContentFormat} */ (currPos.right.content).value))) ; else { + break + } + currPos.forward(); + } + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {Object} attributes + * @return {Map} + * + * @private + * @function + **/ + const insertAttributes = (transaction, parent, currPos, attributes) => { + const doc = transaction.doc; + const ownClientId = doc.clientID; + const negatedAttributes = new Map(); + // insert format-start items + for (const key in attributes) { + const val = attributes[key]; + const currentVal = currPos.currentAttributes.get(key) || null; + if (!equalAttrs(currentVal, val)) { + // save negated attribute (set null if currentVal undefined) + negatedAttributes.set(key, currentVal); + const { left, right } = currPos; + currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val)); + currPos.right.integrate(transaction, 0); + currPos.forward(); + } + } + return negatedAttributes + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {string|object} text + * @param {Object} attributes + * + * @private + * @function + **/ + const insertText = (transaction, parent, currPos, text, attributes) => { + currPos.currentAttributes.forEach((val, key) => { + if (attributes[key] === undefined) { + attributes[key] = null; + } + }); + const doc = transaction.doc; + const ownClientId = doc.clientID; + minimizeAttributeChanges(currPos, attributes); + const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes); + // insert content + const content = text.constructor === String ? new ContentString(/** @type {string} */ (text)) : new ContentEmbed(text); + let { left, right, index } = currPos; + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength()); + } + right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content); + right.integrate(transaction, 0); + currPos.right = right; + currPos.index = index; + currPos.forward(); + insertNegatedAttributes(transaction, parent, currPos, negatedAttributes); + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {number} length + * @param {Object} attributes + * + * @private + * @function + */ + const formatText = (transaction, parent, currPos, length, attributes) => { + const doc = transaction.doc; + const ownClientId = doc.clientID; + minimizeAttributeChanges(currPos, attributes); + const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes); + // iterate until first non-format or null is found + // delete all formats with attributes[format.key] != null + while (length > 0 && currPos.right !== null) { + if (!currPos.right.deleted) { + switch (currPos.right.content.constructor) { + case ContentFormat: { + const { key, value } = /** @type {ContentFormat} */ (currPos.right.content); + const attr = attributes[key]; + if (attr !== undefined) { + if (equalAttrs(attr, value)) { + negatedAttributes.delete(key); + } else { + negatedAttributes.set(key, value); + } + currPos.right.delete(transaction); + } + break + } + case ContentEmbed: + case ContentString: + if (length < currPos.right.length) { + getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length)); + } + length -= currPos.right.length; + break + } + } + currPos.forward(); + } + // Quill just assumes that the editor starts with a newline and that it always + // ends with a newline. We only insert that newline when a new newline is + // inserted - i.e when length is bigger than type.length + if (length > 0) { + let newlines = ''; + for (; length > 0; length--) { + newlines += '\n'; + } + currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines)); + currPos.right.integrate(transaction, 0); + currPos.forward(); + } + insertNegatedAttributes(transaction, parent, currPos, negatedAttributes); + }; + + /** + * Call this function after string content has been deleted in order to + * clean up formatting Items. + * + * @param {Transaction} transaction + * @param {Item} start + * @param {Item|null} end exclusive end, automatically iterates to the next Content Item + * @param {Map} startAttributes + * @param {Map} endAttributes This attribute is modified! + * @return {number} The amount of formatting Items deleted. + * + * @function + */ + const cleanupFormattingGap = (transaction, start, end, startAttributes, endAttributes) => { + while (end && end.content.constructor !== ContentString && end.content.constructor !== ContentEmbed) { + if (!end.deleted && end.content.constructor === ContentFormat) { + updateCurrentAttributes(endAttributes, /** @type {ContentFormat} */ (end.content)); + } + end = end.right; + } + let cleanups = 0; + while (start !== end) { + if (!start.deleted) { + const content = start.content; + switch (content.constructor) { + case ContentFormat: { + const { key, value } = /** @type {ContentFormat} */ (content); + if ((endAttributes.get(key) || null) !== value || (startAttributes.get(key) || null) === value) { + // Either this format is overwritten or it is not necessary because the attribute already existed. + start.delete(transaction); + cleanups++; + } + break + } + } + } + start = /** @type {Item} */ (start.right); + } + return cleanups + }; + + /** + * @param {Transaction} transaction + * @param {Item | null} item + */ + const cleanupContextlessFormattingGap = (transaction, item) => { + // iterate until item.right is null or content + while (item && item.right && (item.right.deleted || (item.right.content.constructor !== ContentString && item.right.content.constructor !== ContentEmbed))) { + item = item.right; + } + const attrs = new Set(); + // iterate back until a content item is found + while (item && (item.deleted || (item.content.constructor !== ContentString && item.content.constructor !== ContentEmbed))) { + if (!item.deleted && item.content.constructor === ContentFormat) { + const key = /** @type {ContentFormat} */ (item.content).key; + if (attrs.has(key)) { + item.delete(transaction); + } else { + attrs.add(key); + } + } + item = item.left; + } + }; + + /** + * This function is experimental and subject to change / be removed. + * + * Ideally, we don't need this function at all. Formatting attributes should be cleaned up + * automatically after each change. This function iterates twice over the complete YText type + * and removes unnecessary formatting attributes. This is also helpful for testing. + * + * This function won't be exported anymore as soon as there is confidence that the YText type works as intended. + * + * @param {YText} type + * @return {number} How many formatting attributes have been cleaned up. + */ + const cleanupYTextFormatting = type => { + let res = 0; + transact(/** @type {Doc} */ (type.doc), transaction => { + let start = /** @type {Item} */ (type._start); + let end = type._start; + let startAttributes = create(); + const currentAttributes = copy(startAttributes); + while (end) { + if (end.deleted === false) { + switch (end.content.constructor) { + case ContentFormat: + updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (end.content)); + break + case ContentEmbed: + case ContentString: + res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes); + startAttributes = copy(currentAttributes); + start = end; + break + } + } + end = end.right; + } + }); + return res + }; + + /** + * @param {Transaction} transaction + * @param {ItemTextListPosition} currPos + * @param {number} length + * @return {ItemTextListPosition} + * + * @private + * @function + */ + const deleteText = (transaction, currPos, length) => { + const startLength = length; + const startAttrs = copy(currPos.currentAttributes); + const start = currPos.right; + while (length > 0 && currPos.right !== null) { + if (currPos.right.deleted === false) { + switch (currPos.right.content.constructor) { + case ContentEmbed: + case ContentString: + if (length < currPos.right.length) { + getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length)); + } + length -= currPos.right.length; + currPos.right.delete(transaction); + break + } + } + currPos.forward(); + } + if (start) { + cleanupFormattingGap(transaction, start, currPos.right, startAttrs, copy(currPos.currentAttributes)); + } + const parent = /** @type {AbstractType} */ (/** @type {Item} */ (currPos.left || currPos.right).parent); + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length); + } + return currPos + }; + + /** + * The Quill Delta format represents changes on a text document with + * formatting information. For mor information visit {@link https://quilljs.com/docs/delta/|Quill Delta} + * + * @example + * { + * ops: [ + * { insert: 'Gandalf', attributes: { bold: true } }, + * { insert: ' the ' }, + * { insert: 'Grey', attributes: { color: '#cccccc' } } + * ] + * } + * + */ + + /** + * Attributes that can be assigned to a selection of text. + * + * @example + * { + * bold: true, + * font-size: '40px' + * } + * + * @typedef {Object} TextAttributes + */ + + /** + * @typedef {Object} DeltaItem + * @property {number|undefined} DeltaItem.delete + * @property {number|undefined} DeltaItem.retain + * @property {string|undefined} DeltaItem.insert + * @property {Object} DeltaItem.attributes + */ + + /** + * Event that describes the changes on a YText type. + */ + class YTextEvent extends YEvent { + /** + * @param {YText} ytext + * @param {Transaction} transaction + */ + constructor (ytext, transaction) { + super(ytext, transaction); + /** + * @type {Array|null} + */ + this._delta = null; + } + + /** + * Compute the changes in the delta format. + * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document. + * + * @type {Array} + * + * @public + */ + get delta () { + if (this._delta === null) { + const y = /** @type {Doc} */ (this.target.doc); + this._delta = []; + transact(y, transaction => { + const delta = /** @type {Array} */ (this._delta); + const currentAttributes = new Map(); // saves all current attributes for insert + const oldAttributes = new Map(); + let item = this.target._start; + /** + * @type {string?} + */ + let action = null; + /** + * @type {Object} + */ + const attributes = {}; // counts added or removed new attributes for retain + /** + * @type {string|object} + */ + let insert = ''; + let retain = 0; + let deleteLen = 0; + const addOp = () => { + if (action !== null) { + /** + * @type {any} + */ + let op; + switch (action) { + case 'delete': + op = { delete: deleteLen }; + deleteLen = 0; + break + case 'insert': + op = { insert }; + if (currentAttributes.size > 0) { + op.attributes = {}; + currentAttributes.forEach((value, key) => { + if (value !== null) { + op.attributes[key] = value; + } + }); + } + insert = ''; + break + case 'retain': + op = { retain }; + if (Object.keys(attributes).length > 0) { + op.attributes = {}; + for (const key in attributes) { + op.attributes[key] = attributes[key]; + } + } + retain = 0; + break + } + delta.push(op); + action = null; + } + }; + while (item !== null) { + switch (item.content.constructor) { + case ContentEmbed: + if (this.adds(item)) { + if (!this.deletes(item)) { + addOp(); + action = 'insert'; + insert = /** @type {ContentEmbed} */ (item.content).embed; + addOp(); + } + } else if (this.deletes(item)) { + if (action !== 'delete') { + addOp(); + action = 'delete'; + } + deleteLen += 1; + } else if (!item.deleted) { + if (action !== 'retain') { + addOp(); + action = 'retain'; + } + retain += 1; + } + break + case ContentString: + if (this.adds(item)) { + if (!this.deletes(item)) { + if (action !== 'insert') { + addOp(); + action = 'insert'; + } + insert += /** @type {ContentString} */ (item.content).str; + } + } else if (this.deletes(item)) { + if (action !== 'delete') { + addOp(); + action = 'delete'; + } + deleteLen += item.length; + } else if (!item.deleted) { + if (action !== 'retain') { + addOp(); + action = 'retain'; + } + retain += item.length; + } + break + case ContentFormat: { + const { key, value } = /** @type {ContentFormat} */ (item.content); + if (this.adds(item)) { + if (!this.deletes(item)) { + const curVal = currentAttributes.get(key) || null; + if (!equalAttrs(curVal, value)) { + if (action === 'retain') { + addOp(); + } + if (equalAttrs(value, (oldAttributes.get(key) || null))) { + delete attributes[key]; + } else { + attributes[key] = value; + } + } else { + item.delete(transaction); + } + } + } else if (this.deletes(item)) { + oldAttributes.set(key, value); + const curVal = currentAttributes.get(key) || null; + if (!equalAttrs(curVal, value)) { + if (action === 'retain') { + addOp(); + } + attributes[key] = curVal; + } + } else if (!item.deleted) { + oldAttributes.set(key, value); + const attr = attributes[key]; + if (attr !== undefined) { + if (!equalAttrs(attr, value)) { + if (action === 'retain') { + addOp(); + } + if (value === null) { + attributes[key] = value; + } else { + delete attributes[key]; + } + } else { + item.delete(transaction); + } + } + } + if (!item.deleted) { + if (action === 'insert') { + addOp(); + } + updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (item.content)); + } + break + } + } + item = item.right; + } + addOp(); + while (delta.length > 0) { + const lastOp = delta[delta.length - 1]; + if (lastOp.retain !== undefined && lastOp.attributes === undefined) { + // retain delta's if they don't assign attributes + delta.pop(); + } else { + break + } + } + }); + } + return this._delta + } + } + + /** + * Type that represents text with formatting information. + * + * This type replaces y-richtext as this implementation is able to handle + * block formats (format information on a paragraph), embeds (complex elements + * like pictures and videos), and text formats (**bold**, *italic*). + * + * @extends AbstractType + */ + class YText extends AbstractType { + /** + * @param {String} [string] The initial value of the YText. + */ + constructor (string) { + super(); + /** + * Array of pending operations on this type + * @type {Array?} + */ + this._pending = string !== undefined ? [() => this.insert(0, string)] : []; + /** + * @type {Array} + */ + this._searchMarker = []; + } + + /** + * Number of characters of this text type. + * + * @type {number} + */ + get length () { + return this._length + } + + /** + * @param {Doc} y + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item); + try { + /** @type {Array} */ (this._pending).forEach(f => f()); + } catch (e) { + console.error(e); + } + this._pending = null; + } + + _copy () { + return new YText() + } + + /** + * Creates YTextEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + super._callObserver(transaction, parentSubs); + const event = new YTextEvent(this, transaction); + const doc = transaction.doc; + // If a remote change happened, we try to cleanup potential formatting duplicates. + if (!transaction.local) { + // check if another formatting item was inserted + let foundFormattingItem = false; + for (const [client, afterClock] of transaction.afterState.entries()) { + const clock = transaction.beforeState.get(client) || 0; + if (afterClock === clock) { + continue + } + iterateStructs(transaction, /** @type {Array} */ (doc.store.clients.get(client)), clock, afterClock, item => { + if (!item.deleted && /** @type {Item} */ (item).content.constructor === ContentFormat) { + foundFormattingItem = true; + } + }); + if (foundFormattingItem) { + break + } + } + if (!foundFormattingItem) { + iterateDeletedStructs(transaction, transaction.deleteSet, item => { + if (item instanceof GC || foundFormattingItem) { + return + } + if (item.parent === this && item.content.constructor === ContentFormat) { + foundFormattingItem = true; + } + }); + } + transact(doc, (t) => { + if (foundFormattingItem) { + // If a formatting item was inserted, we simply clean the whole type. + // We need to compute currentAttributes for the current position anyway. + cleanupYTextFormatting(this); + } else { + // If no formatting attribute was inserted, we can make due with contextless + // formatting cleanups. + // Contextless: it is not necessary to compute currentAttributes for the affected position. + iterateDeletedStructs(t, t.deleteSet, item => { + if (item instanceof GC) { + return + } + if (item.parent === this) { + cleanupContextlessFormattingGap(t, item); + } + }); + } + }); + } + callTypeObservers(this, transaction, event); + } + + /** + * Returns the unformatted string representation of this YText type. + * + * @public + */ + toString () { + let str = ''; + /** + * @type {Item|null} + */ + let n = this._start; + while (n !== null) { + if (!n.deleted && n.countable && n.content.constructor === ContentString) { + str += /** @type {ContentString} */ (n.content).str; + } + n = n.right; + } + return str + } + + /** + * Returns the unformatted string representation of this YText type. + * + * @return {string} + * @public + */ + toJSON () { + return this.toString() + } + + /** + * Apply a {@link Delta} on this shared YText type. + * + * @param {any} delta The changes to apply on this element. + * @param {object} [opts] + * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true. + * + * + * @public + */ + applyDelta (delta, { sanitize = true } = {}) { + if (this.doc !== null) { + transact(this.doc, transaction => { + const currPos = new ItemTextListPosition(null, this._start, 0, new Map()); + for (let i = 0; i < delta.length; i++) { + const op = delta[i]; + if (op.insert !== undefined) { + // Quill assumes that the content starts with an empty paragraph. + // Yjs/Y.Text assumes that it starts empty. We always hide that + // there is a newline at the end of the content. + // If we omit this step, clients will see a different number of + // paragraphs, but nothing bad will happen. + const ins = (!sanitize && typeof op.insert === 'string' && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === '\n') ? op.insert.slice(0, -1) : op.insert; + if (typeof ins !== 'string' || ins.length > 0) { + insertText(transaction, this, currPos, ins, op.attributes || {}); + } + } else if (op.retain !== undefined) { + formatText(transaction, this, currPos, op.retain, op.attributes || {}); + } else if (op.delete !== undefined) { + deleteText(transaction, currPos, op.delete); + } + } + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.applyDelta(delta)); + } + } + + /** + * Returns the Delta representation of this YText type. + * + * @param {Snapshot} [snapshot] + * @param {Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', ID):any} [computeYChange] + * @return {any} The Delta representation of this type. + * + * @public + */ + toDelta (snapshot, prevSnapshot, computeYChange) { + /** + * @type{Array} + */ + const ops = []; + const currentAttributes = new Map(); + const doc = /** @type {Doc} */ (this.doc); + let str = ''; + let n = this._start; + function packStr () { + if (str.length > 0) { + // pack str with attributes to ops + /** + * @type {Object} + */ + const attributes = {}; + let addAttributes = false; + currentAttributes.forEach((value, key) => { + addAttributes = true; + attributes[key] = value; + }); + /** + * @type {Object} + */ + const op = { insert: str }; + if (addAttributes) { + op.attributes = attributes; + } + ops.push(op); + str = ''; + } + } + // snapshots are merged again after the transaction, so we need to keep the + // transalive until we are done + transact(doc, transaction => { + if (snapshot) { + splitSnapshotAffectedStructs(transaction, snapshot); + } + if (prevSnapshot) { + splitSnapshotAffectedStructs(transaction, prevSnapshot); + } + while (n !== null) { + if (isVisible(n, snapshot) || (prevSnapshot !== undefined && isVisible(n, prevSnapshot))) { + switch (n.content.constructor) { + case ContentString: { + const cur = currentAttributes.get('ychange'); + if (snapshot !== undefined && !isVisible(n, snapshot)) { + if (cur === undefined || cur.user !== n.id.client || cur.state !== 'removed') { + packStr(); + currentAttributes.set('ychange', computeYChange ? computeYChange('removed', n.id) : { type: 'removed' }); + } + } else if (prevSnapshot !== undefined && !isVisible(n, prevSnapshot)) { + if (cur === undefined || cur.user !== n.id.client || cur.state !== 'added') { + packStr(); + currentAttributes.set('ychange', computeYChange ? computeYChange('added', n.id) : { type: 'added' }); + } + } else if (cur !== undefined) { + packStr(); + currentAttributes.delete('ychange'); + } + str += /** @type {ContentString} */ (n.content).str; + break + } + case ContentEmbed: { + packStr(); + /** + * @type {Object} + */ + const op = { + insert: /** @type {ContentEmbed} */ (n.content).embed + }; + if (currentAttributes.size > 0) { + const attrs = /** @type {Object} */ ({}); + op.attributes = attrs; + currentAttributes.forEach((value, key) => { + attrs[key] = value; + }); + } + ops.push(op); + break + } + case ContentFormat: + if (isVisible(n, snapshot)) { + packStr(); + updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (n.content)); + } + break + } + } + n = n.right; + } + packStr(); + }, splitSnapshotAffectedStructs); + return ops + } + + /** + * Insert text at a given index. + * + * @param {number} index The index at which to start inserting. + * @param {String} text The text to insert at the specified position. + * @param {TextAttributes} [attributes] Optionally define some formatting + * information to apply on the inserted + * Text. + * @public + */ + insert (index, text, attributes) { + if (text.length <= 0) { + return + } + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + const pos = findPosition(transaction, this, index); + if (!attributes) { + attributes = {}; + // @ts-ignore + pos.currentAttributes.forEach((v, k) => { attributes[k] = v; }); + } + insertText(transaction, this, pos, text, attributes); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.insert(index, text, attributes)); + } + } + + /** + * Inserts an embed at a index. + * + * @param {number} index The index to insert the embed at. + * @param {Object} embed The Object that represents the embed. + * @param {TextAttributes} attributes Attribute information to apply on the + * embed + * + * @public + */ + insertEmbed (index, embed, attributes = {}) { + if (embed.constructor !== Object) { + throw new Error('Embed must be an Object') + } + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + const pos = findPosition(transaction, this, index); + insertText(transaction, this, pos, embed, attributes); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.insertEmbed(index, embed, attributes)); + } + } + + /** + * Deletes text starting from an index. + * + * @param {number} index Index at which to start deleting. + * @param {number} length The number of characters to remove. Defaults to 1. + * + * @public + */ + delete (index, length) { + if (length === 0) { + return + } + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + deleteText(transaction, findPosition(transaction, this, index), length); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.delete(index, length)); + } + } + + /** + * Assigns properties to a range of text. + * + * @param {number} index The position where to start formatting. + * @param {number} length The amount of characters to assign properties to. + * @param {TextAttributes} attributes Attribute information to apply on the + * text. + * + * @public + */ + format (index, length, attributes) { + if (length === 0) { + return + } + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + const pos = findPosition(transaction, this, index); + if (pos.right === null) { + return + } + formatText(transaction, this, pos, length, attributes); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.format(index, length, attributes)); + } + } + + /** + * @param {AbstractUpdateEncoder} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YTextRefID); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {YText} + * + * @private + * @function + */ + const readYText = decoder => new YText(); + + /** + * @module YXml + */ + + /** + * Define the elements to which a set of CSS queries apply. + * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors|CSS_Selectors} + * + * @example + * query = '.classSelector' + * query = 'nodeSelector' + * query = '#idSelector' + * + * @typedef {string} CSS_Selector + */ + + /** + * Dom filter function. + * + * @callback domFilter + * @param {string} nodeName The nodeName of the element + * @param {Map} attributes The map of attributes. + * @return {boolean} Whether to include the Dom node in the YXmlElement. + */ + + /** + * Represents a subset of the nodes of a YXmlElement / YXmlFragment and a + * position within them. + * + * Can be created with {@link YXmlFragment#createTreeWalker} + * + * @public + * @implements {Iterable} + */ + class YXmlTreeWalker { + /** + * @param {YXmlFragment | YXmlElement} root + * @param {function(AbstractType):boolean} [f] + */ + constructor (root, f = () => true) { + this._filter = f; + this._root = root; + /** + * @type {Item} + */ + this._currentNode = /** @type {Item} */ (root._start); + this._firstCall = true; + } + + [Symbol.iterator] () { + return this + } + + /** + * Get the next node. + * + * @return {IteratorResult} The next node. + * + * @public + */ + next () { + /** + * @type {Item|null} + */ + let n = this._currentNode; + let type = /** @type {any} */ (n.content).type; + if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { // if first call, we check if we can use the first item + do { + type = /** @type {any} */ (n.content).type; + if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) { + // walk down in the tree + n = type._start; + } else { + // walk right or up in the tree + while (n !== null) { + if (n.right !== null) { + n = n.right; + break + } else if (n.parent === this._root) { + n = null; + } else { + n = /** @type {AbstractType} */ (n.parent)._item; + } + } + } + } while (n !== null && (n.deleted || !this._filter(/** @type {ContentType} */ (n.content).type))) + } + this._firstCall = false; + if (n === null) { + // @ts-ignore + return { value: undefined, done: true } + } + this._currentNode = n; + return { value: /** @type {any} */ (n.content).type, done: false } + } + } + + /** + * Represents a list of {@link YXmlElement}.and {@link YXmlText} types. + * A YxmlFragment is similar to a {@link YXmlElement}, but it does not have a + * nodeName and it does not have attributes. Though it can be bound to a DOM + * element - in this case the attributes and the nodeName are not shared. + * + * @public + * @extends AbstractType + */ + class YXmlFragment extends AbstractType { + constructor () { + super(); + /** + * @type {Array|null} + */ + this._prelimContent = []; + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item); + this.insert(0, /** @type {Array} */ (this._prelimContent)); + this._prelimContent = null; + } + + _copy () { + return new YXmlFragment() + } + + get length () { + return this._prelimContent === null ? this._length : this._prelimContent.length + } + + /** + * Create a subtree of childNodes. + * + * @example + * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div') + * for (let node in walker) { + * // `node` is a div node + * nop(node) + * } + * + * @param {function(AbstractType):boolean} filter Function that is called on each child element and + * returns a Boolean indicating whether the child + * is to be included in the subtree. + * @return {YXmlTreeWalker} A subtree and a position within it. + * + * @public + */ + createTreeWalker (filter) { + return new YXmlTreeWalker(this, filter) + } + + /** + * Returns the first YXmlElement that matches the query. + * Similar to DOM's {@link querySelector}. + * + * Query support: + * - tagname + * TODO: + * - id + * - attribute + * + * @param {CSS_Selector} query The query on the children. + * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null. + * + * @public + */ + querySelector (query) { + query = query.toUpperCase(); + // @ts-ignore + const iterator = new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query); + const next = iterator.next(); + if (next.done) { + return null + } else { + return next.value + } + } + + /** + * Returns all YXmlElements that match the query. + * Similar to Dom's {@link querySelectorAll}. + * + * @todo Does not yet support all queries. Currently only query by tagName. + * + * @param {CSS_Selector} query The query on the children + * @return {Array} The elements that match this query. + * + * @public + */ + querySelectorAll (query) { + query = query.toUpperCase(); + // @ts-ignore + return Array.from(new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query)) + } + + /** + * Creates YXmlEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction)); + } + + /** + * Get the string representation of all the children of this YXmlFragment. + * + * @return {string} The string representation of all children. + */ + toString () { + return typeListMap(this, xml => xml.toString()).join('') + } + + /** + * @return {string} + */ + toJSON () { + return this.toString() + } + + /** + * Creates a Dom Element that mirrors this YXmlElement. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object} [hooks={}] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type. + * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks = {}, binding) { + const fragment = _document.createDocumentFragment(); + if (binding !== undefined) { + binding._createAssociation(fragment, this); + } + typeListForEach(this, xmlType => { + fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null); + }); + return fragment + } + + /** + * Inserts new content at an index. + * + * @example + * // Insert character 'a' at position 0 + * xml.insert(0, [new Y.XmlText('text')]) + * + * @param {number} index The index to insert content at + * @param {Array} content The array of content + */ + insert (index, content) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListInsertGenerics(transaction, this, index, content); + }); + } else { + // @ts-ignore _prelimContent is defined because this is not yet integrated + this._prelimContent.splice(index, 0, ...content); + } + } + + /** + * Deletes elements starting from an index. + * + * @param {number} index Index at which to start deleting elements + * @param {number} [length=1] The number of elements to remove. Defaults to 1. + */ + delete (index, length = 1) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListDelete(transaction, this, index, length); + }); + } else { + // @ts-ignore _prelimContent is defined because this is not yet integrated + this._prelimContent.splice(index, length); + } + } + + /** + * Transforms this YArray to a JavaScript Array. + * + * @return {Array} + */ + toArray () { + return typeListToArray(this) + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {AbstractUpdateEncoder} encoder The encoder to write data to. + */ + _write (encoder) { + encoder.writeTypeRef(YXmlFragmentRefID); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {YXmlFragment} + * + * @private + * @function + */ + const readYXmlFragment = decoder => new YXmlFragment(); + + /** + * An YXmlElement imitates the behavior of a + * {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}. + * + * * An YXmlElement has attributes (key value pairs) + * * An YXmlElement has childElements that must inherit from YXmlElement + */ + class YXmlElement extends YXmlFragment { + constructor (nodeName = 'UNDEFINED') { + super(); + this.nodeName = nodeName; + /** + * @type {Map|null} + */ + this._prelimAttrs = new Map(); + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item) + ;(/** @type {Map} */ (this._prelimAttrs)).forEach((value, key) => { + this.setAttribute(key, value); + }); + this._prelimAttrs = null; + } + + /** + * Creates an Item with the same effect as this Item (without position effect) + * + * @return {YXmlElement} + */ + _copy () { + return new YXmlElement(this.nodeName) + } + + /** + * Returns the XML serialization of this YXmlElement. + * The attributes are ordered by attribute-name, so you can easily use this + * method to compare YXmlElements + * + * @return {string} The string representation of this type. + * + * @public + */ + toString () { + const attrs = this.getAttributes(); + const stringBuilder = []; + const keys = []; + for (const key in attrs) { + keys.push(key); + } + keys.sort(); + const keysLen = keys.length; + for (let i = 0; i < keysLen; i++) { + const key = keys[i]; + stringBuilder.push(key + '="' + attrs[key] + '"'); + } + const nodeName = this.nodeName.toLocaleLowerCase(); + const attrsString = stringBuilder.length > 0 ? ' ' + stringBuilder.join(' ') : ''; + return `<${nodeName}${attrsString}>${super.toString()}` + } + + /** + * Removes an attribute from this YXmlElement. + * + * @param {String} attributeName The attribute name that is to be removed. + * + * @public + */ + removeAttribute (attributeName) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapDelete(transaction, this, attributeName); + }); + } else { + /** @type {Map} */ (this._prelimAttrs).delete(attributeName); + } + } + + /** + * Sets or updates an attribute. + * + * @param {String} attributeName The attribute name that is to be set. + * @param {String} attributeValue The attribute value that is to be set. + * + * @public + */ + setAttribute (attributeName, attributeValue) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapSet(transaction, this, attributeName, attributeValue); + }); + } else { + /** @type {Map} */ (this._prelimAttrs).set(attributeName, attributeValue); + } + } + + /** + * Returns an attribute value that belongs to the attribute name. + * + * @param {String} attributeName The attribute name that identifies the + * queried value. + * @return {String} The queried attribute value. + * + * @public + */ + getAttribute (attributeName) { + return /** @type {any} */ (typeMapGet(this, attributeName)) + } + + /** + * Returns all attribute name/value pairs in a JSON Object. + * + * @param {Snapshot} [snapshot] + * @return {Object} A JSON Object that describes the attributes. + * + * @public + */ + getAttributes (snapshot) { + return typeMapGetAll(this) + } + + /** + * Creates a Dom Element that mirrors this YXmlElement. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object} [hooks={}] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type. + * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks = {}, binding) { + const dom = _document.createElement(this.nodeName); + const attrs = this.getAttributes(); + for (const key in attrs) { + dom.setAttribute(key, attrs[key]); + } + typeListForEach(this, yxml => { + dom.appendChild(yxml.toDOM(_document, hooks, binding)); + }); + if (binding !== undefined) { + binding._createAssociation(dom, this); + } + return dom + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {AbstractUpdateEncoder} encoder The encoder to write data to. + */ + _write (encoder) { + encoder.writeTypeRef(YXmlElementRefID); + encoder.writeKey(this.nodeName); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {YXmlElement} + * + * @function + */ + const readYXmlElement = decoder => new YXmlElement(decoder.readKey()); + + /** + * An Event that describes changes on a YXml Element or Yxml Fragment + */ + class YXmlEvent extends YEvent { + /** + * @param {YXmlElement|YXmlFragment} target The target on which the event is created. + * @param {Set} subs The set of changed attributes. `null` is included if the + * child list changed. + * @param {Transaction} transaction The transaction instance with wich the + * change was created. + */ + constructor (target, subs, transaction) { + super(target, transaction); + /** + * Whether the children changed. + * @type {Boolean} + * @private + */ + this.childListChanged = false; + /** + * Set of all changed attributes. + * @type {Set} + */ + this.attributesChanged = new Set(); + subs.forEach((sub) => { + if (sub === null) { + this.childListChanged = true; + } else { + this.attributesChanged.add(sub); + } + }); + } + } + + /** + * You can manage binding to a custom type with YXmlHook. + * + * @extends {YMap} + */ + class YXmlHook extends YMap { + /** + * @param {string} hookName nodeName of the Dom Node. + */ + constructor (hookName) { + super(); + /** + * @type {string} + */ + this.hookName = hookName; + } + + /** + * Creates an Item with the same effect as this Item (without position effect) + */ + _copy () { + return new YXmlHook(this.hookName) + } + + /** + * Creates a Dom Element that mirrors this YXmlElement. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object.} [hooks] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type + * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks = {}, binding) { + const hook = hooks[this.hookName]; + let dom; + if (hook !== undefined) { + dom = hook.createDom(this); + } else { + dom = document.createElement(this.hookName); + } + dom.setAttribute('data-yjs-hook', this.hookName); + if (binding !== undefined) { + binding._createAssociation(dom, this); + } + return dom + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {AbstractUpdateEncoder} encoder The encoder to write data to. + */ + _write (encoder) { + encoder.writeTypeRef(YXmlHookRefID); + encoder.writeKey(this.hookName); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {YXmlHook} + * + * @private + * @function + */ + const readYXmlHook = decoder => + new YXmlHook(decoder.readKey()); + + /** + * Represents text in a Dom Element. In the future this type will also handle + * simple formatting information like bold and italic. + */ + class YXmlText extends YText { + _copy () { + return new YXmlText() + } + + /** + * Creates a Dom Element that mirrors this YXmlText. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object} [hooks] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type. + * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks, binding) { + const dom = _document.createTextNode(this.toString()); + if (binding !== undefined) { + binding._createAssociation(dom, this); + } + return dom + } + + toString () { + // @ts-ignore + return this.toDelta().map(delta => { + const nestedNodes = []; + for (const nodeName in delta.attributes) { + const attrs = []; + for (const key in delta.attributes[nodeName]) { + attrs.push({ key, value: delta.attributes[nodeName][key] }); + } + // sort attributes to get a unique order + attrs.sort((a, b) => a.key < b.key ? -1 : 1); + nestedNodes.push({ nodeName, attrs }); + } + // sort node order to get a unique order + nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1); + // now convert to dom string + let str = ''; + for (let i = 0; i < nestedNodes.length; i++) { + const node = nestedNodes[i]; + str += `<${node.nodeName}`; + for (let j = 0; j < node.attrs.length; j++) { + const attr = node.attrs[j]; + str += ` ${attr.key}="${attr.value}"`; + } + str += '>'; + } + str += delta.insert; + for (let i = nestedNodes.length - 1; i >= 0; i--) { + str += ``; + } + return str + }).join('') + } + + /** + * @return {string} + */ + toJSON () { + return this.toString() + } + + /** + * @param {AbstractUpdateEncoder} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YXmlTextRefID); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {YXmlText} + * + * @private + * @function + */ + const readYXmlText = decoder => new YXmlText(); + + class AbstractStruct { + /** + * @param {ID} id + * @param {number} length + */ + constructor (id, length) { + this.id = id; + this.length = length; + } + + /** + * @type {boolean} + */ + get deleted () { + throw methodUnimplemented() + } + + /** + * Merge this struct with the item to the right. + * This method is already assuming that `this.id.clock + this.length === this.id.clock`. + * Also this method does *not* remove right from StructStore! + * @param {AbstractStruct} right + * @return {boolean} wether this merged with right + */ + mergeWith (right) { + return false + } + + /** + * @param {AbstractUpdateEncoder} encoder The encoder to write data to. + * @param {number} offset + * @param {number} encodingRef + */ + write (encoder, offset, encodingRef) { + throw methodUnimplemented() + } + + /** + * @param {Transaction} transaction + * @param {number} offset + */ + integrate (transaction, offset) { + throw methodUnimplemented() + } + } + + const structGCRefNumber = 0; + + /** + * @private + */ + class GC extends AbstractStruct { + get deleted () { + return true + } + + delete () {} + + /** + * @param {GC} right + * @return {boolean} + */ + mergeWith (right) { + this.length += right.length; + return true + } + + /** + * @param {Transaction} transaction + * @param {number} offset + */ + integrate (transaction, offset) { + if (offset > 0) { + this.id.clock += offset; + this.length -= offset; + } + addStruct(transaction.doc.store, this); + } + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeInfo(structGCRefNumber); + encoder.writeLen(this.length - offset); + } + + /** + * @param {Transaction} transaction + * @param {StructStore} store + * @return {null | number} + */ + getMissing (transaction, store) { + return null + } + } + + class ContentBinary { + /** + * @param {Uint8Array} content + */ + constructor (content) { + this.content = content; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.content] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentBinary} + */ + copy () { + return new ContentBinary(this.content) + } + + /** + * @param {number} offset + * @return {ContentBinary} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {ContentBinary} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeBuf(this.content); + } + + /** + * @return {number} + */ + getRef () { + return 3 + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {ContentBinary} + */ + const readContentBinary = decoder => new ContentBinary(decoder.readBuf()); + + class ContentDeleted { + /** + * @param {number} len + */ + constructor (len) { + this.len = len; + } + + /** + * @return {number} + */ + getLength () { + return this.len + } + + /** + * @return {Array} + */ + getContent () { + return [] + } + + /** + * @return {boolean} + */ + isCountable () { + return false + } + + /** + * @return {ContentDeleted} + */ + copy () { + return new ContentDeleted(this.len) + } + + /** + * @param {number} offset + * @return {ContentDeleted} + */ + splice (offset) { + const right = new ContentDeleted(this.len - offset); + this.len = offset; + return right + } + + /** + * @param {ContentDeleted} right + * @return {boolean} + */ + mergeWith (right) { + this.len += right.len; + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len); + item.markDeleted(); + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeLen(this.len - offset); + } + + /** + * @return {number} + */ + getRef () { + return 1 + } + } + + /** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentDeleted} + */ + const readContentDeleted = decoder => new ContentDeleted(decoder.readLen()); + + /** + * @private + */ + class ContentDoc { + /** + * @param {Doc} doc + */ + constructor (doc) { + if (doc._item) { + console.error('This document was already integrated as a sub-document. You should create a second instance instead with the same guid.'); + } + /** + * @type {Doc} + */ + this.doc = doc; + /** + * @type {any} + */ + const opts = {}; + this.opts = opts; + if (!doc.gc) { + opts.gc = false; + } + if (doc.autoLoad) { + opts.autoLoad = true; + } + if (doc.meta !== null) { + opts.meta = doc.meta; + } + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.doc] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentDoc} + */ + copy () { + return new ContentDoc(this.doc) + } + + /** + * @param {number} offset + * @return {ContentDoc} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {ContentDoc} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + // this needs to be reflected in doc.destroy as well + this.doc._item = item; + transaction.subdocsAdded.add(this.doc); + if (this.doc.shouldLoad) { + transaction.subdocsLoaded.add(this.doc); + } + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) { + if (transaction.subdocsAdded.has(this.doc)) { + transaction.subdocsAdded.delete(this.doc); + } else { + transaction.subdocsRemoved.add(this.doc); + } + } + + /** + * @param {StructStore} store + */ + gc (store) { } + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeString(this.doc.guid); + encoder.writeAny(this.opts); + } + + /** + * @return {number} + */ + getRef () { + return 9 + } + } + + /** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentDoc} + */ + const readContentDoc = decoder => new ContentDoc(new Doc({ guid: decoder.readString(), ...decoder.readAny() })); + + /** + * @private + */ + class ContentEmbed { + /** + * @param {Object} embed + */ + constructor (embed) { + this.embed = embed; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.embed] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentEmbed} + */ + copy () { + return new ContentEmbed(this.embed) + } + + /** + * @param {number} offset + * @return {ContentEmbed} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {ContentEmbed} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeJSON(this.embed); + } + + /** + * @return {number} + */ + getRef () { + return 5 + } + } + + /** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentEmbed} + */ + const readContentEmbed = decoder => new ContentEmbed(decoder.readJSON()); + + /** + * @private + */ + class ContentFormat { + /** + * @param {string} key + * @param {Object} value + */ + constructor (key, value) { + this.key = key; + this.value = value; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [] + } + + /** + * @return {boolean} + */ + isCountable () { + return false + } + + /** + * @return {ContentFormat} + */ + copy () { + return new ContentFormat(this.key, this.value) + } + + /** + * @param {number} offset + * @return {ContentFormat} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {ContentFormat} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + // @todo searchmarker are currently unsupported for rich text documents + /** @type {AbstractType} */ (item.parent)._searchMarker = null; + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeKey(this.key); + encoder.writeJSON(this.value); + } + + /** + * @return {number} + */ + getRef () { + return 6 + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {ContentFormat} + */ + const readContentFormat = decoder => new ContentFormat(decoder.readString(), decoder.readJSON()); + + /** + * @private + */ + class ContentJSON { + /** + * @param {Array} arr + */ + constructor (arr) { + /** + * @type {Array} + */ + this.arr = arr; + } + + /** + * @return {number} + */ + getLength () { + return this.arr.length + } + + /** + * @return {Array} + */ + getContent () { + return this.arr + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentJSON} + */ + copy () { + return new ContentJSON(this.arr) + } + + /** + * @param {number} offset + * @return {ContentJSON} + */ + splice (offset) { + const right = new ContentJSON(this.arr.slice(offset)); + this.arr = this.arr.slice(0, offset); + return right + } + + /** + * @param {ContentJSON} right + * @return {boolean} + */ + mergeWith (right) { + this.arr = this.arr.concat(right.arr); + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + const len = this.arr.length; + encoder.writeLen(len - offset); + for (let i = offset; i < len; i++) { + const c = this.arr[i]; + encoder.writeString(c === undefined ? 'undefined' : JSON.stringify(c)); + } + } + + /** + * @return {number} + */ + getRef () { + return 2 + } + } + + /** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentJSON} + */ + const readContentJSON = decoder => { + const len = decoder.readLen(); + const cs = []; + for (let i = 0; i < len; i++) { + const c = decoder.readString(); + if (c === 'undefined') { + cs.push(undefined); + } else { + cs.push(JSON.parse(c)); + } + } + return new ContentJSON(cs) + }; + + class ContentAny { + /** + * @param {Array} arr + */ + constructor (arr) { + /** + * @type {Array} + */ + this.arr = arr; + } + + /** + * @return {number} + */ + getLength () { + return this.arr.length + } + + /** + * @return {Array} + */ + getContent () { + return this.arr + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentAny} + */ + copy () { + return new ContentAny(this.arr) + } + + /** + * @param {number} offset + * @return {ContentAny} + */ + splice (offset) { + const right = new ContentAny(this.arr.slice(offset)); + this.arr = this.arr.slice(0, offset); + return right + } + + /** + * @param {ContentAny} right + * @return {boolean} + */ + mergeWith (right) { + this.arr = this.arr.concat(right.arr); + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + const len = this.arr.length; + encoder.writeLen(len - offset); + for (let i = offset; i < len; i++) { + const c = this.arr[i]; + encoder.writeAny(c); + } + } + + /** + * @return {number} + */ + getRef () { + return 8 + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @return {ContentAny} + */ + const readContentAny = decoder => { + const len = decoder.readLen(); + const cs = []; + for (let i = 0; i < len; i++) { + cs.push(decoder.readAny()); + } + return new ContentAny(cs) + }; + + /** + * @private + */ + class ContentString { + /** + * @param {string} str + */ + constructor (str) { + /** + * @type {string} + */ + this.str = str; + } + + /** + * @return {number} + */ + getLength () { + return this.str.length + } + + /** + * @return {Array} + */ + getContent () { + return this.str.split('') + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentString} + */ + copy () { + return new ContentString(this.str) + } + + /** + * @param {number} offset + * @return {ContentString} + */ + splice (offset) { + const right = new ContentString(this.str.slice(offset)); + this.str = this.str.slice(0, offset); + + // Prevent encoding invalid documents because of splitting of surrogate pairs: https://github.com/yjs/yjs/issues/248 + const firstCharCode = this.str.charCodeAt(offset - 1); + if (firstCharCode >= 0xD800 && firstCharCode <= 0xDBFF) { + // Last character of the left split is the start of a surrogate utf16/ucs2 pair. + // We don't support splitting of surrogate pairs because this may lead to invalid documents. + // Replace the invalid character with a unicode replacement character (� / U+FFFD) + this.str = this.str.slice(0, offset - 1) + '�'; + // replace right as well + right.str = '�' + right.str.slice(1); + } + return right + } + + /** + * @param {ContentString} right + * @return {boolean} + */ + mergeWith (right) { + this.str += right.str; + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeString(offset === 0 ? this.str : this.str.slice(offset)); + } + + /** + * @return {number} + */ + getRef () { + return 4 + } + } + + /** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentString} + */ + const readContentString = decoder => new ContentString(decoder.readString()); + + /** + * @type {Array>} + * @private + */ + const typeRefs = [ + readYArray, + readYMap, + readYText, + readYXmlElement, + readYXmlFragment, + readYXmlHook, + readYXmlText + ]; + + const YArrayRefID = 0; + const YMapRefID = 1; + const YTextRefID = 2; + const YXmlElementRefID = 3; + const YXmlFragmentRefID = 4; + const YXmlHookRefID = 5; + const YXmlTextRefID = 6; + + /** + * @private + */ + class ContentType { + /** + * @param {AbstractType} type + */ + constructor (type) { + /** + * @type {AbstractType} + */ + this.type = type; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.type] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentType} + */ + copy () { + return new ContentType(this.type._copy()) + } + + /** + * @param {number} offset + * @return {ContentType} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {ContentType} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + this.type._integrate(transaction.doc, item); + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) { + let item = this.type._start; + while (item !== null) { + if (!item.deleted) { + item.delete(transaction); + } else { + // Whis will be gc'd later and we want to merge it if possible + // We try to merge all deleted items after each transaction, + // but we have no knowledge about that this needs to be merged + // since it is not in transaction.ds. Hence we add it to transaction._mergeStructs + transaction._mergeStructs.push(item); + } + item = item.right; + } + this.type._map.forEach(item => { + if (!item.deleted) { + item.delete(transaction); + } else { + // same as above + transaction._mergeStructs.push(item); + } + }); + transaction.changed.delete(this.type); + } + + /** + * @param {StructStore} store + */ + gc (store) { + let item = this.type._start; + while (item !== null) { + item.gc(store, true); + item = item.right; + } + this.type._start = null; + this.type._map.forEach(/** @param {Item | null} item */ (item) => { + while (item !== null) { + item.gc(store, true); + item = item.left; + } + }); + this.type._map = new Map(); + } + + /** + * @param {AbstractUpdateEncoder} encoder + * @param {number} offset + */ + write (encoder, offset) { + this.type._write(encoder); + } + + /** + * @return {number} + */ + getRef () { + return 7 + } + } + + /** + * @private + * + * @param {AbstractUpdateDecoder} decoder + * @return {ContentType} + */ + const readContentType = decoder => new ContentType(typeRefs[decoder.readTypeRef()](decoder)); + + /** + * @todo This should return several items + * + * @param {StructStore} store + * @param {ID} id + * @return {{item:Item, diff:number}} + */ + const followRedone = (store, id) => { + /** + * @type {ID|null} + */ + let nextID = id; + let diff = 0; + let item; + do { + if (diff > 0) { + nextID = createID(nextID.client, nextID.clock + diff); + } + item = getItem(store, nextID); + diff = nextID.clock - item.id.clock; + nextID = item.redone; + } while (nextID !== null && item instanceof Item) + return { + item, diff + } + }; + + /** + * Make sure that neither item nor any of its parents is ever deleted. + * + * This property does not persist when storing it into a database or when + * sending it to other peers + * + * @param {Item|null} item + * @param {boolean} keep + */ + const keepItem = (item, keep) => { + while (item !== null && item.keep !== keep) { + item.keep = keep; + item = /** @type {AbstractType} */ (item.parent)._item; + } + }; + + /** + * Split leftItem into two items + * @param {Transaction} transaction + * @param {Item} leftItem + * @param {number} diff + * @return {Item} + * + * @function + * @private + */ + const splitItem = (transaction, leftItem, diff) => { + // create rightItem + const { client, clock } = leftItem.id; + const rightItem = new Item( + createID(client, clock + diff), + leftItem, + createID(client, clock + diff - 1), + leftItem.right, + leftItem.rightOrigin, + leftItem.parent, + leftItem.parentSub, + leftItem.content.splice(diff) + ); + if (leftItem.deleted) { + rightItem.markDeleted(); + } + if (leftItem.keep) { + rightItem.keep = true; + } + if (leftItem.redone !== null) { + rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff); + } + // update left (do not set leftItem.rightOrigin as it will lead to problems when syncing) + leftItem.right = rightItem; + // update right + if (rightItem.right !== null) { + rightItem.right.left = rightItem; + } + // right is more specific. + transaction._mergeStructs.push(rightItem); + // update parent._map + if (rightItem.parentSub !== null && rightItem.right === null) { + /** @type {AbstractType} */ (rightItem.parent)._map.set(rightItem.parentSub, rightItem); + } + leftItem.length = diff; + return rightItem + }; + + /** + * Redoes the effect of this operation. + * + * @param {Transaction} transaction The Yjs instance. + * @param {Item} item + * @param {Set} redoitems + * + * @return {Item|null} + * + * @private + */ + const redoItem = (transaction, item, redoitems) => { + const doc = transaction.doc; + const store = doc.store; + const ownClientID = doc.clientID; + const redone = item.redone; + if (redone !== null) { + return getItemCleanStart(transaction, redone) + } + let parentItem = /** @type {AbstractType} */ (item.parent)._item; + /** + * @type {Item|null} + */ + let left; + /** + * @type {Item|null} + */ + let right; + if (item.parentSub === null) { + // Is an array item. Insert at the old position + left = item.left; + right = item; + } else { + // Is a map item. Insert as current value + left = item; + while (left.right !== null) { + left = left.right; + if (left.id.client !== ownClientID) { + // It is not possible to redo this item because it conflicts with a + // change from another client + return null + } + } + if (left.right !== null) { + left = /** @type {Item} */ (/** @type {AbstractType} */ (item.parent)._map.get(item.parentSub)); + } + right = null; + } + // make sure that parent is redone + if (parentItem !== null && parentItem.deleted === true && parentItem.redone === null) { + // try to undo parent if it will be undone anyway + if (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems) === null) { + return null + } + } + if (parentItem !== null && parentItem.redone !== null) { + while (parentItem.redone !== null) { + parentItem = getItemCleanStart(transaction, parentItem.redone); + } + // find next cloned_redo items + while (left !== null) { + /** + * @type {Item|null} + */ + let leftTrace = left; + // trace redone until parent matches + while (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item !== parentItem) { + leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone); + } + if (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item === parentItem) { + left = leftTrace; + break + } + left = left.left; + } + while (right !== null) { + /** + * @type {Item|null} + */ + let rightTrace = right; + // trace redone until parent matches + while (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item !== parentItem) { + rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone); + } + if (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item === parentItem) { + right = rightTrace; + break + } + right = right.right; + } + } + const nextClock = getState(store, ownClientID); + const nextId = createID(ownClientID, nextClock); + const redoneItem = new Item( + nextId, + left, left && left.lastId, + right, right && right.id, + parentItem === null ? item.parent : /** @type {ContentType} */ (parentItem.content).type, + item.parentSub, + item.content.copy() + ); + item.redone = nextId; + keepItem(redoneItem, true); + redoneItem.integrate(transaction, 0); + return redoneItem + }; + + /** + * Abstract class that represents any content. + */ + class Item extends AbstractStruct { + /** + * @param {ID} id + * @param {Item | null} left + * @param {ID | null} origin + * @param {Item | null} right + * @param {ID | null} rightOrigin + * @param {AbstractType|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it. + * @param {string | null} parentSub + * @param {AbstractContent} content + */ + constructor (id, left, origin, right, rightOrigin, parent, parentSub, content) { + super(id, content.getLength()); + /** + * The item that was originally to the left of this item. + * @type {ID | null} + */ + this.origin = origin; + /** + * The item that is currently to the left of this item. + * @type {Item | null} + */ + this.left = left; + /** + * The item that is currently to the right of this item. + * @type {Item | null} + */ + this.right = right; + /** + * The item that was originally to the right of this item. + * @type {ID | null} + */ + this.rightOrigin = rightOrigin; + /** + * @type {AbstractType|ID|null} + */ + this.parent = parent; + /** + * If the parent refers to this item with some kind of key (e.g. YMap, the + * key is specified here. The key is then used to refer to the list in which + * to insert this item. If `parentSub = null` type._start is the list in + * which to insert to. Otherwise it is `parent._map`. + * @type {String | null} + */ + this.parentSub = parentSub; + /** + * If this type's effect is reundone this type refers to the type that undid + * this operation. + * @type {ID | null} + */ + this.redone = null; + /** + * @type {AbstractContent} + */ + this.content = content; + /** + * bit1: keep + * bit2: countable + * bit3: deleted + * bit4: mark - mark node as fast-search-marker + * @type {number} byte + */ + this.info = this.content.isCountable() ? BIT2 : 0; + } + + /** + * This is used to mark the item as an indexed fast-search marker + * + * @type {boolean} + */ + set marker (isMarked) { + if (((this.info & BIT4) > 0) !== isMarked) { + this.info ^= BIT4; + } + } + + get marker () { + return (this.info & BIT4) > 0 + } + + /** + * If true, do not garbage collect this Item. + */ + get keep () { + return (this.info & BIT1) > 0 + } + + set keep (doKeep) { + if (this.keep !== doKeep) { + this.info ^= BIT1; + } + } + + get countable () { + return (this.info & BIT2) > 0 + } + + /** + * Whether this item was deleted or not. + * @type {Boolean} + */ + get deleted () { + return (this.info & BIT3) > 0 + } + + set deleted (doDelete) { + if (this.deleted !== doDelete) { + this.info ^= BIT3; + } + } + + markDeleted () { + this.info |= BIT3; + } + + /** + * Return the creator clientID of the missing op or define missing items and return null. + * + * @param {Transaction} transaction + * @param {StructStore} store + * @return {null | number} + */ + getMissing (transaction, store) { + if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) { + return this.origin.client + } + if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) { + return this.rightOrigin.client + } + if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) { + return this.parent.client + } + + // We have all missing ids, now find the items + + if (this.origin) { + this.left = getItemCleanEnd(transaction, store, this.origin); + this.origin = this.left.lastId; + } + if (this.rightOrigin) { + this.right = getItemCleanStart(transaction, this.rightOrigin); + this.rightOrigin = this.right.id; + } + if ((this.left && this.left.constructor === GC) || (this.right && this.right.constructor === GC)) { + this.parent = null; + } + // only set parent if this shouldn't be garbage collected + if (!this.parent) { + if (this.left && this.left.constructor === Item) { + this.parent = this.left.parent; + this.parentSub = this.left.parentSub; + } + if (this.right && this.right.constructor === Item) { + this.parent = this.right.parent; + this.parentSub = this.right.parentSub; + } + } else if (this.parent.constructor === ID) { + const parentItem = getItem(store, this.parent); + if (parentItem.constructor === GC) { + this.parent = null; + } else { + this.parent = /** @type {ContentType} */ (parentItem.content).type; + } + } + return null + } + + /** + * @param {Transaction} transaction + * @param {number} offset + */ + integrate (transaction, offset) { + if (offset > 0) { + this.id.clock += offset; + this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1)); + this.origin = this.left.lastId; + this.content = this.content.splice(offset); + this.length -= offset; + } + + if (this.parent) { + if ((!this.left && (!this.right || this.right.left !== null)) || (this.left && this.left.right !== this.right)) { + /** + * @type {Item|null} + */ + let left = this.left; + + /** + * @type {Item|null} + */ + let o; + // set o to the first conflicting item + if (left !== null) { + o = left.right; + } else if (this.parentSub !== null) { + o = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null; + while (o !== null && o.left !== null) { + o = o.left; + } + } else { + o = /** @type {AbstractType} */ (this.parent)._start; + } + // TODO: use something like DeleteSet here (a tree implementation would be best) + // @todo use global set definitions + /** + * @type {Set} + */ + const conflictingItems = new Set(); + /** + * @type {Set} + */ + const itemsBeforeOrigin = new Set(); + // Let c in conflictingItems, b in itemsBeforeOrigin + // ***{origin}bbbb{this}{c,b}{c,b}{o}*** + // Note that conflictingItems is a subset of itemsBeforeOrigin + while (o !== null && o !== this.right) { + itemsBeforeOrigin.add(o); + conflictingItems.add(o); + if (compareIDs(this.origin, o.origin)) { + // case 1 + if (o.id.client < this.id.client) { + left = o; + conflictingItems.clear(); + } else if (compareIDs(this.rightOrigin, o.rightOrigin)) { + // this and o are conflicting and point to the same integration points. The id decides which item comes first. + // Since this is to the left of o, we can break here + break + } // else, o might be integrated before an item that this conflicts with. If so, we will find it in the next iterations + } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) { // use getItem instead of getItemCleanEnd because we don't want / need to split items. + // case 2 + if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) { + left = o; + conflictingItems.clear(); + } + } else { + break + } + o = o.right; + } + this.left = left; + } + // reconnect left/right + update parent map/start if necessary + if (this.left !== null) { + const right = this.left.right; + this.right = right; + this.left.right = this; + } else { + let r; + if (this.parentSub !== null) { + r = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null; + while (r !== null && r.left !== null) { + r = r.left; + } + } else { + r = /** @type {AbstractType} */ (this.parent)._start + ;/** @type {AbstractType} */ (this.parent)._start = this; + } + this.right = r; + } + if (this.right !== null) { + this.right.left = this; + } else if (this.parentSub !== null) { + // set as current parent value if right === null and this is parentSub + /** @type {AbstractType} */ (this.parent)._map.set(this.parentSub, this); + if (this.left !== null) { + // this is the current attribute value of parent. delete right + this.left.delete(transaction); + } + } + // adjust length of parent + if (this.parentSub === null && this.countable && !this.deleted) { + /** @type {AbstractType} */ (this.parent)._length += this.length; + } + addStruct(transaction.doc.store, this); + this.content.integrate(transaction, this); + // add parent to transaction.changed + addChangedTypeToTransaction(transaction, /** @type {AbstractType} */ (this.parent), this.parentSub); + if ((/** @type {AbstractType} */ (this.parent)._item !== null && /** @type {AbstractType} */ (this.parent)._item.deleted) || (this.parentSub !== null && this.right !== null)) { + // delete if parent is deleted or if this is not the current attribute value of parent + this.delete(transaction); + } + } else { + // parent is not defined. Integrate GC struct instead + new GC(this.id, this.length).integrate(transaction, 0); + } + } + + /** + * Returns the next non-deleted item + */ + get next () { + let n = this.right; + while (n !== null && n.deleted) { + n = n.right; + } + return n + } + + /** + * Returns the previous non-deleted item + */ + get prev () { + let n = this.left; + while (n !== null && n.deleted) { + n = n.left; + } + return n + } + + /** + * Computes the last content address of this Item. + */ + get lastId () { + // allocating ids is pretty costly because of the amount of ids created, so we try to reuse whenever possible + return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1) + } + + /** + * Try to merge two items + * + * @param {Item} right + * @return {boolean} + */ + mergeWith (right) { + if ( + compareIDs(right.origin, this.lastId) && + this.right === right && + compareIDs(this.rightOrigin, right.rightOrigin) && + this.id.client === right.id.client && + this.id.clock + this.length === right.id.clock && + this.deleted === right.deleted && + this.redone === null && + right.redone === null && + this.content.constructor === right.content.constructor && + this.content.mergeWith(right.content) + ) { + if (right.keep) { + this.keep = true; + } + this.right = right.right; + if (this.right !== null) { + this.right.left = this; + } + this.length += right.length; + return true + } + return false + } + + /** + * Mark this Item as deleted. + * + * @param {Transaction} transaction + */ + delete (transaction) { + if (!this.deleted) { + const parent = /** @type {AbstractType} */ (this.parent); + // adjust the length of parent + if (this.countable && this.parentSub === null) { + parent._length -= this.length; + } + this.markDeleted(); + addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length); + addChangedTypeToTransaction(transaction, parent, this.parentSub); + this.content.delete(transaction); + } + } + + /** + * @param {StructStore} store + * @param {boolean} parentGCd + */ + gc (store, parentGCd) { + if (!this.deleted) { + throw unexpectedCase() + } + this.content.gc(store); + if (parentGCd) { + replaceStruct(store, this, new GC(this.id, this.length)); + } else { + this.content = new ContentDeleted(this.length); + } + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {AbstractUpdateEncoder} encoder The encoder to write data to. + * @param {number} offset + */ + write (encoder, offset) { + const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin; + const rightOrigin = this.rightOrigin; + const parentSub = this.parentSub; + const info = (this.content.getRef() & BITS5) | + (origin === null ? 0 : BIT8) | // origin is defined + (rightOrigin === null ? 0 : BIT7) | // right origin is defined + (parentSub === null ? 0 : BIT6); // parentSub is non-null + encoder.writeInfo(info); + if (origin !== null) { + encoder.writeLeftID(origin); + } + if (rightOrigin !== null) { + encoder.writeRightID(rightOrigin); + } + if (origin === null && rightOrigin === null) { + const parent = /** @type {AbstractType} */ (this.parent); + const parentItem = parent._item; + if (parentItem === null) { + // parent type on y._map + // find the correct key + const ykey = findRootTypeKey(parent); + encoder.writeParentInfo(true); // write parentYKey + encoder.writeString(ykey); + } else { + encoder.writeParentInfo(false); // write parent id + encoder.writeLeftID(parentItem.id); + } + if (parentSub !== null) { + encoder.writeString(parentSub); + } + } + this.content.write(encoder, offset); + } + } + + /** + * @param {AbstractUpdateDecoder} decoder + * @param {number} info + */ + const readItemContent = (decoder, info) => contentRefs[info & BITS5](decoder); + + /** + * A lookup map for reading Item content. + * + * @type {Array} + */ + const contentRefs = [ + () => { throw unexpectedCase() }, // GC is not ItemContent + readContentDeleted, // 1 + readContentJSON, // 2 + readContentBinary, // 3 + readContentString, // 4 + readContentEmbed, // 5 + readContentFormat, // 6 + readContentType, // 7 + readContentAny, // 8 + readContentDoc // 9 + ]; + + /* eslint-env browser */ + + const reconnectTimeoutBase = 1200; + const maxReconnectTimeout = 2500; + // @todo - this should depend on awareness.outdatedTime + const messageReconnectTimeout = 30000; + + /** + * @param {WebsocketClient} wsclient + */ + const setupWS = (wsclient) => { + if (wsclient.shouldConnect && wsclient.ws === null) { + const websocket = new WebSocket(wsclient.url); + const binaryType = wsclient.binaryType; + /** + * @type {any} + */ + let pingTimeout = null; + if (binaryType) { + websocket.binaryType = binaryType; + } + wsclient.ws = websocket; + wsclient.connecting = true; + wsclient.connected = false; + websocket.onmessage = event => { + wsclient.lastMessageReceived = getUnixTime(); + const data = event.data; + const message = typeof data === 'string' ? JSON.parse(data) : data; + if (message && message.type === 'pong') { + clearTimeout(pingTimeout); + pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2); + } + wsclient.emit('message', [message, wsclient]); + }; + /** + * @param {any} error + */ + const onclose = error => { + if (wsclient.ws !== null) { + wsclient.ws = null; + wsclient.connecting = false; + if (wsclient.connected) { + wsclient.connected = false; + wsclient.emit('disconnect', [{ type: 'disconnect', error }, wsclient]); + } else { + wsclient.unsuccessfulReconnects++; + } + // Start with no reconnect timeout and increase timeout by + // log10(wsUnsuccessfulReconnects). + // The idea is to increase reconnect timeout slowly and have no reconnect + // timeout at the beginning (log(1) = 0) + setTimeout(setupWS, min(log10(wsclient.unsuccessfulReconnects + 1) * reconnectTimeoutBase, maxReconnectTimeout), wsclient); + } + clearTimeout(pingTimeout); + }; + const sendPing = () => { + if (wsclient.ws === websocket) { + wsclient.send({ + type: 'ping' + }); + } + }; + websocket.onclose = () => onclose(null); + websocket.onerror = error => onclose(error); + websocket.onopen = () => { + wsclient.lastMessageReceived = getUnixTime(); + wsclient.connecting = false; + wsclient.connected = true; + wsclient.unsuccessfulReconnects = 0; + wsclient.emit('connect', [{ type: 'connect' }, wsclient]); + // set ping + pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2); + }; + } + }; + + /** + * @extends Observable + */ + class WebsocketClient extends Observable { + /** + * @param {string} url + * @param {object} [opts] + * @param {'arraybuffer' | 'blob' | null} [opts.binaryType] Set `ws.binaryType` + */ + constructor (url, { binaryType } = {}) { + super(); + this.url = url; + /** + * @type {WebSocket?} + */ + this.ws = null; + this.binaryType = binaryType || null; + this.connected = false; + this.connecting = false; + this.unsuccessfulReconnects = 0; + this.lastMessageReceived = 0; + /** + * Whether to connect to other peers or not + * @type {boolean} + */ + this.shouldConnect = true; + this._checkInterval = setInterval(() => { + if (this.connected && messageReconnectTimeout < getUnixTime() - this.lastMessageReceived) { + // no message received in a long time - not even your own awareness + // updates (which are updated every 15 seconds) + /** @type {WebSocket} */ (this.ws).close(); + } + }, messageReconnectTimeout / 2); + setupWS(this); + } + + /** + * @param {any} message + */ + send (message) { + if (this.ws) { + this.ws.send(JSON.stringify(message)); + } + } + + destroy () { + clearInterval(this._checkInterval); + this.disconnect(); + super.destroy(); + } + + disconnect () { + this.shouldConnect = false; + if (this.ws !== null) { + this.ws.close(); + } + } + + connect () { + this.shouldConnect = true; + if (!this.connected && this.ws === null) { + setupWS(this); + } + } + } + + /** + * Utility helpers to work with promises. + * + * @module promise + */ + + /** + * @param {Error} [reason] + * @return {Promise} + */ + const reject = reason => Promise.reject(reason); + + /** + * @template T + * @param {T|void} res + * @return {Promise} + */ + const resolve = res => Promise.resolve(res); + + /* eslint-env browser */ + + /** + * @typedef {Object} Channel + * @property {Set} Channel.subs + * @property {any} Channel.bc + */ + + /** + * @type {Map} + */ + const channels = new Map(); + + class LocalStoragePolyfill { + /** + * @param {string} room + */ + constructor (room) { + this.room = room; + /** + * @type {null|function({data:ArrayBuffer}):void} + */ + this.onmessage = null; + addEventListener('storage', e => e.key === room && this.onmessage !== null && this.onmessage({ data: fromBase64(e.newValue || '') })); + } + + /** + * @param {ArrayBuffer} buf + */ + postMessage (buf) { + varStorage.setItem(this.room, toBase64(createUint8ArrayFromArrayBuffer(buf))); + } + } + + // Use BroadcastChannel or Polyfill + const BC = typeof BroadcastChannel === 'undefined' ? LocalStoragePolyfill : BroadcastChannel; + + /** + * @param {string} room + * @return {Channel} + */ + const getChannel = room => + setIfUndefined(channels, room, () => { + const subs = new Set(); + const bc = new BC(room); + /** + * @param {{data:ArrayBuffer}} e + */ + bc.onmessage = e => subs.forEach(sub => sub(e.data)); + return { + bc, subs + } + }); + + /** + * Subscribe to global `publish` events. + * + * @function + * @param {string} room + * @param {function(any):any} f + */ + const subscribe = (room, f) => getChannel(room).subs.add(f); + + /** + * Unsubscribe from `publish` global events. + * + * @function + * @param {string} room + * @param {function(any):any} f + */ + const unsubscribe = (room, f) => getChannel(room).subs.delete(f); + + /** + * Publish data to all subscribers (including subscribers on this tab) + * + * @function + * @param {string} room + * @param {any} data + */ + const publish = (room, data) => { + const c = getChannel(room); + c.bc.postMessage(data); + c.subs.forEach(sub => sub(data)); + }; + + /** + * Mutual exclude for JavaScript. + * + * @module mutex + */ + + /** + * @callback mutex + * @param {function():void} cb Only executed when this mutex is not in the current stack + * @param {function():void} [elseCb] Executed when this mutex is in the current stack + */ + + /** + * Creates a mutual exclude function with the following property: + * + * ```js + * const mutex = createMutex() + * mutex(() => { + * // This function is immediately executed + * mutex(() => { + * // This function is not executed, as the mutex is already active. + * }) + * }) + * ``` + * + * @return {mutex} A mutual exclude function + * @public + */ + const createMutex = () => { + let token = true; + return (f, g) => { + if (token) { + token = false; + try { + f(); + } finally { + token = true; + } + } else if (g !== undefined) { + g(); + } + } + }; + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function createCommonjsModule(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function (path, base) { + return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); + } + }, fn(module, module.exports), module.exports; + } + + function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); + } + + var simplepeer_min = createCommonjsModule(function (module, exports) { + (function(e){module.exports=e();})(function(){var t=Math.floor,n=Math.abs,r=Math.pow;return function(){function d(s,e,n){function t(o,i){if(!e[o]){if(!s[o]){var l="function"==typeof commonjsRequire&&commonjsRequire;if(!i&&l)return l(o,!0);if(r)return r(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var a=e[o]={exports:{}};s[o][0].call(a.exports,function(e){var r=s[o][1][e];return t(r||e)},a,a.exports,d,s,e,n);}return e[o].exports}for(var r="function"==typeof commonjsRequire&&commonjsRequire,a=0;a>16,l[c++]=255&t>>8,l[c++]=255&t;return 2===s&&(t=u[e.charCodeAt(n)]<<2|u[e.charCodeAt(n+1)]>>4,l[c++]=255&t),1===s&&(t=u[e.charCodeAt(n)]<<10|u[e.charCodeAt(n+1)]<<4|u[e.charCodeAt(n+2)]>>2,l[c++]=255&t>>8,l[c++]=255&t),l}function d(e){return c[63&e>>18]+c[63&e>>12]+c[63&e>>6]+c[63&e]}function s(e,t,n){for(var r,a=[],o=t;ol?l:d+o));return 1===r?(t=e[n-1],a.push(c[t>>2]+c[63&t<<4]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],a.push(c[t>>10]+c[63&t>>4]+c[63&t<<2]+"=")),a.join("")}n.byteLength=function(e){var t=r(e),n=t[0],a=t[1];return 3*(n+a)/4-a},n.toByteArray=o,n.fromByteArray=l;for(var c=[],u=[],p="undefined"==typeof Uint8Array?Array:Uint8Array,f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",g=0,h=f.length;ge)throw new RangeError("The value \""+e+"\" is invalid for option \"size\"")}function d(e,t,n){return i(e),0>=e?a(e):void 0===t?a(e):"string"==typeof n?a(e).fill(t,n):a(e).fill(t)}function s(e){return i(e),a(0>e?0:0|f(e))}function l(e,n){if(("string"!=typeof n||""===n)&&(n="utf8"),!t.isEncoding(n))throw new TypeError("Unknown encoding: "+n);var r=0|h(e,n),o=a(r),i=o.write(e,n);return i!==r&&(o=o.slice(0,i)),o}function c(e){for(var t=0>e.length?0:0|f(e.length),n=a(t),r=0;rn||e.byteLength=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647 .toString(16)+" bytes");return 0|e}function g(e){return +e!=e&&(e=0),t.alloc(+e)}function h(e,n){if(t.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||G(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError("The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. Received type "+typeof e);var r=e.length,a=2>>1;case"base64":return H(e).length;default:if(o)return a?-1:j(e).length;n=(""+n).toLowerCase(),o=!0;}}function _(e,t,n){var r=!1;if((void 0===t||0>t)&&(t=0),t>this.length)return "";if((void 0===n||n>this.length)&&(n=this.length),0>=n)return "";if(n>>>=0,t>>>=0,n<=t)return "";for(e||(e="utf8");;)switch(e){case"hex":return N(this,t,n);case"utf8":case"utf-8":return v(this,t,n);case"ascii":return A(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return T(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0;}}function m(e,t,n){var r=e[t];e[t]=e[n],e[n]=r;}function b(e,n,r,a,o){if(0===e.length)return -1;if("string"==typeof r?(a=r,r=0):2147483647r&&(r=-2147483648),r=+r,Y(r)&&(r=o?0:e.length-1),0>r&&(r=e.length+r),r>=e.length){if(o)return -1;r=e.length-1;}else if(0>r)if(o)r=0;else return -1;if("string"==typeof n&&(n=t.from(n,a)),t.isBuffer(n))return 0===n.length?-1:y(e,n,r,a,o);if("number"==typeof n)return n&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,n,r):Uint8Array.prototype.lastIndexOf.call(e,n,r):y(e,[n],r,a,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,a){function o(e,t){return 1===d?e[t]:e.readUInt16BE(t*d)}var d=1,s=e.length,l=t.length;if(void 0!==r&&(r=(r+"").toLowerCase(),"ucs2"===r||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(2>e.length||2>t.length)return -1;d=2,s/=2,l/=2,n/=2;}var c;if(a){var u=-1;for(c=n;cs&&(n=s-l),c=n;0<=c;c--){for(var p=!0,f=0;fa&&(r=a)):r=a;var o=t.length;r>o/2&&(r=o/2);for(var d,s=0;so&&(d=o):2===s?(l=e[a+1],128==(192&l)&&(p=(31&o)<<6|63&l,127p||57343p&&(d=p))):void 0;}null===d?(d=65533,s=1):65535>>10),d=56320|1023&d),r.push(d),a+=s;}return L(r)}function L(e){var t=e.length;if(t<=4096)return z.apply(String,e);for(var n="",r=0;rt)&&(t=0),(!n||0>n||n>r)&&(n=r);for(var a="",o=t;oe)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function P(e,n,r,a,o,i){if(!t.isBuffer(e))throw new TypeError("\"buffer\" argument must be a Buffer instance");if(n>o||ne.length)throw new RangeError("Index out of range")}function D(e,t,n,r){if(n+r>e.length)throw new RangeError("Index out of range");if(0>n)throw new RangeError("Index out of range")}function F(e,t,n,r,a){return t=+t,n>>>=0,a||D(e,t,n,4),$.write(e,t,n,r,23,4),n+4}function B(e,t,n,r,a){return t=+t,n>>>=0,a||D(e,t,n,8),$.write(e,t,n,r,52,8),n+8}function O(e){if(e=e.split("=")[0],e=e.trim().replace(J,""),2>e.length)return "";for(;0!=e.length%4;)e+="=";return e}function U(e){return 16>e?"0"+e.toString(16):e.toString(16)}function j(e,t){t=t||1/0;for(var n,r=e.length,a=null,o=[],d=0;dn){if(!a){if(56319n){-1<(t-=3)&&o.push(239,191,189),a=n;continue}n=(a-55296<<10|n-56320)+65536;}else a&&-1<(t-=3)&&o.push(239,191,189);if(a=null,128>n){if(0>(t-=1))break;o.push(n);}else if(2048>n){if(0>(t-=2))break;o.push(192|n>>6,128|63&n);}else if(65536>n){if(0>(t-=3))break;o.push(224|n>>12,128|63&n>>6,128|63&n);}else if(1114112>n){if(0>(t-=4))break;o.push(240|n>>18,128|63&n>>12,128|63&n>>6,128|63&n);}else throw new Error("Invalid code point")}return o}function q(e){for(var t=[],n=0;n(t-=2));++d)n=e.charCodeAt(d),r=n>>8,a=n%256,o.push(a),o.push(r);return o}function H(e){return X.toByteArray(O(e))}function V(e,t,n,r){for(var a=0;a=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function G(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!==e}var X=e("base64-js"),$=e("ieee754");n.Buffer=t,n.SlowBuffer=g,n.INSPECT_MAX_BYTES=50;n.kMaxLength=2147483647,t.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(t){return !1}}(),t.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(t.prototype,"parent",{enumerable:!0,get:function(){return t.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(t.prototype,"offset",{enumerable:!0,get:function(){return t.isBuffer(this)?this.byteOffset:void 0}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&t[Symbol.species]===t&&Object.defineProperty(t,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),t.poolSize=8192,t.from=function(e,t,n){return o(e,t,n)},t.prototype.__proto__=Uint8Array.prototype,t.__proto__=Uint8Array,t.alloc=function(e,t,n){return d(e,t,n)},t.allocUnsafe=function(e){return s(e)},t.allocUnsafeSlow=function(e){return s(e)},t.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==t.prototype},t.compare=function(e,n){if(G(e,Uint8Array)&&(e=t.from(e,e.offset,e.byteLength)),G(n,Uint8Array)&&(n=t.from(n,n.offset,n.byteLength)),!t.isBuffer(e)||!t.isBuffer(n))throw new TypeError("The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array");if(e===n)return 0;for(var r=e.length,o=n.length,d=0,s=K(r,o);dt&&(e+=" ... "),""},t.prototype.compare=function(e,n,r,a,o){if(G(e,Uint8Array)&&(e=t.from(e,e.offset,e.byteLength)),!t.isBuffer(e))throw new TypeError("The \"target\" argument must be one of type Buffer or Uint8Array. Received type "+typeof e);if(void 0===n&&(n=0),void 0===r&&(r=e?e.length:0),void 0===a&&(a=0),void 0===o&&(o=this.length),0>n||r>e.length||0>a||o>this.length)throw new RangeError("out of range index");if(a>=o&&n>=r)return 0;if(a>=o)return -1;if(n>=r)return 1;if(n>>>=0,r>>>=0,a>>>=0,o>>>=0,this===e)return 0;for(var d=o-a,s=r-n,l=K(d,s),c=this.slice(a,o),u=e.slice(n,r),p=0;p>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var a=this.length-t;if((void 0===n||n>a)&&(n=a),0n||0>t)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return C(this,e,t,n);case"utf8":case"utf-8":return w(this,e,t,n);case"ascii":return R(this,e,t,n);case"latin1":case"binary":return E(this,e,t,n);case"base64":return S(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0;}},t.prototype.toJSON=function(){return {type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};t.prototype.slice=function(e,n){var r=this.length;e=~~e,n=void 0===n?r:~~n,0>e?(e+=r,0>e&&(e=0)):e>r&&(e=r),0>n?(n+=r,0>n&&(n=0)):n>r&&(n=r),n>>=0,t>>>=0,n||M(e,t,this.length);for(var r=this[e],a=1,o=0;++o>>=0,t>>>=0,n||M(e,t,this.length);for(var r=this[e+--t],a=1;0>>=0,t||M(e,1,this.length),this[e]},t.prototype.readUInt16LE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]|this[e+1]<<8},t.prototype.readUInt16BE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]<<8|this[e+1]},t.prototype.readUInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},t.prototype.readUInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},t.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);for(var a=this[e],o=1,d=0;++d=o&&(a-=r(2,8*t)),a},t.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);for(var a=t,o=1,d=this[e+--a];0=o&&(d-=r(2,8*t)),d},t.prototype.readInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},t.prototype.readInt16LE=function(e,t){e>>>=0,t||M(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt16BE=function(e,t){e>>>=0,t||M(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},t.prototype.readInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},t.prototype.readFloatLE=function(e,t){return e>>>=0,t||M(e,4,this.length),$.read(this,e,!0,23,4)},t.prototype.readFloatBE=function(e,t){return e>>>=0,t||M(e,4,this.length),$.read(this,e,!1,23,4)},t.prototype.readDoubleLE=function(e,t){return e>>>=0,t||M(e,8,this.length),$.read(this,e,!0,52,8)},t.prototype.readDoubleBE=function(e,t){return e>>>=0,t||M(e,8,this.length),$.read(this,e,!1,52,8)},t.prototype.writeUIntLE=function(e,t,n,a){if(e=+e,t>>>=0,n>>>=0,!a){var o=r(2,8*n)-1;P(this,e,t,n,o,0);}var d=1,s=0;for(this[t]=255&e;++s>>=0,n>>>=0,!a){var o=r(2,8*n)-1;P(this,e,t,n,o,0);}var d=n-1,s=1;for(this[t+d]=255&e;0<=--d&&(s*=256);)this[t+d]=255&e/s;return t+n},t.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,1,255,0),this[t]=255&e,t+1},t.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},t.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeIntLE=function(e,t,n,a){if(e=+e,t>>>=0,!a){var o=r(2,8*n-1);P(this,e,t,n,o-1,-o);}var d=0,s=1,l=0;for(this[t]=255&e;++de&&0===l&&0!==this[t+d-1]&&(l=1),this[t+d]=255&(e/s>>0)-l;return t+n},t.prototype.writeIntBE=function(e,t,n,a){if(e=+e,t>>>=0,!a){var o=r(2,8*n-1);P(this,e,t,n,o-1,-o);}var d=n-1,s=1,l=0;for(this[t+d]=255&e;0<=--d&&(s*=256);)0>e&&0===l&&0!==this[t+d+1]&&(l=1),this[t+d]=255&(e/s>>0)-l;return t+n},t.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,1,127,-128),0>e&&(e=255+e+1),this[t]=255&e,t+1},t.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},t.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,2147483647,-2147483648),0>e&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeFloatLE=function(e,t,n){return F(this,e,t,!0,n)},t.prototype.writeFloatBE=function(e,t,n){return F(this,e,t,!1,n)},t.prototype.writeDoubleLE=function(e,t,n){return B(this,e,t,!0,n)},t.prototype.writeDoubleBE=function(e,t,n){return B(this,e,t,!1,n)},t.prototype.copy=function(e,n,r,a){if(!t.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),a||0===a||(a=this.length),n>=e.length&&(n=e.length),n||(n=0),0n)throw new RangeError("targetStart out of bounds");if(0>r||r>=this.length)throw new RangeError("Index out of range");if(0>a)throw new RangeError("sourceEnd out of bounds");a>this.length&&(a=this.length),e.length-no||"latin1"===a)&&(e=o);}}else "number"==typeof e&&(e&=255);if(0>n||this.length>>=0,r=r===void 0?this.length:r>>>0,e||(e=0);var d;if("number"==typeof e)for(d=n;d{"%%"===e||(r++,"%c"===e&&(a=r));}),e.splice(a,0,n);},n.save=function(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug");}catch(e){}},n.load=o,n.useColors=function(){return !!("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))||!("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},n.storage=function(){try{return localStorage}catch(e){}}(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.exports=e("./common")(n);const{formatters:i}=t.exports;i.j=function(e){try{return JSON.stringify(e)}catch(e){return "[UnexpectedJSONParseError]: "+e.message}};}).call(this,e("_process"));},{"./common":5,_process:11}],5:[function(e,t){t.exports=function(t){function r(e){let t=0;for(let n=0;n{if("%%"===t)return t;d++;const o=a.formatters[n];if("function"==typeof o){const n=e[d];t=o.call(r,n),e.splice(d,1),d--;}return t}),a.formatArgs.call(r,e);const s=r.log||a.log;s.apply(r,e);}let n;return t.namespace=e,t.enabled=a.enabled(e),t.useColors=a.useColors(),t.color=r(e),t.destroy=o,t.extend=i,"function"==typeof a.init&&a.init(t),a.instances.push(t),t}function o(){const e=a.instances.indexOf(this);return -1!==e&&(a.instances.splice(e,1),!0)}function i(e,t){const n=a(this.namespace+("undefined"==typeof t?":":t)+e);return n.log=this.log,n}function d(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return a.debug=a,a.default=a,a.coerce=function(e){return e instanceof Error?e.stack||e.message:e},a.disable=function(){const e=[...a.names.map(d),...a.skips.map(d).map(e=>"-"+e)].join(",");return a.enable(""),e},a.enable=function(e){a.save(e),a.names=[],a.skips=[];let t;const n=("string"==typeof e?e:"").split(/[\s,]+/),r=n.length;for(t=0;t{a[e]=t[e];}),a.instances=[],a.names=[],a.skips=[],a.formatters={},a.selectColor=r,a.enable(a.load()),a};},{ms:10}],6:[function(e,t){function n(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=y(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0;}function r(e){return void 0===e._maxListeners?n.defaultMaxListeners:e._maxListeners}function a(e,t,n){if(t)e.call(n);else for(var r=e.length,a=m(e,r),o=0;oo)){d.warned=!0;var s=new Error("Possible EventEmitter memory leak detected. "+d.length+" \""+(t+"\" listeners added. Use emitter.setMaxListeners() to increase limit."));s.name="MaxListenersExceededWarning",s.emitter=e,s.type=t,s.count=d.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",s.name,s.message);}return e}function p(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=Array(arguments.length),t=0;te||e!==e)throw new TypeError("\"defaultMaxListeners\" must be a positive number");E=e;}}):n.defaultMaxListeners=E,n.prototype.setMaxListeners=function(e){if("number"!=typeof e||0>e||isNaN(e))throw new TypeError("\"n\" argument must be a positive number");return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return r(this)},n.prototype.emit=function(e){var t,n,r,o,u,p,f="error"===e;if(p=this._events,p)f=f&&null==p.error;else if(!f)return !1;if(f){if(1a)return this;0===a?n.shift():_(n,a),1===n.length&&(r[e]=n[0]),r.removeListener&&this.emit("removeListener",e,d||t);}return this},n.prototype.removeAllListeners=function(e){var t,n,r;if(n=this._events,!n)return this;if(!n.removeListener)return 0===arguments.length?(this._events=y(null),this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=y(null):delete n[e]),this;if(0===arguments.length){var a,o=C(n);for(r=0;r>1,h=-7,_=a?l-1:0,b=a?-1:1,d=t[n+_];for(_+=b,c=d&(1<<-h)-1,d>>=-h,h+=p;0>=-h,h+=o;0>1,E=23===p?r(2,-24)-r(2,-77):0,S=u?0:f-1,k=u?1:-1,d=0>o||0===o&&0>1/o?1:0;for(o=n(o),isNaN(o)||o===1/0?(b=isNaN(o)?1:0,_=w):(_=t(h(o)/g),1>o*(y=r(2,-_))&&(_--,y*=2),o+=1<=_+R?E/y:E*r(2,1-R),2<=o*y&&(_++,y/=2),_+R>=w?(b=0,_=w):1<=_+R?(b=(o*y-1)*r(2,p),_+=R):(b=o*r(2,R-1)*r(2,p),_=0));8<=p;a[l+S]=255&b,S+=k,b/=256,p-=8);for(_=_<=1.5*r?"s":"")}t.exports=function(e,t){t=t||{};var n=typeof e;if("string"==n&&0(n||(n=Promise.resolve())).then(e).catch(e=>setTimeout(()=>{throw e},0));},{}],13:[function(e,t){(function(n,r){var a=e("safe-buffer").Buffer,o=r.crypto||r.msCrypto;t.exports=o&&o.getRandomValues?function(e,t){if(e>4294967295)throw new RangeError("requested too many random bytes");var r=a.allocUnsafe(e);if(0n?0:+n,t.length)===t}function i(e,t,n){return (void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function d(e,t,n){return "number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}var s={};r("ERR_INVALID_OPT_VALUE",function(e,t){return "The value \""+t+"\" is invalid for option \""+e+"\""},TypeError),r("ERR_INVALID_ARG_TYPE",function(e,t,n){var r;"string"==typeof t&&o(t,"not ")?(r="must not be",t=t.replace(/^not /,"")):r="must be";var s;if(i(e," argument"))s="The ".concat(e," ").concat(r," ").concat(a(t,"type"));else {var l=d(e,".")?"property":"argument";s="The \"".concat(e,"\" ").concat(l," ").concat(r," ").concat(a(t,"type"));}return s+=". Received type ".concat(typeof n),s},TypeError),r("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),r("ERR_METHOD_NOT_IMPLEMENTED",function(e){return "The "+e+" method is not implemented"}),r("ERR_STREAM_PREMATURE_CLOSE","Premature close"),r("ERR_STREAM_DESTROYED",function(e){return "Cannot call "+e+" after a stream was destroyed"}),r("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),r("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),r("ERR_STREAM_WRITE_AFTER_END","write after end"),r("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),r("ERR_UNKNOWN_ENCODING",function(e){return "Unknown encoding: "+e},TypeError),r("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=s;},{}],15:[function(e,t){(function(n){function r(e){return this instanceof r?void(d.call(this,e),s.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",a)))):new r(e)}function a(){this._writableState.ended||n.nextTick(o,this);}function o(e){e.end();}var i=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=r;var d=e("./_stream_readable"),s=e("./_stream_writable");e("inherits")(r,d);for(var l,c=i(s.prototype),u=0;u>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function f(e,t){return 0>=e||0===t.length&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=p(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}function g(e,t){if(x("onEofChunk"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length);}t.ended=!0,t.sync?h(e):(t.needReadable=!1,!t.emittedReadable&&(t.emittedReadable=!0,_(e)));}}function h(e){var t=e._readableState;x("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(x("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(_,e));}function _(e){var t=e._readableState;x("emitReadable_",t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,S(e);}function m(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(b,e,t));}function b(e,t){for(;!t.reading&&!t.ended&&(t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function T(e){var t=e._readableState;x("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(v,t,e));}function v(e,t){if(x("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy();}}function L(e,t){for(var n=0,r=e.length;n=t.highWaterMark)||t.ended))return x("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?T(this):h(this),null;if(e=f(e,t),0===e&&t.ended)return 0===t.length&&T(this),null;var a=t.needReadable;x("need readable",a),(0===t.length||t.length-e>>0),n=this.head,r=0;n;)s(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:"consume",value:function(e,t){var n;return eo.length?o.length:e;if(a+=i===o.length?o:o.slice(0,e),e-=i,0===e){i===o.length?(++r,this.head=t.next?t.next:this.tail=null):(this.head=t,t.data=o.slice(i));break}++r;}return this.length-=r,a}},{key:"_getBuffer",value:function(e){var t=u.allocUnsafe(e),r=this.head,a=1;for(r.data.copy(t),e-=r.data.length;r=r.next;){var o=r.data,i=e>o.length?o.length:e;if(o.copy(t,t.length-e,0,i),e-=i,0===e){i===o.length?(++a,this.head=r.next?r.next:this.tail=null):(this.head=r,r.data=o.slice(i));break}++a;}return this.length-=a,t}},{key:g,value:function(e,t){return f(this,r({},t,{depth:0,customInspect:!1}))}}]),e}();},{buffer:3,util:2}],22:[function(e,t){(function(e){function n(e,t){a(e,t),r(e);}function r(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close");}function a(e,t){e.emit("error",t);}t.exports={destroy:function(t,o){var i=this,d=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return d||s?(o?o(t):t&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,e.nextTick(a,this,t)):e.nextTick(a,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!o&&t?i._writableState?i._writableState.errorEmitted?e.nextTick(r,i):(i._writableState.errorEmitted=!0,e.nextTick(n,i,t)):e.nextTick(n,i,t):o?(e.nextTick(r,i),o(t)):e.nextTick(r,i);}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1);},errorOrDestroy:function(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t);}};}).call(this,e("_process"));},{_process:11}],23:[function(e,t){function n(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=Array(n),a=0;at.length)throw new u("streams");var a,l=t.map(function(e,n){var d=nd){var s=i?o:"highWaterMark";throw new a(s,d)}return t(d)}return e.objectMode?16:16384}};},{"../../../errors":14}],27:[function(e,t){t.exports=e("events").EventEmitter;},{events:6}],28:[function(e,t,n){n=t.exports=e("./lib/_stream_readable.js"),n.Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js"),n.finished=e("./lib/internal/streams/end-of-stream.js"),n.pipeline=e("./lib/internal/streams/pipeline.js");},{"./lib/_stream_duplex.js":15,"./lib/_stream_passthrough.js":16,"./lib/_stream_readable.js":17,"./lib/_stream_transform.js":18,"./lib/_stream_writable.js":19,"./lib/internal/streams/end-of-stream.js":23,"./lib/internal/streams/pipeline.js":25}],29:[function(e,t,n){function r(e,t){for(var n in e)t[n]=e[n];}function a(e,t,n){return i(e,t,n)}/*! safe-buffer. MIT License. Feross Aboukhadijeh */var o=e("buffer"),i=o.Buffer;i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=o:(r(o,n),n.Buffer=a),a.prototype=Object.create(i.prototype),r(i,a),a.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,n)},a.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=i(e);return void 0===t?r.fill(0):"string"==typeof n?r.fill(t,n):r.fill(t),r},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o.SlowBuffer(e)};},{buffer:3}],30:[function(e,t,n){function r(e){if(!e)return "utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return "utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return "utf16le";case"latin1":case"binary":return "latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0;}}function a(e){var t=r(e);if("string"!=typeof t&&(m.isEncoding===b||!b(e)))throw new Error("Unknown encoding: "+e);return t||e}function o(e){this.encoding=a(e);var t;switch(this.encoding){case"utf16le":this.text=u,this.end=p,t=4;break;case"utf8":this.fillLast=c,t=4;break;case"base64":this.text=f,this.end=g,t=3;break;default:return this.write=h,void(this.end=_);}this.lastNeed=0,this.lastTotal=0,this.lastChar=m.allocUnsafe(t);}function d(e){if(127>=e)return 0;return 6==e>>5?2:14==e>>4?3:30==e>>3?4:2==e>>6?-1:-2}function s(e,t,n){var r=t.length-1;if(r=r)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function p(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function f(e,t){var r=(e.length-t)%3;return 0==r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1==r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function g(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function _(e){return e&&e.length?this.write(e):""}var m=e("safe-buffer").Buffer,b=m.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return !0;default:return !1;}};n.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return "";var t,n;if(this.lastNeed){if(t=this.fillLast(e),void 0===t)return "";n=this.lastNeed,this.lastNeed=0;}else n=0;return n */var i=e("debug")("simple-peer"),d=e("get-browser-rtc"),s=e("randombytes"),l=e("readable-stream"),c=e("queue-microtask"),u=65536;class p extends l.Duplex{constructor(e){if(e=Object.assign({allowHalfOpen:!1},e),super(e),this._id=s(4).toString("hex").slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||s(20).toString("hex"):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||p.channelConfig,this.negotiated=this.channelConfig.negotiated,this.config=Object.assign({},p.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.streams=e.streams||(e.stream?[e.stream]:[]),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5000,this.destroyed=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:d(),!this._wrtc)if("undefined"==typeof window)throw a("No WebRTC support: Specify `opts.wrtc` option in this environment","ERR_WEBRTC_SUPPORT");else throw a("No WebRTC support: Not a supported browser","ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!this.negotiated&&!this.initiator,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._firstStable=!0,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config);}catch(e){return void c(()=>this.destroy(a(e,"ERR_PC_CONSTRUCTOR")))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange();},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange();},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange();},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange();},this._pc.onicecandidate=e=>{this._onIceCandidate(e);},this.initiator||this.negotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e);},this.streams&&this.streams.forEach(e=>{this.addStream(e);}),this._pc.ontrack=e=>{this._onTrack(e);},this.initiator&&this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish();},this.once("finish",this._onFinishBound);}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return {port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(this.destroyed)throw a("cannot signal after peer is destroyed","ERR_SIGNALING");if("string"==typeof e)try{e=JSON.parse(e);}catch(t){e={};}this._debug("signal()"),e.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(e=>{this._addIceCandidate(e);}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer());}).catch(e=>{this.destroy(a(e,"ERR_SET_REMOTE_DESCRIPTION"));}),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(a("signal() called with invalid signal data","ERR_SIGNALING"));}_addIceCandidate(e){var t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch(e=>{!t.address||t.address.endsWith(".local")?o("Ignoring unsupported ICE candidate."):this.destroy(a(e,"ERR_ADD_ICE_CANDIDATE"));});}send(e){this._channel.send(e);}addTransceiver(e,t){if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation();}catch(e){this.destroy(a(e,"ERR_ADD_TRANSCEIVER"));}else this.emit("signal",{transceiverRequest:{kind:e,init:t}});}addStream(e){this._debug("addStream()"),e.getTracks().forEach(t=>{this.addTrack(t,e);});}addTrack(e,t){this._debug("addTrack()");var n=this._senderMap.get(e)||new Map,r=n.get(t);if(!r)r=this._pc.addTrack(e,t),n.set(t,r),this._senderMap.set(e,n),this._needsNegotiation();else if(r.removed)throw a("Track has been removed. You should enable/disable tracks that you want to re-add.","ERR_SENDER_REMOVED");else throw a("Track has already been added to that stream.","ERR_SENDER_ALREADY_ADDED")}replaceTrack(e,t,n){this._debug("replaceTrack()");var r=this._senderMap.get(e),o=r?r.get(n):null;if(!o)throw a("Cannot replace track that was never added.","ERR_TRACK_NOT_ADDED");t&&this._senderMap.set(t,r),null==o.replaceTrack?this.destroy(a("replaceTrack is not supported in this browser","ERR_UNSUPPORTED_REPLACETRACK")):o.replaceTrack(t);}removeTrack(e,t){this._debug("removeSender()");var n=this._senderMap.get(e),r=n?n.get(t):null;if(!r)throw a("Cannot remove track that was never added.","ERR_TRACK_NOT_ADDED");try{r.removed=!0,this._pc.removeTrack(r);}catch(e){"NS_ERROR_UNEXPECTED"===e.name?this._sendersAwaitingStable.push(r):this.destroy(a(e,"ERR_REMOVE_TRACK"));}this._needsNegotiation();}removeStream(e){this._debug("removeSenders()"),e.getTracks().forEach(t=>{this.removeTrack(t,e);});}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,c(()=>{this._batchedNegotiation=!1,this._debug("starting batched negotiation"),this.negotiate();}));}negotiate(){this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer();},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{renegotiate:!0})),this._isNegotiating=!0;}destroy(e){this._destroy(e,()=>{});}_destroy(e,t){if(!this.destroyed){if(this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.destroyed=!0,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close();}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null;}if(this._pc){try{this._pc.close();}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null;}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close"),t();}}_setupData(e){if(!e.channel)return this.destroy(a("Data channel event is missing `channel` property","ERR_DATA_CHANNEL"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=u),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e);},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow();},this._channel.onopen=()=>{this._onChannelOpen();},this._channel.onclose=()=>{this._onChannelClose();},this._channel.onerror=e=>{this.destroy(a(e,"ERR_DATA_CHANNEL"));};var t=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1;},5000);}_read(){}_write(e,t,n){if(this.destroyed)return n(a("cannot write after peer is destroyed","ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e);}catch(e){return this.destroy(a(e,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>u?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=n):n(null);}else this._debug("write before connect"),this._chunk=e,this._cb=n;}_onFinish(){if(!this.destroyed){const e=()=>{setTimeout(()=>this.destroy(),1e3);};this._connected?e():this.once("connect",e);}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"));},this.iceCompleteTimeout));}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=r(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){var t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp});}};this._pc.setLocalDescription(e).then(()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t));}).catch(e=>{this.destroy(a(e,"ERR_SET_LOCAL_DESCRIPTION"));});}).catch(e=>{this.destroy(a(e,"ERR_CREATE_OFFER"));});}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind));});}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=r(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){var t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers();}};this._pc.setLocalDescription(e).then(()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t));}).catch(e=>{this.destroy(a(e,"ERR_SET_LOCAL_DESCRIPTION"));});}).catch(e=>{this.destroy(a(e,"ERR_CREATE_ANSWER"));});}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(a("Connection failed.","ERR_CONNECTION_FAILURE"));}_onIceStateChange(){if(!this.destroyed){var e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,t),this.emit("iceStateChange",e,t),("connected"===e||"completed"===e)&&(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(a("Ice connection failed.","ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(a("Ice connection closed.","ERR_ICE_CONNECTION_CLOSED"));}}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach(t=>{Object.assign(e,t);}),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(n=>{var r=[];n.forEach(e=>{r.push(t(e));}),e(null,r);},t=>e(t)):0{if(!this.destroyed){var r=[];n.result().forEach(e=>{var n={};e.names().forEach(t=>{n[t]=e.stat(t);}),n.id=e.id,n.type=e.type,n.timestamp=e.timestamp,r.push(t(n));}),e(null,r);}},t=>e(t)):e(null,[]);}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats((t,n)=>{if(this.destroyed)return;t&&(n=[]);var r={},o={},i={},d=!1;n.forEach(e=>{("remotecandidate"===e.type||"remote-candidate"===e.type)&&(r[e.id]=e),("localcandidate"===e.type||"local-candidate"===e.type)&&(o[e.id]=e),("candidatepair"===e.type||"candidate-pair"===e.type)&&(i[e.id]=e);});const s=e=>{d=!0;var t=o[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=+t.port):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=+t.portNumber):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=+t[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");var n=r[e.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=+n.port):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=+n.portNumber):"string"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(":"),this.remoteAddress=n[0],this.remotePort=+n[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort);};if(n.forEach(e=>{"transport"===e.type&&e.selectedCandidatePairId&&s(i[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&s(e);}),!d&&(!Object.keys(i).length||Object.keys(o).length))return void setTimeout(e,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk);}catch(e){return this.destroy(a(e,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug("sent chunk from \"write before connect\"");var l=this._cb;this._cb=null,l(null);}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect");});};e();}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>u)&&this._onChannelBufferedAmountLow();}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&!this._firstStable&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0;}),this._sendersAwaitingStable=[],this._queuedNegotiation&&(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()),this._debug("negotiate"),this.emit("negotiate")),this._firstStable=!1,this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState));}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):!e.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout());}_onChannelMessage(e){if(!this.destroyed){var t=e.data;t instanceof ArrayBuffer&&(t=n.from(t)),this.push(t);}}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);var e=this._cb;this._cb=null,e(null);}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady());}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy());}_onTrack(e){this.destroyed||e.streams.forEach(t=>{this._debug("on track"),this.emit("track",e.track,t),this._remoteTracks.push({track:e.track,stream:t}),this._remoteStreams.some(e=>e.id===t.id)||(this._remoteStreams.push(t),c(()=>{this.emit("stream",t);}));});}_debug(){var e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],i.apply(null,e);}}p.WEBRTC_SUPPORT=!!d(),p.config={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:global.stun.twilio.com:3478?transport=udp"}],sdpSemantics:"unified-plan"},p.channelConfig={},t.exports=p;}).call(this,e("buffer").Buffer);},{buffer:3,debug:4,"get-browser-rtc":7,"queue-microtask":12,randombytes:13,"readable-stream":28}]},{},[])("/")}); + }); + + /** + * @module sync-protocol + */ + + /** + * @typedef {Map} StateMap + */ + + /** + * Core Yjs defines three message types: + * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2. + * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the the client is assured that + * it received all information from the remote client. + * + * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection + * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both + * SyncStep2 and SyncDone, it is assured that it is synced to the remote client. + * + * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1. + * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies + * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the + * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can + * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them. + * Therefore it is necesarry that the client initiates the sync. + * + * Construction of a message: + * [messageType : varUint, message definition..] + * + * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol! + * + * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer) + */ + + const messageYjsSyncStep1 = 0; + const messageYjsSyncStep2 = 1; + const messageYjsUpdate = 2; + + /** + * Create a sync step 1 message based on the state of the current shared document. + * + * @param {encoding.Encoder} encoder + * @param {Y.Doc} doc + */ + const writeSyncStep1 = (encoder, doc) => { + writeVarUint(encoder, messageYjsSyncStep1); + const sv = encodeStateVector(doc); + writeVarUint8Array(encoder, sv); + }; + + /** + * @param {encoding.Encoder} encoder + * @param {Y.Doc} doc + * @param {Uint8Array} [encodedStateVector] + */ + const writeSyncStep2 = (encoder, doc, encodedStateVector) => { + writeVarUint(encoder, messageYjsSyncStep2); + writeVarUint8Array(encoder, encodeStateAsUpdate(doc, encodedStateVector)); + }; + + /** + * Read SyncStep1 message and reply with SyncStep2. + * + * @param {decoding.Decoder} decoder The reply to the received message + * @param {encoding.Encoder} encoder The received message + * @param {Y.Doc} doc + */ + const readSyncStep1 = (decoder, encoder, doc) => + writeSyncStep2(encoder, doc, readVarUint8Array(decoder)); + + /** + * Read and apply Structs and then DeleteStore to a y instance. + * + * @param {decoding.Decoder} decoder + * @param {Y.Doc} doc + * @param {any} transactionOrigin + */ + const readSyncStep2 = (decoder, doc, transactionOrigin) => { + applyUpdate(doc, readVarUint8Array(decoder), transactionOrigin); + }; + + /** + * @param {encoding.Encoder} encoder + * @param {Uint8Array} update + */ + const writeUpdate = (encoder, update) => { + writeVarUint(encoder, messageYjsUpdate); + writeVarUint8Array(encoder, update); + }; + + /** + * Read and apply Structs and then DeleteStore to a y instance. + * + * @param {decoding.Decoder} decoder + * @param {Y.Doc} doc + * @param {any} transactionOrigin + */ + const readUpdate = readSyncStep2; + + /** + * @param {decoding.Decoder} decoder A message received from another client + * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty. + * @param {Y.Doc} doc + * @param {any} transactionOrigin + */ + const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => { + const messageType = readVarUint(decoder); + switch (messageType) { + case messageYjsSyncStep1: + readSyncStep1(decoder, encoder, doc); + break + case messageYjsSyncStep2: + readSyncStep2(decoder, doc, transactionOrigin); + break + case messageYjsUpdate: + readUpdate(decoder, doc, transactionOrigin); + break + default: + throw new Error('Unknown message type') + } + return messageType + }; + + /** + * @module awareness-protocol + */ + + const outdatedTimeout = 30000; + + /** + * @typedef {Object} MetaClientState + * @property {number} MetaClientState.clock + * @property {number} MetaClientState.lastUpdated unix timestamp + */ + + /** + * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information + * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of + * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline. + * + * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override + * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is + * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that + * a remote client is offline, it may propagate a message with + * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a + * message is received, and the known clock of that client equals the received clock, it will override the state with `null`. + * + * Before a client disconnects, it should propagate a `null` state with an updated clock. + * + * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state. + * + * @extends {Observable} + */ + class Awareness extends Observable { + /** + * @param {Y.Doc} doc + */ + constructor (doc) { + super(); + this.doc = doc; + /** + * Maps from client id to client state + * @type {Map>} + */ + this.states = new Map(); + /** + * @type {Map} + */ + this.meta = new Map(); + this._checkInterval = setInterval(() => { + const now = getUnixTime(); + if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(doc.clientID)).lastUpdated)) { + // renew local clock + this.setLocalState(this.getLocalState()); + } + /** + * @type {Array} + */ + const remove = []; + this.meta.forEach((meta, clientid) => { + if (clientid !== doc.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) { + remove.push(clientid); + } + }); + if (remove.length > 0) { + removeAwarenessStates(this, remove, 'timeout'); + } + }, floor(outdatedTimeout / 10)); + doc.on('destroy', () => { + this.destroy(); + }); + this.setLocalState({}); + } + destroy () { + super.destroy(); + clearInterval(this._checkInterval); + } + /** + * @return {Object|null} + */ + getLocalState () { + return this.states.get(this.doc.clientID) || null + } + /** + * @param {Object|null} state + */ + setLocalState (state) { + const clientID = this.doc.clientID; + const currLocalMeta = this.meta.get(clientID); + const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1; + const prevState = this.states.get(clientID); + if (state === null) { + this.states.delete(clientID); + } else { + this.states.set(clientID, state); + } + this.meta.set(clientID, { + clock, + lastUpdated: getUnixTime() + }); + const added = []; + const updated = []; + const filteredUpdated = []; + const removed = []; + if (state === null) { + removed.push(clientID); + } else if (prevState == null) { + if (state != null) { + added.push(clientID); + } + } else { + updated.push(clientID); + if (!equalityDeep(prevState, state)) { + filteredUpdated.push(clientID); + } + } + if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) { + this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local']); + } + this.emit('update', [{ added, updated, removed }, 'local']); + } + /** + * @param {string} field + * @param {any} value + */ + setLocalStateField (field, value) { + const state = this.getLocalState(); + if (state !== null) { + state[field] = value; + this.setLocalState(state); + } + } + /** + * @return {Map>} + */ + getStates () { + return this.states + } + } + + /** + * Mark (remote) clients as inactive and remove them from the list of active peers. + * This change will be propagated to remote clients. + * + * @param {Awareness} awareness + * @param {Array} clients + * @param {any} origin + */ + const removeAwarenessStates = (awareness, clients, origin) => { + const removed = []; + for (let i = 0; i < clients.length; i++) { + const clientID = clients[i]; + if (awareness.states.has(clientID)) { + awareness.states.delete(clientID); + if (clientID === awareness.doc.clientID) { + const curMeta = /** @type {MetaClientState} */ (awareness.meta.get(clientID)); + awareness.meta.set(clientID, { + clock: curMeta.clock + 1, + lastUpdated: getUnixTime() + }); + } + removed.push(clientID); + } + } + if (removed.length > 0) { + awareness.emit('change', [{ added: [], updated: [], removed }, origin]); + awareness.emit('update', [{ added: [], updated: [], removed }, origin]); + } + }; + + /** + * @param {Awareness} awareness + * @param {Array} clients + * @return {Uint8Array} + */ + const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => { + const len = clients.length; + const encoder = createEncoder(); + writeVarUint(encoder, len); + for (let i = 0; i < len; i++) { + const clientID = clients[i]; + const state = states.get(clientID) || null; + const clock = /** @type {MetaClientState} */ (awareness.meta.get(clientID)).clock; + writeVarUint(encoder, clientID); + writeVarUint(encoder, clock); + writeVarString(encoder, JSON.stringify(state)); + } + return toUint8Array(encoder) + }; + + /** + * @param {Awareness} awareness + * @param {Uint8Array} update + * @param {any} origin This will be added to the emitted change event + */ + const applyAwarenessUpdate = (awareness, update, origin) => { + const decoder = createDecoder(update); + const timestamp = getUnixTime(); + const added = []; + const updated = []; + const filteredUpdated = []; + const removed = []; + const len = readVarUint(decoder); + for (let i = 0; i < len; i++) { + const clientID = readVarUint(decoder); + let clock = readVarUint(decoder); + const state = JSON.parse(readVarString(decoder)); + const clientMeta = awareness.meta.get(clientID); + const prevState = awareness.states.get(clientID); + const currClock = clientMeta === undefined ? 0 : clientMeta.clock; + if (currClock < clock || (currClock === clock && state === null && awareness.states.has(clientID))) { + if (state === null) { + // never let a remote client remove this local state + if (clientID === awareness.doc.clientID && awareness.getLocalState() != null) { + // remote client removed the local state. Do not remote state. Broadcast a message indicating + // that this client still exists by increasing the clock + clock++; + } else { + awareness.states.delete(clientID); + } + } else { + awareness.states.set(clientID, state); + } + awareness.meta.set(clientID, { + clock, + lastUpdated: timestamp + }); + if (clientMeta === undefined && state !== null) { + added.push(clientID); + } else if (clientMeta !== undefined && state === null) { + removed.push(clientID); + } else if (state !== null) { + if (!equalityDeep(state, prevState)) { + filteredUpdated.push(clientID); + } + updated.push(clientID); + } + } + } + if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) { + awareness.emit('change', [{ + added, updated: filteredUpdated, removed + }, origin]); + } + if (added.length > 0 || updated.length > 0 || removed.length > 0) { + awareness.emit('update', [{ + added, updated, removed + }, origin]); + } + }; + + /* eslint-env browser */ + + /** + * @param {string} secret + * @param {string} roomName + * @return {PromiseLike} + */ + const deriveKey = (secret, roomName) => { + const secretBuffer = encodeUtf8(secret).buffer; + const salt = encodeUtf8(roomName).buffer; + return crypto.subtle.importKey( + 'raw', + secretBuffer, + 'PBKDF2', + false, + ['deriveKey'] + ).then(keyMaterial => + crypto.subtle.deriveKey( + { + name: 'PBKDF2', + salt, + iterations: 100000, + hash: 'SHA-256' + }, + keyMaterial, + { + name: 'AES-GCM', + length: 256 + }, + true, + ['encrypt', 'decrypt'] + ) + ) + }; + + /** + * @param {Uint8Array} data data to be encrypted + * @param {CryptoKey?} key + * @return {PromiseLike} encrypted, base64 encoded message + */ + const encrypt = (data, key) => { + if (!key) { + return /** @type {PromiseLike} */ (resolve(data)) + } + const iv = crypto.getRandomValues(new Uint8Array(12)); + return crypto.subtle.encrypt( + { + name: 'AES-GCM', + iv + }, + key, + data + ).then(cipher => { + const encryptedDataEncoder = createEncoder(); + writeVarString(encryptedDataEncoder, 'AES-GCM'); + writeVarUint8Array(encryptedDataEncoder, iv); + writeVarUint8Array(encryptedDataEncoder, new Uint8Array(cipher)); + return toUint8Array(encryptedDataEncoder) + }) + }; + + /** + * @param {Object} data data to be encrypted + * @param {CryptoKey?} key + * @return {PromiseLike} encrypted data, if key is provided + */ + const encryptJson = (data, key) => { + const dataEncoder = createEncoder(); + writeAny(dataEncoder, data); + return encrypt(toUint8Array(dataEncoder), key) + }; + + /** + * @param {Uint8Array} data + * @param {CryptoKey?} key + * @return {PromiseLike} decrypted buffer + */ + const decrypt = (data, key) => { + if (!key) { + return /** @type {PromiseLike} */ (resolve(data)) + } + const dataDecoder = createDecoder(data); + const algorithm = readVarString(dataDecoder); + if (algorithm !== 'AES-GCM') { + reject(create$2('Unknown encryption algorithm')); + } + const iv = readVarUint8Array(dataDecoder); + const cipher = readVarUint8Array(dataDecoder); + return crypto.subtle.decrypt( + { + name: 'AES-GCM', + iv + }, + key, + cipher + ).then(data => new Uint8Array(data)) + }; + + /** + * @param {Uint8Array} data + * @param {CryptoKey?} key + * @return {PromiseLike} decrypted object + */ + const decryptJson = (data, key) => + decrypt(data, key).then(decryptedValue => + readAny(createDecoder(new Uint8Array(decryptedValue))) + ); + + const log = createModuleLogger('y-webrtc'); + + const messageSync = 0; + const messageQueryAwareness = 3; + const messageAwareness = 1; + const messageBcPeerId = 4; + + /** + * @type {Map} + */ + const signalingConns = new Map(); + + /** + * @type {Map} + */ + const rooms = new Map(); + + /** + * @param {Room} room + */ + const checkIsSynced = room => { + let synced = true; + room.webrtcConns.forEach(peer => { + if (!peer.synced) { + synced = false; + } + }); + if ((!synced && room.synced) || (synced && !room.synced)) { + room.synced = synced; + room.provider.emit('synced', [{ synced }]); + log('synced ', BOLD, room.name, UNBOLD, ' with all peers'); + } + }; + + /** + * @param {Room} room + * @param {Uint8Array} buf + * @param {function} syncedCallback + * @return {encoding.Encoder?} + */ + const readMessage = (room, buf, syncedCallback) => { + const decoder = createDecoder(buf); + const encoder = createEncoder(); + const messageType = readVarUint(decoder); + if (room === undefined) { + return null + } + const awareness = room.awareness; + const doc = room.doc; + let sendReply = false; + switch (messageType) { + case messageSync: { + writeVarUint(encoder, messageSync); + const syncMessageType = readSyncMessage(decoder, encoder, doc, room); + if (syncMessageType === messageYjsSyncStep2 && !room.synced) { + syncedCallback(); + } + if (syncMessageType === messageYjsSyncStep1) { + sendReply = true; + } + break + } + case messageQueryAwareness: + writeVarUint(encoder, messageAwareness); + writeVarUint8Array(encoder, encodeAwarenessUpdate(awareness, Array.from(awareness.getStates().keys()))); + sendReply = true; + break + case messageAwareness: + applyAwarenessUpdate(awareness, readVarUint8Array(decoder), room); + break + case messageBcPeerId: { + const add = readUint8(decoder) === 1; + const peerName = readVarString(decoder); + if (peerName !== room.peerId && ((room.bcConns.has(peerName) && !add) || (!room.bcConns.has(peerName) && add))) { + const removed = []; + const added = []; + if (add) { + room.bcConns.add(peerName); + added.push(peerName); + } else { + room.bcConns.delete(peerName); + removed.push(peerName); + } + room.provider.emit('peers', [{ + added, + removed, + webrtcPeers: Array.from(room.webrtcConns.keys()), + bcPeers: Array.from(room.bcConns) + }]); + broadcastBcPeerId(room); + } + break + } + default: + console.error('Unable to compute message'); + return encoder + } + if (!sendReply) { + // nothing has been written, no answer created + return null + } + return encoder + }; + + /** + * @param {WebrtcConn} peerConn + * @param {Uint8Array} buf + * @return {encoding.Encoder?} + */ + const readPeerMessage = (peerConn, buf) => { + const room = peerConn.room; + log('received message from ', BOLD, peerConn.remotePeerId, GREY, ' (', room.name, ')', UNBOLD, UNCOLOR); + return readMessage(room, buf, () => { + peerConn.synced = true; + log('synced ', BOLD, room.name, UNBOLD, ' with ', BOLD, peerConn.remotePeerId); + checkIsSynced(room); + }) + }; + + /** + * @param {WebrtcConn} webrtcConn + * @param {encoding.Encoder} encoder + */ + const sendWebrtcConn = (webrtcConn, encoder) => { + log('send message to ', BOLD, webrtcConn.remotePeerId, UNBOLD, GREY, ' (', webrtcConn.room.name, ')', UNCOLOR); + try { + webrtcConn.peer.send(toUint8Array(encoder)); + } catch (e) {} + }; + + /** + * @param {Room} room + * @param {Uint8Array} m + */ + const broadcastWebrtcConn = (room, m) => { + log('broadcast message in ', BOLD, room.name, UNBOLD); + room.webrtcConns.forEach(conn => { + try { + conn.peer.send(m); + } catch (e) {} + }); + }; + + class WebrtcConn { + /** + * @param {SignalingConn} signalingConn + * @param {boolean} initiator + * @param {string} remotePeerId + * @param {Room} room + */ + constructor (signalingConn, initiator, remotePeerId, room) { + log('establishing connection to ', BOLD, remotePeerId); + this.room = room; + this.remotePeerId = remotePeerId; + this.closed = false; + this.connected = false; + this.synced = false; + /** + * @type {any} + */ + this.peer = new simplepeer_min({ initiator, ...room.provider.peerOpts }); + this.peer.on('signal', signal => { + publishSignalingMessage(signalingConn, room, { to: remotePeerId, from: room.peerId, type: 'signal', signal }); + }); + this.peer.on('connect', () => { + log('connected to ', BOLD, remotePeerId); + this.connected = true; + // send sync step 1 + const provider = room.provider; + const doc = provider.doc; + const awareness = room.awareness; + const encoder = createEncoder(); + writeVarUint(encoder, messageSync); + writeSyncStep1(encoder, doc); + sendWebrtcConn(this, encoder); + const awarenessStates = awareness.getStates(); + if (awarenessStates.size > 0) { + const encoder = createEncoder(); + writeVarUint(encoder, messageAwareness); + writeVarUint8Array(encoder, encodeAwarenessUpdate(awareness, Array.from(awarenessStates.keys()))); + sendWebrtcConn(this, encoder); + } + }); + this.peer.on('close', () => { + this.connected = false; + this.closed = true; + if (room.webrtcConns.has(this.remotePeerId)) { + room.webrtcConns.delete(this.remotePeerId); + room.provider.emit('peers', [{ + removed: [this.remotePeerId], + added: [], + webrtcPeers: Array.from(room.webrtcConns.keys()), + bcPeers: Array.from(room.bcConns) + }]); + } + checkIsSynced(room); + this.peer.destroy(); + log('closed connection to ', BOLD, remotePeerId); + }); + this.peer.on('close', () => { + log('Connection to remote peer ', BOLD, remotePeerId, UNBOLD, ' has been closed'); + announceSignalingInfo(room); + }); + this.peer.on('error', err => { + log('Error in connection to ', BOLD, remotePeerId, ': ', err); + announceSignalingInfo(room); + }); + this.peer.on('data', data => { + const answer = readPeerMessage(this, data); + if (answer !== null) { + sendWebrtcConn(this, answer); + } + }); + } + + destroy () { + this.peer.destroy(); + } + } + + /** + * @param {Room} room + * @param {Uint8Array} m + */ + const broadcastBcMessage = (room, m) => encrypt(m, room.key).then(data => + room.mux(() => + publish(room.name, data) + ) + ); + + /** + * @param {Room} room + * @param {Uint8Array} m + */ + const broadcastRoomMessage = (room, m) => { + if (room.bcconnected) { + broadcastBcMessage(room, m); + } + broadcastWebrtcConn(room, m); + }; + + /** + * @param {Room} room + */ + const announceSignalingInfo = room => { + signalingConns.forEach(conn => { + // only subcribe if connection is established, otherwise the conn automatically subscribes to all rooms + if (conn.connected) { + conn.send({ type: 'subscribe', topics: [room.name] }); + if (room.webrtcConns.size < room.provider.maxConns) { + publishSignalingMessage(conn, room, { type: 'announce', from: room.peerId }); + } + } + }); + }; + + /** + * @param {Room} room + */ + const broadcastBcPeerId = room => { + if (room.provider.filterBcConns) { + // broadcast peerId via broadcastchannel + const encoderPeerIdBc = createEncoder(); + writeVarUint(encoderPeerIdBc, messageBcPeerId); + writeUint8(encoderPeerIdBc, 1); + writeVarString(encoderPeerIdBc, room.peerId); + broadcastBcMessage(room, toUint8Array(encoderPeerIdBc)); + } + }; + + class Room { + /** + * @param {Y.Doc} doc + * @param {WebrtcProvider} provider + * @param {string} name + * @param {CryptoKey|null} key + */ + constructor (doc, provider, name, key) { + /** + * Do not assume that peerId is unique. This is only meant for sending signaling messages. + * + * @type {string} + */ + this.peerId = uuidv4(); + this.doc = doc; + /** + * @type {awarenessProtocol.Awareness} + */ + this.awareness = provider.awareness; + this.provider = provider; + this.synced = false; + this.name = name; + // @todo make key secret by scoping + this.key = key; + /** + * @type {Map} + */ + this.webrtcConns = new Map(); + /** + * @type {Set} + */ + this.bcConns = new Set(); + this.mux = createMutex(); + this.bcconnected = false; + /** + * @param {ArrayBuffer} data + */ + this._bcSubscriber = data => + decrypt(new Uint8Array(data), key).then(m => + this.mux(() => { + const reply = readMessage(this, m, () => {}); + if (reply) { + broadcastBcMessage(this, toUint8Array(reply)); + } + }) + ); + /** + * Listens to Yjs updates and sends them to remote peers + * + * @param {Uint8Array} update + * @param {any} origin + */ + this._docUpdateHandler = (update, origin) => { + const encoder = createEncoder(); + writeVarUint(encoder, messageSync); + writeUpdate(encoder, update); + broadcastRoomMessage(this, toUint8Array(encoder)); + }; + /** + * Listens to Awareness updates and sends them to remote peers + * + * @param {any} changed + * @param {any} origin + */ + this._awarenessUpdateHandler = ({ added, updated, removed }, origin) => { + const changedClients = added.concat(updated).concat(removed); + const encoderAwareness = createEncoder(); + writeVarUint(encoderAwareness, messageAwareness); + writeVarUint8Array(encoderAwareness, encodeAwarenessUpdate(this.awareness, changedClients)); + broadcastRoomMessage(this, toUint8Array(encoderAwareness)); + }; + this.doc.on('update', this._docUpdateHandler); + this.awareness.on('update', this._awarenessUpdateHandler); + window.addEventListener('beforeunload', () => { + removeAwarenessStates(this.awareness, [doc.clientID], 'window unload'); + rooms.forEach(room => { + room.disconnect(); + }); + }); + } + + connect () { + // signal through all available signaling connections + announceSignalingInfo(this); + const roomName = this.name; + subscribe(roomName, this._bcSubscriber); + this.bcconnected = true; + // broadcast peerId via broadcastchannel + broadcastBcPeerId(this); + // write sync step 1 + const encoderSync = createEncoder(); + writeVarUint(encoderSync, messageSync); + writeSyncStep1(encoderSync, this.doc); + broadcastBcMessage(this, toUint8Array(encoderSync)); + // broadcast local state + const encoderState = createEncoder(); + writeVarUint(encoderState, messageSync); + writeSyncStep2(encoderState, this.doc); + broadcastBcMessage(this, toUint8Array(encoderState)); + // write queryAwareness + const encoderAwarenessQuery = createEncoder(); + writeVarUint(encoderAwarenessQuery, messageQueryAwareness); + broadcastBcMessage(this, toUint8Array(encoderAwarenessQuery)); + // broadcast local awareness state + const encoderAwarenessState = createEncoder(); + writeVarUint(encoderAwarenessState, messageAwareness); + writeVarUint8Array(encoderAwarenessState, encodeAwarenessUpdate(this.awareness, [this.doc.clientID])); + broadcastBcMessage(this, toUint8Array(encoderAwarenessState)); + } + + disconnect () { + // signal through all available signaling connections + signalingConns.forEach(conn => { + if (conn.connected) { + conn.send({ type: 'unsubscribe', topics: [this.name] }); + } + }); + removeAwarenessStates(this.awareness, [this.doc.clientID], 'disconnect'); + // broadcast peerId removal via broadcastchannel + const encoderPeerIdBc = createEncoder(); + writeVarUint(encoderPeerIdBc, messageBcPeerId); + writeUint8(encoderPeerIdBc, 0); // remove peerId from other bc peers + writeVarString(encoderPeerIdBc, this.peerId); + broadcastBcMessage(this, toUint8Array(encoderPeerIdBc)); + + unsubscribe(this.name, this._bcSubscriber); + this.bcconnected = false; + this.doc.off('update', this._docUpdateHandler); + this.awareness.off('update', this._awarenessUpdateHandler); + this.webrtcConns.forEach(conn => conn.destroy()); + } + + destroy () { + this.disconnect(); + } + } + + /** + * @param {Y.Doc} doc + * @param {WebrtcProvider} provider + * @param {string} name + * @param {CryptoKey|null} key + * @return {Room} + */ + const openRoom = (doc, provider, name, key) => { + // there must only be one room + if (rooms.has(name)) { + throw create$2(`A Yjs Doc connected to room "${name}" already exists!`) + } + const room = new Room(doc, provider, name, key); + rooms.set(name, /** @type {Room} */ (room)); + return room + }; + + /** + * @param {SignalingConn} conn + * @param {Room} room + * @param {any} data + */ + const publishSignalingMessage = (conn, room, data) => { + if (room.key) { + encryptJson(data, room.key).then(data => { + conn.send({ type: 'publish', topic: room.name, data: toBase64(data) }); + }); + } else { + conn.send({ type: 'publish', topic: room.name, data }); + } + }; + + class SignalingConn extends WebsocketClient { + constructor (url) { + super(url); + /** + * @type {Set} + */ + this.providers = new Set(); + this.on('connect', () => { + log(`connected (${url})`); + const topics = Array.from(rooms.keys()); + this.send({ type: 'subscribe', topics }); + rooms.forEach(room => + publishSignalingMessage(this, room, { type: 'announce', from: room.peerId }) + ); + }); + this.on('message', m => { + switch (m.type) { + case 'publish': { + const roomName = m.topic; + const room = rooms.get(roomName); + if (room == null || typeof roomName !== 'string') { + return + } + const execMessage = data => { + const webrtcConns = room.webrtcConns; + const peerId = room.peerId; + if (data == null || data.from === peerId || (data.to !== undefined && data.to !== peerId) || room.bcConns.has(data.from)) { + // ignore messages that are not addressed to this conn, or from clients that are connected via broadcastchannel + return + } + const emitPeerChange = webrtcConns.has(data.from) ? () => {} : () => + room.provider.emit('peers', [{ + removed: [], + added: [data.from], + webrtcPeers: Array.from(room.webrtcConns.keys()), + bcPeers: Array.from(room.bcConns) + }]); + switch (data.type) { + case 'announce': + if (webrtcConns.size < room.provider.maxConns) { + setIfUndefined(webrtcConns, data.from, () => new WebrtcConn(this, true, data.from, room)); + emitPeerChange(); + } + break + case 'signal': + if (data.to === peerId) { + setIfUndefined(webrtcConns, data.from, () => new WebrtcConn(this, false, data.from, room)).peer.signal(data.signal); + emitPeerChange(); + } + break + } + }; + if (room.key) { + if (typeof m.data === 'string') { + decryptJson(fromBase64(m.data), room.key).then(execMessage); + } + } else { + execMessage(m.data); + } + } + } + }); + this.on('disconnect', () => log(`disconnect (${url})`)); + } + } + + /** + * @extends Observable + */ + class WebrtcProvider extends Observable { + /** + * @param {string} roomName + * @param {Y.Doc} doc + * @param {Object} [opts] + * @param {Array} [opts.signaling] + * @param {string?} [opts.password] + * @param {awarenessProtocol.Awareness} [opts.awareness] + * @param {number} [opts.maxConns] + * @param {boolean} [opts.filterBcConns] + * @param {any} [opts.peerOpts] + */ + constructor ( + roomName, + doc, + { + signaling = ['wss://signaling.yjs.dev', 'wss://y-webrtc-signaling-eu.herokuapp.com', 'wss://y-webrtc-signaling-us.herokuapp.com'], + password = null, + awareness = new Awareness(doc), + maxConns = 20 + floor(rand() * 15), // the random factor reduces the chance that n clients form a cluster + filterBcConns = true, + peerOpts = {} // simple-peer options. See https://github.com/feross/simple-peer#peer--new-peeropts + } = {} + ) { + super(); + this.roomName = roomName; + this.doc = doc; + this.filterBcConns = filterBcConns; + /** + * @type {awarenessProtocol.Awareness} + */ + this.awareness = awareness; + this.shouldConnect = false; + this.signalingUrls = signaling; + this.signalingConns = []; + this.maxConns = maxConns; + this.peerOpts = peerOpts; + /** + * @type {PromiseLike} + */ + this.key = password ? deriveKey(password, roomName) : /** @type {PromiseLike} */ (resolve(null)); + /** + * @type {Room|null} + */ + this.room = null; + this.key.then(key => { + this.room = openRoom(doc, this, roomName, key); + if (this.shouldConnect) { + this.room.connect(); + } else { + this.room.disconnect(); + } + }); + this.connect(); + } + + /** + * @type {boolean} + */ + get connected () { + return this.room !== null && this.shouldConnect + } + + connect () { + this.shouldConnect = true; + this.signalingUrls.forEach(url => { + const signalingConn = setIfUndefined(signalingConns, url, () => new SignalingConn(url)); + this.signalingConns.push(signalingConn); + signalingConn.providers.add(this); + }); + if (this.room) { + this.room.connect(); + } + } + + disconnect () { + this.shouldConnect = false; + this.signalingConns.forEach(conn => { + conn.providers.delete(this); + if (conn.providers.size === 0) { + conn.destroy(); + signalingConns.delete(this.roomName); + } + }); + if (this.room) { + this.room.disconnect(); + } + } + + destroy () { + // need to wait for key before deleting room + this.key.then(() => { + /** @type {Room} */ (this.room).destroy(); + rooms.delete(this.roomName); + }); + super.destroy(); + } + } + + // ::- Persistent data structure representing an ordered mapping from + // strings to values, with some convenient update methods. + function OrderedMap(content) { + this.content = content; + } + + OrderedMap.prototype = { + constructor: OrderedMap, + + find: function(key) { + for (var i = 0; i < this.content.length; i += 2) + if (this.content[i] === key) return i + return -1 + }, + + // :: (string) → ?any + // Retrieve the value stored under `key`, or return undefined when + // no such key exists. + get: function(key) { + var found = this.find(key); + return found == -1 ? undefined : this.content[found + 1] + }, + + // :: (string, any, ?string) → OrderedMap + // Create a new map by replacing the value of `key` with a new + // value, or adding a binding to the end of the map. If `newKey` is + // given, the key of the binding will be replaced with that key. + update: function(key, value, newKey) { + var self = newKey && newKey != key ? this.remove(newKey) : this; + var found = self.find(key), content = self.content.slice(); + if (found == -1) { + content.push(newKey || key, value); + } else { + content[found + 1] = value; + if (newKey) content[found] = newKey; + } + return new OrderedMap(content) + }, + + // :: (string) → OrderedMap + // Return a map with the given key removed, if it existed. + remove: function(key) { + var found = this.find(key); + if (found == -1) return this + var content = this.content.slice(); + content.splice(found, 2); + return new OrderedMap(content) + }, + + // :: (string, any) → OrderedMap + // Add a new key to the start of the map. + addToStart: function(key, value) { + return new OrderedMap([key, value].concat(this.remove(key).content)) + }, + + // :: (string, any) → OrderedMap + // Add a new key to the end of the map. + addToEnd: function(key, value) { + var content = this.remove(key).content.slice(); + content.push(key, value); + return new OrderedMap(content) + }, + + // :: (string, string, any) → OrderedMap + // Add a key after the given key. If `place` is not found, the new + // key is added to the end. + addBefore: function(place, key, value) { + var without = this.remove(key), content = without.content.slice(); + var found = without.find(place); + content.splice(found == -1 ? content.length : found, 0, key, value); + return new OrderedMap(content) + }, + + // :: ((key: string, value: any)) + // Call the given function for each key/value pair in the map, in + // order. + forEach: function(f) { + for (var i = 0; i < this.content.length; i += 2) + f(this.content[i], this.content[i + 1]); + }, + + // :: (union) → OrderedMap + // Create a new map by prepending the keys in this map that don't + // appear in `map` before the keys in `map`. + prepend: function(map) { + map = OrderedMap.from(map); + if (!map.size) return this + return new OrderedMap(map.content.concat(this.subtract(map).content)) + }, + + // :: (union) → OrderedMap + // Create a new map by appending the keys in this map that don't + // appear in `map` after the keys in `map`. + append: function(map) { + map = OrderedMap.from(map); + if (!map.size) return this + return new OrderedMap(this.subtract(map).content.concat(map.content)) + }, + + // :: (union) → OrderedMap + // Create a map containing all the keys in this map that don't + // appear in `map`. + subtract: function(map) { + var result = this; + map = OrderedMap.from(map); + for (var i = 0; i < map.content.length; i += 2) + result = result.remove(map.content[i]); + return result + }, + + // :: number + // The amount of keys in this map. + get size() { + return this.content.length >> 1 + } + }; + + // :: (?union) → OrderedMap + // Return a map with the given content. If null, create an empty + // map. If given an ordered map, return that map itself. If given an + // object, create a map from the object's properties. + OrderedMap.from = function(value) { + if (value instanceof OrderedMap) return value + var content = []; + if (value) for (var prop in value) content.push(prop, value[prop]); + return new OrderedMap(content) + }; + + var orderedmap = OrderedMap; + + function findDiffStart(a, b, pos) { + for (var i = 0;; i++) { + if (i == a.childCount || i == b.childCount) + { return a.childCount == b.childCount ? null : pos } + + var childA = a.child(i), childB = b.child(i); + if (childA == childB) { pos += childA.nodeSize; continue } + + if (!childA.sameMarkup(childB)) { return pos } + + if (childA.isText && childA.text != childB.text) { + for (var j = 0; childA.text[j] == childB.text[j]; j++) + { pos++; } + return pos + } + if (childA.content.size || childB.content.size) { + var inner = findDiffStart(childA.content, childB.content, pos + 1); + if (inner != null) { return inner } + } + pos += childA.nodeSize; + } + } + + function findDiffEnd(a, b, posA, posB) { + for (var iA = a.childCount, iB = b.childCount;;) { + if (iA == 0 || iB == 0) + { return iA == iB ? null : {a: posA, b: posB} } + + var childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize; + if (childA == childB) { + posA -= size; posB -= size; + continue + } + + if (!childA.sameMarkup(childB)) { return {a: posA, b: posB} } + + if (childA.isText && childA.text != childB.text) { + var same = 0, minSize = Math.min(childA.text.length, childB.text.length); + while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) { + same++; posA--; posB--; + } + return {a: posA, b: posB} + } + if (childA.content.size || childB.content.size) { + var inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1); + if (inner) { return inner } + } + posA -= size; posB -= size; + } + } + + // ::- A fragment represents a node's collection of child nodes. + // + // Like nodes, fragments are persistent data structures, and you + // should not mutate them or their content. Rather, you create new + // instances whenever needed. The API tries to make this easy. + var Fragment = function Fragment(content, size) { + this.content = content; + // :: number + // The size of the fragment, which is the total of the size of its + // content nodes. + this.size = size || 0; + if (size == null) { for (var i = 0; i < content.length; i++) + { this.size += content[i].nodeSize; } } + }; + + var prototypeAccessors = { firstChild: { configurable: true },lastChild: { configurable: true },childCount: { configurable: true } }; + + // :: (number, number, (node: Node, start: number, parent: Node, index: number) → ?bool, ?number) + // Invoke a callback for all descendant nodes between the given two + // positions (relative to start of this fragment). Doesn't descend + // into a node when the callback returns `false`. + Fragment.prototype.nodesBetween = function nodesBetween (from, to, f, nodeStart, parent) { + if ( nodeStart === void 0 ) nodeStart = 0; + + for (var i = 0, pos = 0; pos < to; i++) { + var child = this.content[i], end = pos + child.nodeSize; + if (end > from && f(child, nodeStart + pos, parent, i) !== false && child.content.size) { + var start = pos + 1; + child.nodesBetween(Math.max(0, from - start), + Math.min(child.content.size, to - start), + f, nodeStart + start); + } + pos = end; + } + }; + + // :: ((node: Node, pos: number, parent: Node) → ?bool) + // Call the given callback for every descendant node. The callback + // may return `false` to prevent traversal of a given node's children. + Fragment.prototype.descendants = function descendants (f) { + this.nodesBetween(0, this.size, f); + }; + + // : (number, number, ?string, ?string) → string + Fragment.prototype.textBetween = function textBetween (from, to, blockSeparator, leafText) { + var text = "", separated = true; + this.nodesBetween(from, to, function (node, pos) { + if (node.isText) { + text += node.text.slice(Math.max(from, pos) - pos, to - pos); + separated = !blockSeparator; + } else if (node.isLeaf && leafText) { + text += leafText; + separated = !blockSeparator; + } else if (!separated && node.isBlock) { + text += blockSeparator; + separated = true; + } + }, 0); + return text + }; + + // :: (Fragment) → Fragment + // Create a new fragment containing the combined content of this + // fragment and the other. + Fragment.prototype.append = function append (other) { + if (!other.size) { return this } + if (!this.size) { return other } + var last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0; + if (last.isText && last.sameMarkup(first)) { + content[content.length - 1] = last.withText(last.text + first.text); + i = 1; + } + for (; i < other.content.length; i++) { content.push(other.content[i]); } + return new Fragment(content, this.size + other.size) + }; + + // :: (number, ?number) → Fragment + // Cut out the sub-fragment between the two given positions. + Fragment.prototype.cut = function cut (from, to) { + if (to == null) { to = this.size; } + if (from == 0 && to == this.size) { return this } + var result = [], size = 0; + if (to > from) { for (var i = 0, pos = 0; pos < to; i++) { + var child = this.content[i], end = pos + child.nodeSize; + if (end > from) { + if (pos < from || end > to) { + if (child.isText) + { child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos)); } + else + { child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1)); } + } + result.push(child); + size += child.nodeSize; + } + pos = end; + } } + return new Fragment(result, size) + }; + + Fragment.prototype.cutByIndex = function cutByIndex (from, to) { + if (from == to) { return Fragment.empty } + if (from == 0 && to == this.content.length) { return this } + return new Fragment(this.content.slice(from, to)) + }; + + // :: (number, Node) → Fragment + // Create a new fragment in which the node at the given index is + // replaced by the given node. + Fragment.prototype.replaceChild = function replaceChild (index, node) { + var current = this.content[index]; + if (current == node) { return this } + var copy = this.content.slice(); + var size = this.size + node.nodeSize - current.nodeSize; + copy[index] = node; + return new Fragment(copy, size) + }; + + // : (Node) → Fragment + // Create a new fragment by prepending the given node to this + // fragment. + Fragment.prototype.addToStart = function addToStart (node) { + return new Fragment([node].concat(this.content), this.size + node.nodeSize) + }; + + // : (Node) → Fragment + // Create a new fragment by appending the given node to this + // fragment. + Fragment.prototype.addToEnd = function addToEnd (node) { + return new Fragment(this.content.concat(node), this.size + node.nodeSize) + }; + + // :: (Fragment) → bool + // Compare this fragment to another one. + Fragment.prototype.eq = function eq (other) { + if (this.content.length != other.content.length) { return false } + for (var i = 0; i < this.content.length; i++) + { if (!this.content[i].eq(other.content[i])) { return false } } + return true + }; + + // :: ?Node + // The first child of the fragment, or `null` if it is empty. + prototypeAccessors.firstChild.get = function () { return this.content.length ? this.content[0] : null }; + + // :: ?Node + // The last child of the fragment, or `null` if it is empty. + prototypeAccessors.lastChild.get = function () { return this.content.length ? this.content[this.content.length - 1] : null }; + + // :: number + // The number of child nodes in this fragment. + prototypeAccessors.childCount.get = function () { return this.content.length }; + + // :: (number) → Node + // Get the child node at the given index. Raise an error when the + // index is out of range. + Fragment.prototype.child = function child (index) { + var found = this.content[index]; + if (!found) { throw new RangeError("Index " + index + " out of range for " + this) } + return found + }; + + // :: (number) → ?Node + // Get the child node at the given index, if it exists. + Fragment.prototype.maybeChild = function maybeChild (index) { + return this.content[index] + }; + + // :: ((node: Node, offset: number, index: number)) + // Call `f` for every child node, passing the node, its offset + // into this parent node, and its index. + Fragment.prototype.forEach = function forEach (f) { + for (var i = 0, p = 0; i < this.content.length; i++) { + var child = this.content[i]; + f(child, p, i); + p += child.nodeSize; + } + }; + + // :: (Fragment) → ?number + // Find the first position at which this fragment and another + // fragment differ, or `null` if they are the same. + Fragment.prototype.findDiffStart = function findDiffStart$1 (other, pos) { + if ( pos === void 0 ) pos = 0; + + return findDiffStart(this, other, pos) + }; + + // :: (Fragment) → ?{a: number, b: number} + // Find the first position, searching from the end, at which this + // fragment and the given fragment differ, or `null` if they are the + // same. Since this position will not be the same in both nodes, an + // object with two separate positions is returned. + Fragment.prototype.findDiffEnd = function findDiffEnd$1 (other, pos, otherPos) { + if ( pos === void 0 ) pos = this.size; + if ( otherPos === void 0 ) otherPos = other.size; + + return findDiffEnd(this, other, pos, otherPos) + }; + + // : (number, ?number) → {index: number, offset: number} + // Find the index and inner offset corresponding to a given relative + // position in this fragment. The result object will be reused + // (overwritten) the next time the function is called. (Not public.) + Fragment.prototype.findIndex = function findIndex (pos, round) { + if ( round === void 0 ) round = -1; + + if (pos == 0) { return retIndex(0, pos) } + if (pos == this.size) { return retIndex(this.content.length, pos) } + if (pos > this.size || pos < 0) { throw new RangeError(("Position " + pos + " outside of fragment (" + (this) + ")")) } + for (var i = 0, curPos = 0;; i++) { + var cur = this.child(i), end = curPos + cur.nodeSize; + if (end >= pos) { + if (end == pos || round > 0) { return retIndex(i + 1, end) } + return retIndex(i, curPos) + } + curPos = end; + } + }; + + // :: () → string + // Return a debugging string that describes this fragment. + Fragment.prototype.toString = function toString () { return "<" + this.toStringInner() + ">" }; + + Fragment.prototype.toStringInner = function toStringInner () { return this.content.join(", ") }; + + // :: () → ?Object + // Create a JSON-serializeable representation of this fragment. + Fragment.prototype.toJSON = function toJSON () { + return this.content.length ? this.content.map(function (n) { return n.toJSON(); }) : null + }; + + // :: (Schema, ?Object) → Fragment + // Deserialize a fragment from its JSON representation. + Fragment.fromJSON = function fromJSON (schema, value) { + if (!value) { return Fragment.empty } + if (!Array.isArray(value)) { throw new RangeError("Invalid input for Fragment.fromJSON") } + return new Fragment(value.map(schema.nodeFromJSON)) + }; + + // :: ([Node]) → Fragment + // Build a fragment from an array of nodes. Ensures that adjacent + // text nodes with the same marks are joined together. + Fragment.fromArray = function fromArray (array) { + if (!array.length) { return Fragment.empty } + var joined, size = 0; + for (var i = 0; i < array.length; i++) { + var node = array[i]; + size += node.nodeSize; + if (i && node.isText && array[i - 1].sameMarkup(node)) { + if (!joined) { joined = array.slice(0, i); } + joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text); + } else if (joined) { + joined.push(node); + } + } + return new Fragment(joined || array, size) + }; + + // :: (?union) → Fragment + // Create a fragment from something that can be interpreted as a set + // of nodes. For `null`, it returns the empty fragment. For a + // fragment, the fragment itself. For a node or array of nodes, a + // fragment containing those nodes. + Fragment.from = function from (nodes) { + if (!nodes) { return Fragment.empty } + if (nodes instanceof Fragment) { return nodes } + if (Array.isArray(nodes)) { return this.fromArray(nodes) } + if (nodes.attrs) { return new Fragment([nodes], nodes.nodeSize) } + throw new RangeError("Can not convert " + nodes + " to a Fragment" + + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : "")) + }; + + Object.defineProperties( Fragment.prototype, prototypeAccessors ); + + var found = {index: 0, offset: 0}; + function retIndex(index, offset) { + found.index = index; + found.offset = offset; + return found + } + + // :: Fragment + // An empty fragment. Intended to be reused whenever a node doesn't + // contain anything (rather than allocating a new empty fragment for + // each leaf node). + Fragment.empty = new Fragment([], 0); + + function compareDeep(a, b) { + if (a === b) { return true } + if (!(a && typeof a == "object") || + !(b && typeof b == "object")) { return false } + var array = Array.isArray(a); + if (Array.isArray(b) != array) { return false } + if (array) { + if (a.length != b.length) { return false } + for (var i = 0; i < a.length; i++) { if (!compareDeep(a[i], b[i])) { return false } } + } else { + for (var p in a) { if (!(p in b) || !compareDeep(a[p], b[p])) { return false } } + for (var p$1 in b) { if (!(p$1 in a)) { return false } } + } + return true + } + + // ::- A mark is a piece of information that can be attached to a node, + // such as it being emphasized, in code font, or a link. It has a type + // and optionally a set of attributes that provide further information + // (such as the target of the link). Marks are created through a + // `Schema`, which controls which types exist and which + // attributes they have. + var Mark = function Mark(type, attrs) { + // :: MarkType + // The type of this mark. + this.type = type; + // :: Object + // The attributes associated with this mark. + this.attrs = attrs; + }; + + // :: ([Mark]) → [Mark] + // Given a set of marks, create a new set which contains this one as + // well, in the right position. If this mark is already in the set, + // the set itself is returned. If any marks that are set to be + // [exclusive](#model.MarkSpec.excludes) with this mark are present, + // those are replaced by this one. + Mark.prototype.addToSet = function addToSet (set) { + var copy, placed = false; + for (var i = 0; i < set.length; i++) { + var other = set[i]; + if (this.eq(other)) { return set } + if (this.type.excludes(other.type)) { + if (!copy) { copy = set.slice(0, i); } + } else if (other.type.excludes(this.type)) { + return set + } else { + if (!placed && other.type.rank > this.type.rank) { + if (!copy) { copy = set.slice(0, i); } + copy.push(this); + placed = true; + } + if (copy) { copy.push(other); } + } + } + if (!copy) { copy = set.slice(); } + if (!placed) { copy.push(this); } + return copy + }; + + // :: ([Mark]) → [Mark] + // Remove this mark from the given set, returning a new set. If this + // mark is not in the set, the set itself is returned. + Mark.prototype.removeFromSet = function removeFromSet (set) { + for (var i = 0; i < set.length; i++) + { if (this.eq(set[i])) + { return set.slice(0, i).concat(set.slice(i + 1)) } } + return set + }; + + // :: ([Mark]) → bool + // Test whether this mark is in the given set of marks. + Mark.prototype.isInSet = function isInSet (set) { + for (var i = 0; i < set.length; i++) + { if (this.eq(set[i])) { return true } } + return false + }; + + // :: (Mark) → bool + // Test whether this mark has the same type and attributes as + // another mark. + Mark.prototype.eq = function eq (other) { + return this == other || + (this.type == other.type && compareDeep(this.attrs, other.attrs)) + }; + + // :: () → Object + // Convert this mark to a JSON-serializeable representation. + Mark.prototype.toJSON = function toJSON () { + var obj = {type: this.type.name}; + for (var _ in this.attrs) { + obj.attrs = this.attrs; + break + } + return obj + }; + + // :: (Schema, Object) → Mark + Mark.fromJSON = function fromJSON (schema, json) { + if (!json) { throw new RangeError("Invalid input for Mark.fromJSON") } + var type = schema.marks[json.type]; + if (!type) { throw new RangeError(("There is no mark type " + (json.type) + " in this schema")) } + return type.create(json.attrs) + }; + + // :: ([Mark], [Mark]) → bool + // Test whether two sets of marks are identical. + Mark.sameSet = function sameSet (a, b) { + if (a == b) { return true } + if (a.length != b.length) { return false } + for (var i = 0; i < a.length; i++) + { if (!a[i].eq(b[i])) { return false } } + return true + }; + + // :: (?union) → [Mark] + // Create a properly sorted mark set from null, a single mark, or an + // unsorted array of marks. + Mark.setFrom = function setFrom (marks) { + if (!marks || marks.length == 0) { return Mark.none } + if (marks instanceof Mark) { return [marks] } + var copy = marks.slice(); + copy.sort(function (a, b) { return a.type.rank - b.type.rank; }); + return copy + }; + + // :: [Mark] The empty set of marks. + Mark.none = []; + + // ReplaceError:: class extends Error + // Error type raised by [`Node.replace`](#model.Node.replace) when + // given an invalid replacement. + + function ReplaceError(message) { + var err = Error.call(this, message); + err.__proto__ = ReplaceError.prototype; + return err + } + + ReplaceError.prototype = Object.create(Error.prototype); + ReplaceError.prototype.constructor = ReplaceError; + ReplaceError.prototype.name = "ReplaceError"; + + // ::- A slice represents a piece cut out of a larger document. It + // stores not only a fragment, but also the depth up to which nodes on + // both side are ‘open’ (cut through). + var Slice = function Slice(content, openStart, openEnd) { + // :: Fragment The slice's content. + this.content = content; + // :: number The open depth at the start. + this.openStart = openStart; + // :: number The open depth at the end. + this.openEnd = openEnd; + }; + + var prototypeAccessors$1 = { size: { configurable: true } }; + + // :: number + // The size this slice would add when inserted into a document. + prototypeAccessors$1.size.get = function () { + return this.content.size - this.openStart - this.openEnd + }; + + Slice.prototype.insertAt = function insertAt (pos, fragment) { + var content = insertInto(this.content, pos + this.openStart, fragment, null); + return content && new Slice(content, this.openStart, this.openEnd) + }; + + Slice.prototype.removeBetween = function removeBetween (from, to) { + return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd) + }; + + // :: (Slice) → bool + // Tests whether this slice is equal to another slice. + Slice.prototype.eq = function eq (other) { + return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd + }; + + Slice.prototype.toString = function toString () { + return this.content + "(" + this.openStart + "," + this.openEnd + ")" + }; + + // :: () → ?Object + // Convert a slice to a JSON-serializable representation. + Slice.prototype.toJSON = function toJSON () { + if (!this.content.size) { return null } + var json = {content: this.content.toJSON()}; + if (this.openStart > 0) { json.openStart = this.openStart; } + if (this.openEnd > 0) { json.openEnd = this.openEnd; } + return json + }; + + // :: (Schema, ?Object) → Slice + // Deserialize a slice from its JSON representation. + Slice.fromJSON = function fromJSON (schema, json) { + if (!json) { return Slice.empty } + var openStart = json.openStart || 0, openEnd = json.openEnd || 0; + if (typeof openStart != "number" || typeof openEnd != "number") + { throw new RangeError("Invalid input for Slice.fromJSON") } + return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd) + }; + + // :: (Fragment, ?bool) → Slice + // Create a slice from a fragment by taking the maximum possible + // open value on both side of the fragment. + Slice.maxOpen = function maxOpen (fragment, openIsolating) { + if ( openIsolating === void 0 ) openIsolating=true; + + var openStart = 0, openEnd = 0; + for (var n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild) { openStart++; } + for (var n$1 = fragment.lastChild; n$1 && !n$1.isLeaf && (openIsolating || !n$1.type.spec.isolating); n$1 = n$1.lastChild) { openEnd++; } + return new Slice(fragment, openStart, openEnd) + }; + + Object.defineProperties( Slice.prototype, prototypeAccessors$1 ); + + function removeRange(content, from, to) { + var ref = content.findIndex(from); + var index = ref.index; + var offset = ref.offset; + var child = content.maybeChild(index); + var ref$1 = content.findIndex(to); + var indexTo = ref$1.index; + var offsetTo = ref$1.offset; + if (offset == from || child.isText) { + if (offsetTo != to && !content.child(indexTo).isText) { throw new RangeError("Removing non-flat range") } + return content.cut(0, from).append(content.cut(to)) + } + if (index != indexTo) { throw new RangeError("Removing non-flat range") } + return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1))) + } + + function insertInto(content, dist, insert, parent) { + var ref = content.findIndex(dist); + var index = ref.index; + var offset = ref.offset; + var child = content.maybeChild(index); + if (offset == dist || child.isText) { + if (parent && !parent.canReplace(index, index, insert)) { return null } + return content.cut(0, dist).append(insert).append(content.cut(dist)) + } + var inner = insertInto(child.content, dist - offset - 1, insert); + return inner && content.replaceChild(index, child.copy(inner)) + } + + // :: Slice + // The empty slice. + Slice.empty = new Slice(Fragment.empty, 0, 0); + + function replace($from, $to, slice) { + if (slice.openStart > $from.depth) + { throw new ReplaceError("Inserted content deeper than insertion position") } + if ($from.depth - slice.openStart != $to.depth - slice.openEnd) + { throw new ReplaceError("Inconsistent open depths") } + return replaceOuter($from, $to, slice, 0) + } + + function replaceOuter($from, $to, slice, depth) { + var index = $from.index(depth), node = $from.node(depth); + if (index == $to.index(depth) && depth < $from.depth - slice.openStart) { + var inner = replaceOuter($from, $to, slice, depth + 1); + return node.copy(node.content.replaceChild(index, inner)) + } else if (!slice.content.size) { + return close(node, replaceTwoWay($from, $to, depth)) + } else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case + var parent = $from.parent, content = parent.content; + return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset))) + } else { + var ref = prepareSliceForReplace(slice, $from); + var start = ref.start; + var end = ref.end; + return close(node, replaceThreeWay($from, start, end, $to, depth)) + } + } + + function checkJoin(main, sub) { + if (!sub.type.compatibleContent(main.type)) + { throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name) } + } + + function joinable($before, $after, depth) { + var node = $before.node(depth); + checkJoin(node, $after.node(depth)); + return node + } + + function addNode(child, target) { + var last = target.length - 1; + if (last >= 0 && child.isText && child.sameMarkup(target[last])) + { target[last] = child.withText(target[last].text + child.text); } + else + { target.push(child); } + } + + function addRange($start, $end, depth, target) { + var node = ($end || $start).node(depth); + var startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount; + if ($start) { + startIndex = $start.index(depth); + if ($start.depth > depth) { + startIndex++; + } else if ($start.textOffset) { + addNode($start.nodeAfter, target); + startIndex++; + } + } + for (var i = startIndex; i < endIndex; i++) { addNode(node.child(i), target); } + if ($end && $end.depth == depth && $end.textOffset) + { addNode($end.nodeBefore, target); } + } + + function close(node, content) { + if (!node.type.validContent(content)) + { throw new ReplaceError("Invalid content for node " + node.type.name) } + return node.copy(content) + } + + function replaceThreeWay($from, $start, $end, $to, depth) { + var openStart = $from.depth > depth && joinable($from, $start, depth + 1); + var openEnd = $to.depth > depth && joinable($end, $to, depth + 1); + + var content = []; + addRange(null, $from, depth, content); + if (openStart && openEnd && $start.index(depth) == $end.index(depth)) { + checkJoin(openStart, openEnd); + addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content); + } else { + if (openStart) + { addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content); } + addRange($start, $end, depth, content); + if (openEnd) + { addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content); } + } + addRange($to, null, depth, content); + return new Fragment(content) + } + + function replaceTwoWay($from, $to, depth) { + var content = []; + addRange(null, $from, depth, content); + if ($from.depth > depth) { + var type = joinable($from, $to, depth + 1); + addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content); + } + addRange($to, null, depth, content); + return new Fragment(content) + } + + function prepareSliceForReplace(slice, $along) { + var extra = $along.depth - slice.openStart, parent = $along.node(extra); + var node = parent.copy(slice.content); + for (var i = extra - 1; i >= 0; i--) + { node = $along.node(i).copy(Fragment.from(node)); } + return {start: node.resolveNoCache(slice.openStart + extra), + end: node.resolveNoCache(node.content.size - slice.openEnd - extra)} + } + + // ::- You can [_resolve_](#model.Node.resolve) a position to get more + // information about it. Objects of this class represent such a + // resolved position, providing various pieces of context information, + // and some helper methods. + // + // Throughout this interface, methods that take an optional `depth` + // parameter will interpret undefined as `this.depth` and negative + // numbers as `this.depth + value`. + var ResolvedPos = function ResolvedPos(pos, path, parentOffset) { + // :: number The position that was resolved. + this.pos = pos; + this.path = path; + // :: number + // The number of levels the parent node is from the root. If this + // position points directly into the root node, it is 0. If it + // points into a top-level paragraph, 1, and so on. + this.depth = path.length / 3 - 1; + // :: number The offset this position has into its parent node. + this.parentOffset = parentOffset; + }; + + var prototypeAccessors$2 = { parent: { configurable: true },doc: { configurable: true },textOffset: { configurable: true },nodeAfter: { configurable: true },nodeBefore: { configurable: true } }; + + ResolvedPos.prototype.resolveDepth = function resolveDepth (val) { + if (val == null) { return this.depth } + if (val < 0) { return this.depth + val } + return val + }; + + // :: Node + // The parent node that the position points into. Note that even if + // a position points into a text node, that node is not considered + // the parent—text nodes are ‘flat’ in this model, and have no content. + prototypeAccessors$2.parent.get = function () { return this.node(this.depth) }; + + // :: Node + // The root node in which the position was resolved. + prototypeAccessors$2.doc.get = function () { return this.node(0) }; + + // :: (?number) → Node + // The ancestor node at the given level. `p.node(p.depth)` is the + // same as `p.parent`. + ResolvedPos.prototype.node = function node (depth) { return this.path[this.resolveDepth(depth) * 3] }; + + // :: (?number) → number + // The index into the ancestor at the given level. If this points at + // the 3rd node in the 2nd paragraph on the top level, for example, + // `p.index(0)` is 1 and `p.index(1)` is 2. + ResolvedPos.prototype.index = function index (depth) { return this.path[this.resolveDepth(depth) * 3 + 1] }; + + // :: (?number) → number + // The index pointing after this position into the ancestor at the + // given level. + ResolvedPos.prototype.indexAfter = function indexAfter (depth) { + depth = this.resolveDepth(depth); + return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1) + }; + + // :: (?number) → number + // The (absolute) position at the start of the node at the given + // level. + ResolvedPos.prototype.start = function start (depth) { + depth = this.resolveDepth(depth); + return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1 + }; + + // :: (?number) → number + // The (absolute) position at the end of the node at the given + // level. + ResolvedPos.prototype.end = function end (depth) { + depth = this.resolveDepth(depth); + return this.start(depth) + this.node(depth).content.size + }; + + // :: (?number) → number + // The (absolute) position directly before the wrapping node at the + // given level, or, when `depth` is `this.depth + 1`, the original + // position. + ResolvedPos.prototype.before = function before (depth) { + depth = this.resolveDepth(depth); + if (!depth) { throw new RangeError("There is no position before the top-level node") } + return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + }; + + // :: (?number) → number + // The (absolute) position directly after the wrapping node at the + // given level, or the original position when `depth` is `this.depth + 1`. + ResolvedPos.prototype.after = function after (depth) { + depth = this.resolveDepth(depth); + if (!depth) { throw new RangeError("There is no position after the top-level node") } + return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize + }; + + // :: number + // When this position points into a text node, this returns the + // distance between the position and the start of the text node. + // Will be zero for positions that point between nodes. + prototypeAccessors$2.textOffset.get = function () { return this.pos - this.path[this.path.length - 1] }; + + // :: ?Node + // Get the node directly after the position, if any. If the position + // points into a text node, only the part of that node after the + // position is returned. + prototypeAccessors$2.nodeAfter.get = function () { + var parent = this.parent, index = this.index(this.depth); + if (index == parent.childCount) { return null } + var dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index); + return dOff ? parent.child(index).cut(dOff) : child + }; + + // :: ?Node + // Get the node directly before the position, if any. If the + // position points into a text node, only the part of that node + // before the position is returned. + prototypeAccessors$2.nodeBefore.get = function () { + var index = this.index(this.depth); + var dOff = this.pos - this.path[this.path.length - 1]; + if (dOff) { return this.parent.child(index).cut(0, dOff) } + return index == 0 ? null : this.parent.child(index - 1) + }; + + // :: (number, ?number) → number + // Get the position at the given index in the parent node at the + // given depth (which defaults to `this.depth`). + ResolvedPos.prototype.posAtIndex = function posAtIndex (index, depth) { + depth = this.resolveDepth(depth); + var node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1; + for (var i = 0; i < index; i++) { pos += node.child(i).nodeSize; } + return pos + }; + + // :: () → [Mark] + // Get the marks at this position, factoring in the surrounding + // marks' [`inclusive`](#model.MarkSpec.inclusive) property. If the + // position is at the start of a non-empty node, the marks of the + // node after it (if any) are returned. + ResolvedPos.prototype.marks = function marks () { + var parent = this.parent, index = this.index(); + + // In an empty parent, return the empty array + if (parent.content.size == 0) { return Mark.none } + + // When inside a text node, just return the text node's marks + if (this.textOffset) { return parent.child(index).marks } + + var main = parent.maybeChild(index - 1), other = parent.maybeChild(index); + // If the `after` flag is true of there is no node before, make + // the node after this position the main reference. + if (!main) { var tmp = main; main = other; other = tmp; } + + // Use all marks in the main node, except those that have + // `inclusive` set to false and are not present in the other node. + var marks = main.marks; + for (var i = 0; i < marks.length; i++) + { if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks))) + { marks = marks[i--].removeFromSet(marks); } } + + return marks + }; + + // :: (ResolvedPos) → ?[Mark] + // Get the marks after the current position, if any, except those + // that are non-inclusive and not present at position `$end`. This + // is mostly useful for getting the set of marks to preserve after a + // deletion. Will return `null` if this position is at the end of + // its parent node or its parent node isn't a textblock (in which + // case no marks should be preserved). + ResolvedPos.prototype.marksAcross = function marksAcross ($end) { + var after = this.parent.maybeChild(this.index()); + if (!after || !after.isInline) { return null } + + var marks = after.marks, next = $end.parent.maybeChild($end.index()); + for (var i = 0; i < marks.length; i++) + { if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks))) + { marks = marks[i--].removeFromSet(marks); } } + return marks + }; + + // :: (number) → number + // The depth up to which this position and the given (non-resolved) + // position share the same parent nodes. + ResolvedPos.prototype.sharedDepth = function sharedDepth (pos) { + for (var depth = this.depth; depth > 0; depth--) + { if (this.start(depth) <= pos && this.end(depth) >= pos) { return depth } } + return 0 + }; + + // :: (?ResolvedPos, ?(Node) → bool) → ?NodeRange + // Returns a range based on the place where this position and the + // given position diverge around block content. If both point into + // the same textblock, for example, a range around that textblock + // will be returned. If they point into different blocks, the range + // around those blocks in their shared ancestor is returned. You can + // pass in an optional predicate that will be called with a parent + // node to see if a range into that parent is acceptable. + ResolvedPos.prototype.blockRange = function blockRange (other, pred) { + if ( other === void 0 ) other = this; + + if (other.pos < this.pos) { return other.blockRange(this) } + for (var d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--) + { if (other.pos <= this.end(d) && (!pred || pred(this.node(d)))) + { return new NodeRange(this, other, d) } } + }; + + // :: (ResolvedPos) → bool + // Query whether the given position shares the same parent node. + ResolvedPos.prototype.sameParent = function sameParent (other) { + return this.pos - this.parentOffset == other.pos - other.parentOffset + }; + + // :: (ResolvedPos) → ResolvedPos + // Return the greater of this and the given position. + ResolvedPos.prototype.max = function max (other) { + return other.pos > this.pos ? other : this + }; + + // :: (ResolvedPos) → ResolvedPos + // Return the smaller of this and the given position. + ResolvedPos.prototype.min = function min (other) { + return other.pos < this.pos ? other : this + }; + + ResolvedPos.prototype.toString = function toString () { + var str = ""; + for (var i = 1; i <= this.depth; i++) + { str += (str ? "/" : "") + this.node(i).type.name + "_" + this.index(i - 1); } + return str + ":" + this.parentOffset + }; + + ResolvedPos.resolve = function resolve (doc, pos) { + if (!(pos >= 0 && pos <= doc.content.size)) { throw new RangeError("Position " + pos + " out of range") } + var path = []; + var start = 0, parentOffset = pos; + for (var node = doc;;) { + var ref = node.content.findIndex(parentOffset); + var index = ref.index; + var offset = ref.offset; + var rem = parentOffset - offset; + path.push(node, index, start + offset); + if (!rem) { break } + node = node.child(index); + if (node.isText) { break } + parentOffset = rem - 1; + start += offset + 1; + } + return new ResolvedPos(pos, path, parentOffset) + }; + + ResolvedPos.resolveCached = function resolveCached (doc, pos) { + for (var i = 0; i < resolveCache.length; i++) { + var cached = resolveCache[i]; + if (cached.pos == pos && cached.doc == doc) { return cached } + } + var result = resolveCache[resolveCachePos] = ResolvedPos.resolve(doc, pos); + resolveCachePos = (resolveCachePos + 1) % resolveCacheSize; + return result + }; + + Object.defineProperties( ResolvedPos.prototype, prototypeAccessors$2 ); + + var resolveCache = [], resolveCachePos = 0, resolveCacheSize = 12; + + // ::- Represents a flat range of content, i.e. one that starts and + // ends in the same node. + var NodeRange = function NodeRange($from, $to, depth) { + // :: ResolvedPos A resolved position along the start of the + // content. May have a `depth` greater than this object's `depth` + // property, since these are the positions that were used to + // compute the range, not re-resolved positions directly at its + // boundaries. + this.$from = $from; + // :: ResolvedPos A position along the end of the content. See + // caveat for [`$from`](#model.NodeRange.$from). + this.$to = $to; + // :: number The depth of the node that this range points into. + this.depth = depth; + }; + + var prototypeAccessors$1$1 = { start: { configurable: true },end: { configurable: true },parent: { configurable: true },startIndex: { configurable: true },endIndex: { configurable: true } }; + + // :: number The position at the start of the range. + prototypeAccessors$1$1.start.get = function () { return this.$from.before(this.depth + 1) }; + // :: number The position at the end of the range. + prototypeAccessors$1$1.end.get = function () { return this.$to.after(this.depth + 1) }; + + // :: Node The parent node that the range points into. + prototypeAccessors$1$1.parent.get = function () { return this.$from.node(this.depth) }; + // :: number The start index of the range in the parent node. + prototypeAccessors$1$1.startIndex.get = function () { return this.$from.index(this.depth) }; + // :: number The end index of the range in the parent node. + prototypeAccessors$1$1.endIndex.get = function () { return this.$to.indexAfter(this.depth) }; + + Object.defineProperties( NodeRange.prototype, prototypeAccessors$1$1 ); + + var emptyAttrs = Object.create(null); + + // ::- This class represents a node in the tree that makes up a + // ProseMirror document. So a document is an instance of `Node`, with + // children that are also instances of `Node`. + // + // Nodes are persistent data structures. Instead of changing them, you + // create new ones with the content you want. Old ones keep pointing + // at the old document shape. This is made cheaper by sharing + // structure between the old and new data as much as possible, which a + // tree shape like this (without back pointers) makes easy. + // + // **Do not** directly mutate the properties of a `Node` object. See + // [the guide](/docs/guide/#doc) for more information. + var Node$1 = function Node(type, attrs, content, marks) { + // :: NodeType + // The type of node that this is. + this.type = type; + + // :: Object + // An object mapping attribute names to values. The kind of + // attributes allowed and required are + // [determined](#model.NodeSpec.attrs) by the node type. + this.attrs = attrs; + + // :: Fragment + // A container holding the node's children. + this.content = content || Fragment.empty; + + // :: [Mark] + // The marks (things like whether it is emphasized or part of a + // link) applied to this node. + this.marks = marks || Mark.none; + }; + + var prototypeAccessors$3 = { nodeSize: { configurable: true },childCount: { configurable: true },textContent: { configurable: true },firstChild: { configurable: true },lastChild: { configurable: true },isBlock: { configurable: true },isTextblock: { configurable: true },inlineContent: { configurable: true },isInline: { configurable: true },isText: { configurable: true },isLeaf: { configurable: true },isAtom: { configurable: true } }; + + // text:: ?string + // For text nodes, this contains the node's text content. + + // :: number + // The size of this node, as defined by the integer-based [indexing + // scheme](/docs/guide/#doc.indexing). For text nodes, this is the + // amount of characters. For other leaf nodes, it is one. For + // non-leaf nodes, it is the size of the content plus two (the start + // and end token). + prototypeAccessors$3.nodeSize.get = function () { return this.isLeaf ? 1 : 2 + this.content.size }; + + // :: number + // The number of children that the node has. + prototypeAccessors$3.childCount.get = function () { return this.content.childCount }; + + // :: (number) → Node + // Get the child node at the given index. Raises an error when the + // index is out of range. + Node$1.prototype.child = function child (index) { return this.content.child(index) }; + + // :: (number) → ?Node + // Get the child node at the given index, if it exists. + Node$1.prototype.maybeChild = function maybeChild (index) { return this.content.maybeChild(index) }; + + // :: ((node: Node, offset: number, index: number)) + // Call `f` for every child node, passing the node, its offset + // into this parent node, and its index. + Node$1.prototype.forEach = function forEach (f) { this.content.forEach(f); }; + + // :: (number, number, (node: Node, pos: number, parent: Node, index: number) → ?bool, ?number) + // Invoke a callback for all descendant nodes recursively between + // the given two positions that are relative to start of this node's + // content. The callback is invoked with the node, its + // parent-relative position, its parent node, and its child index. + // When the callback returns false for a given node, that node's + // children will not be recursed over. The last parameter can be + // used to specify a starting position to count from. + Node$1.prototype.nodesBetween = function nodesBetween (from, to, f, startPos) { + if ( startPos === void 0 ) startPos = 0; + + this.content.nodesBetween(from, to, f, startPos, this); + }; + + // :: ((node: Node, pos: number, parent: Node) → ?bool) + // Call the given callback for every descendant node. Doesn't + // descend into a node when the callback returns `false`. + Node$1.prototype.descendants = function descendants (f) { + this.nodesBetween(0, this.content.size, f); + }; + + // :: string + // Concatenates all the text nodes found in this fragment and its + // children. + prototypeAccessors$3.textContent.get = function () { return this.textBetween(0, this.content.size, "") }; + + // :: (number, number, ?string, ?string) → string + // Get all text between positions `from` and `to`. When + // `blockSeparator` is given, it will be inserted whenever a new + // block node is started. When `leafText` is given, it'll be + // inserted for every non-text leaf node encountered. + Node$1.prototype.textBetween = function textBetween (from, to, blockSeparator, leafText) { + return this.content.textBetween(from, to, blockSeparator, leafText) + }; + + // :: ?Node + // Returns this node's first child, or `null` if there are no + // children. + prototypeAccessors$3.firstChild.get = function () { return this.content.firstChild }; + + // :: ?Node + // Returns this node's last child, or `null` if there are no + // children. + prototypeAccessors$3.lastChild.get = function () { return this.content.lastChild }; + + // :: (Node) → bool + // Test whether two nodes represent the same piece of document. + Node$1.prototype.eq = function eq (other) { + return this == other || (this.sameMarkup(other) && this.content.eq(other.content)) + }; + + // :: (Node) → bool + // Compare the markup (type, attributes, and marks) of this node to + // those of another. Returns `true` if both have the same markup. + Node$1.prototype.sameMarkup = function sameMarkup (other) { + return this.hasMarkup(other.type, other.attrs, other.marks) + }; + + // :: (NodeType, ?Object, ?[Mark]) → bool + // Check whether this node's markup correspond to the given type, + // attributes, and marks. + Node$1.prototype.hasMarkup = function hasMarkup (type, attrs, marks) { + return this.type == type && + compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) && + Mark.sameSet(this.marks, marks || Mark.none) + }; + + // :: (?Fragment) → Node + // Create a new node with the same markup as this node, containing + // the given content (or empty, if no content is given). + Node$1.prototype.copy = function copy (content) { + if ( content === void 0 ) content = null; + + if (content == this.content) { return this } + return new this.constructor(this.type, this.attrs, content, this.marks) + }; + + // :: ([Mark]) → Node + // Create a copy of this node, with the given set of marks instead + // of the node's own marks. + Node$1.prototype.mark = function mark (marks) { + return marks == this.marks ? this : new this.constructor(this.type, this.attrs, this.content, marks) + }; + + // :: (number, ?number) → Node + // Create a copy of this node with only the content between the + // given positions. If `to` is not given, it defaults to the end of + // the node. + Node$1.prototype.cut = function cut (from, to) { + if (from == 0 && to == this.content.size) { return this } + return this.copy(this.content.cut(from, to)) + }; + + // :: (number, ?number) → Slice + // Cut out the part of the document between the given positions, and + // return it as a `Slice` object. + Node$1.prototype.slice = function slice (from, to, includeParents) { + if ( to === void 0 ) to = this.content.size; + if ( includeParents === void 0 ) includeParents = false; + + if (from == to) { return Slice.empty } + + var $from = this.resolve(from), $to = this.resolve(to); + var depth = includeParents ? 0 : $from.sharedDepth(to); + var start = $from.start(depth), node = $from.node(depth); + var content = node.content.cut($from.pos - start, $to.pos - start); + return new Slice(content, $from.depth - depth, $to.depth - depth) + }; + + // :: (number, number, Slice) → Node + // Replace the part of the document between the given positions with + // the given slice. The slice must 'fit', meaning its open sides + // must be able to connect to the surrounding content, and its + // content nodes must be valid children for the node they are placed + // into. If any of this is violated, an error of type + // [`ReplaceError`](#model.ReplaceError) is thrown. + Node$1.prototype.replace = function replace$1 (from, to, slice) { + return replace(this.resolve(from), this.resolve(to), slice) + }; + + // :: (number) → ?Node + // Find the node directly after the given position. + Node$1.prototype.nodeAt = function nodeAt (pos) { + for (var node = this;;) { + var ref = node.content.findIndex(pos); + var index = ref.index; + var offset = ref.offset; + node = node.maybeChild(index); + if (!node) { return null } + if (offset == pos || node.isText) { return node } + pos -= offset + 1; + } + }; + + // :: (number) → {node: ?Node, index: number, offset: number} + // Find the (direct) child node after the given offset, if any, + // and return it along with its index and offset relative to this + // node. + Node$1.prototype.childAfter = function childAfter (pos) { + var ref = this.content.findIndex(pos); + var index = ref.index; + var offset = ref.offset; + return {node: this.content.maybeChild(index), index: index, offset: offset} + }; + + // :: (number) → {node: ?Node, index: number, offset: number} + // Find the (direct) child node before the given offset, if any, + // and return it along with its index and offset relative to this + // node. + Node$1.prototype.childBefore = function childBefore (pos) { + if (pos == 0) { return {node: null, index: 0, offset: 0} } + var ref = this.content.findIndex(pos); + var index = ref.index; + var offset = ref.offset; + if (offset < pos) { return {node: this.content.child(index), index: index, offset: offset} } + var node = this.content.child(index - 1); + return {node: node, index: index - 1, offset: offset - node.nodeSize} + }; + + // :: (number) → ResolvedPos + // Resolve the given position in the document, returning an + // [object](#model.ResolvedPos) with information about its context. + Node$1.prototype.resolve = function resolve (pos) { return ResolvedPos.resolveCached(this, pos) }; + + Node$1.prototype.resolveNoCache = function resolveNoCache (pos) { return ResolvedPos.resolve(this, pos) }; + + // :: (number, number, union) → bool + // Test whether a given mark or mark type occurs in this document + // between the two given positions. + Node$1.prototype.rangeHasMark = function rangeHasMark (from, to, type) { + var found = false; + if (to > from) { this.nodesBetween(from, to, function (node) { + if (type.isInSet(node.marks)) { found = true; } + return !found + }); } + return found + }; + + // :: bool + // True when this is a block (non-inline node) + prototypeAccessors$3.isBlock.get = function () { return this.type.isBlock }; + + // :: bool + // True when this is a textblock node, a block node with inline + // content. + prototypeAccessors$3.isTextblock.get = function () { return this.type.isTextblock }; + + // :: bool + // True when this node allows inline content. + prototypeAccessors$3.inlineContent.get = function () { return this.type.inlineContent }; + + // :: bool + // True when this is an inline node (a text node or a node that can + // appear among text). + prototypeAccessors$3.isInline.get = function () { return this.type.isInline }; + + // :: bool + // True when this is a text node. + prototypeAccessors$3.isText.get = function () { return this.type.isText }; + + // :: bool + // True when this is a leaf node. + prototypeAccessors$3.isLeaf.get = function () { return this.type.isLeaf }; + + // :: bool + // True when this is an atom, i.e. when it does not have directly + // editable content. This is usually the same as `isLeaf`, but can + // be configured with the [`atom` property](#model.NodeSpec.atom) on + // a node's spec (typically used when the node is displayed as an + // uneditable [node view](#view.NodeView)). + prototypeAccessors$3.isAtom.get = function () { return this.type.isAtom }; + + // :: () → string + // Return a string representation of this node for debugging + // purposes. + Node$1.prototype.toString = function toString () { + if (this.type.spec.toDebugString) { return this.type.spec.toDebugString(this) } + var name = this.type.name; + if (this.content.size) + { name += "(" + this.content.toStringInner() + ")"; } + return wrapMarks(this.marks, name) + }; + + // :: (number) → ContentMatch + // Get the content match in this node at the given index. + Node$1.prototype.contentMatchAt = function contentMatchAt (index) { + var match = this.type.contentMatch.matchFragment(this.content, 0, index); + if (!match) { throw new Error("Called contentMatchAt on a node with invalid content") } + return match + }; + + // :: (number, number, ?Fragment, ?number, ?number) → bool + // Test whether replacing the range between `from` and `to` (by + // child index) with the given replacement fragment (which defaults + // to the empty fragment) would leave the node's content valid. You + // can optionally pass `start` and `end` indices into the + // replacement fragment. + Node$1.prototype.canReplace = function canReplace (from, to, replacement, start, end) { + if ( replacement === void 0 ) replacement = Fragment.empty; + if ( start === void 0 ) start = 0; + if ( end === void 0 ) end = replacement.childCount; + + var one = this.contentMatchAt(from).matchFragment(replacement, start, end); + var two = one && one.matchFragment(this.content, to); + if (!two || !two.validEnd) { return false } + for (var i = start; i < end; i++) { if (!this.type.allowsMarks(replacement.child(i).marks)) { return false } } + return true + }; + + // :: (number, number, NodeType, ?[Mark]) → bool + // Test whether replacing the range `from` to `to` (by index) with a + // node of the given type would leave the node's content valid. + Node$1.prototype.canReplaceWith = function canReplaceWith (from, to, type, marks) { + if (marks && !this.type.allowsMarks(marks)) { return false } + var start = this.contentMatchAt(from).matchType(type); + var end = start && start.matchFragment(this.content, to); + return end ? end.validEnd : false + }; + + // :: (Node) → bool + // Test whether the given node's content could be appended to this + // node. If that node is empty, this will only return true if there + // is at least one node type that can appear in both nodes (to avoid + // merging completely incompatible nodes). + Node$1.prototype.canAppend = function canAppend (other) { + if (other.content.size) { return this.canReplace(this.childCount, this.childCount, other.content) } + else { return this.type.compatibleContent(other.type) } + }; + + // :: () + // Check whether this node and its descendants conform to the + // schema, and raise error when they do not. + Node$1.prototype.check = function check () { + if (!this.type.validContent(this.content)) + { throw new RangeError(("Invalid content for node " + (this.type.name) + ": " + (this.content.toString().slice(0, 50)))) } + this.content.forEach(function (node) { return node.check(); }); + }; + + // :: () → Object + // Return a JSON-serializeable representation of this node. + Node$1.prototype.toJSON = function toJSON () { + var obj = {type: this.type.name}; + for (var _ in this.attrs) { + obj.attrs = this.attrs; + break + } + if (this.content.size) + { obj.content = this.content.toJSON(); } + if (this.marks.length) + { obj.marks = this.marks.map(function (n) { return n.toJSON(); }); } + return obj + }; + + // :: (Schema, Object) → Node + // Deserialize a node from its JSON representation. + Node$1.fromJSON = function fromJSON (schema, json) { + if (!json) { throw new RangeError("Invalid input for Node.fromJSON") } + var marks = null; + if (json.marks) { + if (!Array.isArray(json.marks)) { throw new RangeError("Invalid mark data for Node.fromJSON") } + marks = json.marks.map(schema.markFromJSON); + } + if (json.type == "text") { + if (typeof json.text != "string") { throw new RangeError("Invalid text node in JSON") } + return schema.text(json.text, marks) + } + var content = Fragment.fromJSON(schema, json.content); + return schema.nodeType(json.type).create(json.attrs, content, marks) + }; + + Object.defineProperties( Node$1.prototype, prototypeAccessors$3 ); + + var TextNode = /*@__PURE__*/(function (Node) { + function TextNode(type, attrs, content, marks) { + Node.call(this, type, attrs, null, marks); + + if (!content) { throw new RangeError("Empty text nodes are not allowed") } + + this.text = content; + } + + if ( Node ) TextNode.__proto__ = Node; + TextNode.prototype = Object.create( Node && Node.prototype ); + TextNode.prototype.constructor = TextNode; + + var prototypeAccessors$1 = { textContent: { configurable: true },nodeSize: { configurable: true } }; + + TextNode.prototype.toString = function toString () { + if (this.type.spec.toDebugString) { return this.type.spec.toDebugString(this) } + return wrapMarks(this.marks, JSON.stringify(this.text)) + }; + + prototypeAccessors$1.textContent.get = function () { return this.text }; + + TextNode.prototype.textBetween = function textBetween (from, to) { return this.text.slice(from, to) }; + + prototypeAccessors$1.nodeSize.get = function () { return this.text.length }; + + TextNode.prototype.mark = function mark (marks) { + return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks) + }; + + TextNode.prototype.withText = function withText (text) { + if (text == this.text) { return this } + return new TextNode(this.type, this.attrs, text, this.marks) + }; + + TextNode.prototype.cut = function cut (from, to) { + if ( from === void 0 ) from = 0; + if ( to === void 0 ) to = this.text.length; + + if (from == 0 && to == this.text.length) { return this } + return this.withText(this.text.slice(from, to)) + }; + + TextNode.prototype.eq = function eq (other) { + return this.sameMarkup(other) && this.text == other.text + }; + + TextNode.prototype.toJSON = function toJSON () { + var base = Node.prototype.toJSON.call(this); + base.text = this.text; + return base + }; + + Object.defineProperties( TextNode.prototype, prototypeAccessors$1 ); + + return TextNode; + }(Node$1)); + + function wrapMarks(marks, str) { + for (var i = marks.length - 1; i >= 0; i--) + { str = marks[i].type.name + "(" + str + ")"; } + return str + } + + // ::- Instances of this class represent a match state of a node + // type's [content expression](#model.NodeSpec.content), and can be + // used to find out whether further content matches here, and whether + // a given position is a valid end of the node. + var ContentMatch = function ContentMatch(validEnd) { + // :: bool + // True when this match state represents a valid end of the node. + this.validEnd = validEnd; + this.next = []; + this.wrapCache = []; + }; + + var prototypeAccessors$4 = { inlineContent: { configurable: true },defaultType: { configurable: true },edgeCount: { configurable: true } }; + + ContentMatch.parse = function parse (string, nodeTypes) { + var stream = new TokenStream(string, nodeTypes); + if (stream.next == null) { return ContentMatch.empty } + var expr = parseExpr(stream); + if (stream.next) { stream.err("Unexpected trailing text"); } + var match = dfa(nfa(expr)); + checkForDeadEnds(match, stream); + return match + }; + + // :: (NodeType) → ?ContentMatch + // Match a node type, returning a match after that node if + // successful. + ContentMatch.prototype.matchType = function matchType (type) { + for (var i = 0; i < this.next.length; i += 2) + { if (this.next[i] == type) { return this.next[i + 1] } } + return null + }; + + // :: (Fragment, ?number, ?number) → ?ContentMatch + // Try to match a fragment. Returns the resulting match when + // successful. + ContentMatch.prototype.matchFragment = function matchFragment (frag, start, end) { + if ( start === void 0 ) start = 0; + if ( end === void 0 ) end = frag.childCount; + + var cur = this; + for (var i = start; cur && i < end; i++) + { cur = cur.matchType(frag.child(i).type); } + return cur + }; + + prototypeAccessors$4.inlineContent.get = function () { + var first = this.next[0]; + return first ? first.isInline : false + }; + + // :: ?NodeType + // Get the first matching node type at this match position that can + // be generated. + prototypeAccessors$4.defaultType.get = function () { + for (var i = 0; i < this.next.length; i += 2) { + var type = this.next[i]; + if (!(type.isText || type.hasRequiredAttrs())) { return type } + } + }; + + ContentMatch.prototype.compatible = function compatible (other) { + for (var i = 0; i < this.next.length; i += 2) + { for (var j = 0; j < other.next.length; j += 2) + { if (this.next[i] == other.next[j]) { return true } } } + return false + }; + + // :: (Fragment, bool, ?number) → ?Fragment + // Try to match the given fragment, and if that fails, see if it can + // be made to match by inserting nodes in front of it. When + // successful, return a fragment of inserted nodes (which may be + // empty if nothing had to be inserted). When `toEnd` is true, only + // return a fragment if the resulting match goes to the end of the + // content expression. + ContentMatch.prototype.fillBefore = function fillBefore (after, toEnd, startIndex) { + if ( toEnd === void 0 ) toEnd = false; + if ( startIndex === void 0 ) startIndex = 0; + + var seen = [this]; + function search(match, types) { + var finished = match.matchFragment(after, startIndex); + if (finished && (!toEnd || finished.validEnd)) + { return Fragment.from(types.map(function (tp) { return tp.createAndFill(); })) } + + for (var i = 0; i < match.next.length; i += 2) { + var type = match.next[i], next = match.next[i + 1]; + if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) { + seen.push(next); + var found = search(next, types.concat(type)); + if (found) { return found } + } + } + } + + return search(this, []) + }; + + // :: (NodeType) → ?[NodeType] + // Find a set of wrapping node types that would allow a node of the + // given type to appear at this position. The result may be empty + // (when it fits directly) and will be null when no such wrapping + // exists. + ContentMatch.prototype.findWrapping = function findWrapping (target) { + for (var i = 0; i < this.wrapCache.length; i += 2) + { if (this.wrapCache[i] == target) { return this.wrapCache[i + 1] } } + var computed = this.computeWrapping(target); + this.wrapCache.push(target, computed); + return computed + }; + + ContentMatch.prototype.computeWrapping = function computeWrapping (target) { + var seen = Object.create(null), active = [{match: this, type: null, via: null}]; + while (active.length) { + var current = active.shift(), match = current.match; + if (match.matchType(target)) { + var result = []; + for (var obj = current; obj.type; obj = obj.via) + { result.push(obj.type); } + return result.reverse() + } + for (var i = 0; i < match.next.length; i += 2) { + var type = match.next[i]; + if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || match.next[i + 1].validEnd)) { + active.push({match: type.contentMatch, type: type, via: current}); + seen[type.name] = true; + } + } + } + }; + + // :: number + // The number of outgoing edges this node has in the finite + // automaton that describes the content expression. + prototypeAccessors$4.edgeCount.get = function () { + return this.next.length >> 1 + }; + + // :: (number) → {type: NodeType, next: ContentMatch} + // Get the _n_​th outgoing edge from this node in the finite + // automaton that describes the content expression. + ContentMatch.prototype.edge = function edge (n) { + var i = n << 1; + if (i >= this.next.length) { throw new RangeError(("There's no " + n + "th edge in this content match")) } + return {type: this.next[i], next: this.next[i + 1]} + }; + + ContentMatch.prototype.toString = function toString () { + var seen = []; + function scan(m) { + seen.push(m); + for (var i = 1; i < m.next.length; i += 2) + { if (seen.indexOf(m.next[i]) == -1) { scan(m.next[i]); } } + } + scan(this); + return seen.map(function (m, i) { + var out = i + (m.validEnd ? "*" : " ") + " "; + for (var i$1 = 0; i$1 < m.next.length; i$1 += 2) + { out += (i$1 ? ", " : "") + m.next[i$1].name + "->" + seen.indexOf(m.next[i$1 + 1]); } + return out + }).join("\n") + }; + + Object.defineProperties( ContentMatch.prototype, prototypeAccessors$4 ); + + ContentMatch.empty = new ContentMatch(true); + + var TokenStream = function TokenStream(string, nodeTypes) { + this.string = string; + this.nodeTypes = nodeTypes; + this.inline = null; + this.pos = 0; + this.tokens = string.split(/\s*(?=\b|\W|$)/); + if (this.tokens[this.tokens.length - 1] == "") { this.tokens.pop(); } + if (this.tokens[0] == "") { this.tokens.unshift(); } + }; + + var prototypeAccessors$1$2 = { next: { configurable: true } }; + + prototypeAccessors$1$2.next.get = function () { return this.tokens[this.pos] }; + + TokenStream.prototype.eat = function eat (tok) { return this.next == tok && (this.pos++ || true) }; + + TokenStream.prototype.err = function err (str) { throw new SyntaxError(str + " (in content expression '" + this.string + "')") }; + + Object.defineProperties( TokenStream.prototype, prototypeAccessors$1$2 ); + + function parseExpr(stream) { + var exprs = []; + do { exprs.push(parseExprSeq(stream)); } + while (stream.eat("|")) + return exprs.length == 1 ? exprs[0] : {type: "choice", exprs: exprs} + } + + function parseExprSeq(stream) { + var exprs = []; + do { exprs.push(parseExprSubscript(stream)); } + while (stream.next && stream.next != ")" && stream.next != "|") + return exprs.length == 1 ? exprs[0] : {type: "seq", exprs: exprs} + } + + function parseExprSubscript(stream) { + var expr = parseExprAtom(stream); + for (;;) { + if (stream.eat("+")) + { expr = {type: "plus", expr: expr}; } + else if (stream.eat("*")) + { expr = {type: "star", expr: expr}; } + else if (stream.eat("?")) + { expr = {type: "opt", expr: expr}; } + else if (stream.eat("{")) + { expr = parseExprRange(stream, expr); } + else { break } + } + return expr + } + + function parseNum(stream) { + if (/\D/.test(stream.next)) { stream.err("Expected number, got '" + stream.next + "'"); } + var result = Number(stream.next); + stream.pos++; + return result + } + + function parseExprRange(stream, expr) { + var min = parseNum(stream), max = min; + if (stream.eat(",")) { + if (stream.next != "}") { max = parseNum(stream); } + else { max = -1; } + } + if (!stream.eat("}")) { stream.err("Unclosed braced range"); } + return {type: "range", min: min, max: max, expr: expr} + } + + function resolveName(stream, name) { + var types = stream.nodeTypes, type = types[name]; + if (type) { return [type] } + var result = []; + for (var typeName in types) { + var type$1 = types[typeName]; + if (type$1.groups.indexOf(name) > -1) { result.push(type$1); } + } + if (result.length == 0) { stream.err("No node type or group '" + name + "' found"); } + return result + } + + function parseExprAtom(stream) { + if (stream.eat("(")) { + var expr = parseExpr(stream); + if (!stream.eat(")")) { stream.err("Missing closing paren"); } + return expr + } else if (!/\W/.test(stream.next)) { + var exprs = resolveName(stream, stream.next).map(function (type) { + if (stream.inline == null) { stream.inline = type.isInline; } + else if (stream.inline != type.isInline) { stream.err("Mixing inline and block content"); } + return {type: "name", value: type} + }); + stream.pos++; + return exprs.length == 1 ? exprs[0] : {type: "choice", exprs: exprs} + } else { + stream.err("Unexpected token '" + stream.next + "'"); + } + } + + // The code below helps compile a regular-expression-like language + // into a deterministic finite automaton. For a good introduction to + // these concepts, see https://swtch.com/~rsc/regexp/regexp1.html + + // : (Object) → [[{term: ?any, to: number}]] + // Construct an NFA from an expression as returned by the parser. The + // NFA is represented as an array of states, which are themselves + // arrays of edges, which are `{term, to}` objects. The first state is + // the entry state and the last node is the success state. + // + // Note that unlike typical NFAs, the edge ordering in this one is + // significant, in that it is used to contruct filler content when + // necessary. + function nfa(expr) { + var nfa = [[]]; + connect(compile(expr, 0), node()); + return nfa + + function node() { return nfa.push([]) - 1 } + function edge(from, to, term) { + var edge = {term: term, to: to}; + nfa[from].push(edge); + return edge + } + function connect(edges, to) { edges.forEach(function (edge) { return edge.to = to; }); } + + function compile(expr, from) { + if (expr.type == "choice") { + return expr.exprs.reduce(function (out, expr) { return out.concat(compile(expr, from)); }, []) + } else if (expr.type == "seq") { + for (var i = 0;; i++) { + var next = compile(expr.exprs[i], from); + if (i == expr.exprs.length - 1) { return next } + connect(next, from = node()); + } + } else if (expr.type == "star") { + var loop = node(); + edge(from, loop); + connect(compile(expr.expr, loop), loop); + return [edge(loop)] + } else if (expr.type == "plus") { + var loop$1 = node(); + connect(compile(expr.expr, from), loop$1); + connect(compile(expr.expr, loop$1), loop$1); + return [edge(loop$1)] + } else if (expr.type == "opt") { + return [edge(from)].concat(compile(expr.expr, from)) + } else if (expr.type == "range") { + var cur = from; + for (var i$1 = 0; i$1 < expr.min; i$1++) { + var next$1 = node(); + connect(compile(expr.expr, cur), next$1); + cur = next$1; + } + if (expr.max == -1) { + connect(compile(expr.expr, cur), cur); + } else { + for (var i$2 = expr.min; i$2 < expr.max; i$2++) { + var next$2 = node(); + edge(cur, next$2); + connect(compile(expr.expr, cur), next$2); + cur = next$2; + } + } + return [edge(cur)] + } else if (expr.type == "name") { + return [edge(from, null, expr.value)] + } + } + } + + function cmp(a, b) { return b - a } + + // Get the set of nodes reachable by null edges from `node`. Omit + // nodes with only a single null-out-edge, since they may lead to + // needless duplicated nodes. + function nullFrom(nfa, node) { + var result = []; + scan(node); + return result.sort(cmp) + + function scan(node) { + var edges = nfa[node]; + if (edges.length == 1 && !edges[0].term) { return scan(edges[0].to) } + result.push(node); + for (var i = 0; i < edges.length; i++) { + var ref = edges[i]; + var term = ref.term; + var to = ref.to; + if (!term && result.indexOf(to) == -1) { scan(to); } + } + } + } + + // : ([[{term: ?any, to: number}]]) → ContentMatch + // Compiles an NFA as produced by `nfa` into a DFA, modeled as a set + // of state objects (`ContentMatch` instances) with transitions + // between them. + function dfa(nfa) { + var labeled = Object.create(null); + return explore(nullFrom(nfa, 0)) + + function explore(states) { + var out = []; + states.forEach(function (node) { + nfa[node].forEach(function (ref) { + var term = ref.term; + var to = ref.to; + + if (!term) { return } + var known = out.indexOf(term), set = known > -1 && out[known + 1]; + nullFrom(nfa, to).forEach(function (node) { + if (!set) { out.push(term, set = []); } + if (set.indexOf(node) == -1) { set.push(node); } + }); + }); + }); + var state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1); + for (var i = 0; i < out.length; i += 2) { + var states$1 = out[i + 1].sort(cmp); + state.next.push(out[i], labeled[states$1.join(",")] || explore(states$1)); + } + return state + } + } + + function checkForDeadEnds(match, stream) { + for (var i = 0, work = [match]; i < work.length; i++) { + var state = work[i], dead = !state.validEnd, nodes = []; + for (var j = 0; j < state.next.length; j += 2) { + var node = state.next[j], next = state.next[j + 1]; + nodes.push(node.name); + if (dead && !(node.isText || node.hasRequiredAttrs())) { dead = false; } + if (work.indexOf(next) == -1) { work.push(next); } + } + if (dead) { stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)"); } + } + } + + // For node types where all attrs have a default value (or which don't + // have any attributes), build up a single reusable default attribute + // object, and use it for all nodes that don't specify specific + // attributes. + function defaultAttrs(attrs) { + var defaults = Object.create(null); + for (var attrName in attrs) { + var attr = attrs[attrName]; + if (!attr.hasDefault) { return null } + defaults[attrName] = attr.default; + } + return defaults + } + + function computeAttrs(attrs, value) { + var built = Object.create(null); + for (var name in attrs) { + var given = value && value[name]; + if (given === undefined) { + var attr = attrs[name]; + if (attr.hasDefault) { given = attr.default; } + else { throw new RangeError("No value supplied for attribute " + name) } + } + built[name] = given; + } + return built + } + + function initAttrs(attrs) { + var result = Object.create(null); + if (attrs) { for (var name in attrs) { result[name] = new Attribute(attrs[name]); } } + return result + } + + // ::- Node types are objects allocated once per `Schema` and used to + // [tag](#model.Node.type) `Node` instances. They contain information + // about the node type, such as its name and what kind of node it + // represents. + var NodeType = function NodeType(name, schema, spec) { + // :: string + // The name the node type has in this schema. + this.name = name; + + // :: Schema + // A link back to the `Schema` the node type belongs to. + this.schema = schema; + + // :: NodeSpec + // The spec that this type is based on + this.spec = spec; + + this.groups = spec.group ? spec.group.split(" ") : []; + this.attrs = initAttrs(spec.attrs); + + this.defaultAttrs = defaultAttrs(this.attrs); + + // :: ContentMatch + // The starting match of the node type's content expression. + this.contentMatch = null; + + // : ?[MarkType] + // The set of marks allowed in this node. `null` means all marks + // are allowed. + this.markSet = null; + + // :: bool + // True if this node type has inline content. + this.inlineContent = null; + + // :: bool + // True if this is a block type + this.isBlock = !(spec.inline || name == "text"); + + // :: bool + // True if this is the text node type. + this.isText = name == "text"; + }; + + var prototypeAccessors$5 = { isInline: { configurable: true },isTextblock: { configurable: true },isLeaf: { configurable: true },isAtom: { configurable: true } }; + + // :: bool + // True if this is an inline type. + prototypeAccessors$5.isInline.get = function () { return !this.isBlock }; + + // :: bool + // True if this is a textblock type, a block that contains inline + // content. + prototypeAccessors$5.isTextblock.get = function () { return this.isBlock && this.inlineContent }; + + // :: bool + // True for node types that allow no content. + prototypeAccessors$5.isLeaf.get = function () { return this.contentMatch == ContentMatch.empty }; + + // :: bool + // True when this node is an atom, i.e. when it does not have + // directly editable content. + prototypeAccessors$5.isAtom.get = function () { return this.isLeaf || this.spec.atom }; + + // :: () → bool + // Tells you whether this node type has any required attributes. + NodeType.prototype.hasRequiredAttrs = function hasRequiredAttrs () { + for (var n in this.attrs) { if (this.attrs[n].isRequired) { return true } } + return false + }; + + NodeType.prototype.compatibleContent = function compatibleContent (other) { + return this == other || this.contentMatch.compatible(other.contentMatch) + }; + + NodeType.prototype.computeAttrs = function computeAttrs$1 (attrs) { + if (!attrs && this.defaultAttrs) { return this.defaultAttrs } + else { return computeAttrs(this.attrs, attrs) } + }; + + // :: (?Object, ?union, ?[Mark]) → Node + // Create a `Node` of this type. The given attributes are + // checked and defaulted (you can pass `null` to use the type's + // defaults entirely, if no required attributes exist). `content` + // may be a `Fragment`, a node, an array of nodes, or + // `null`. Similarly `marks` may be `null` to default to the empty + // set of marks. + NodeType.prototype.create = function create (attrs, content, marks) { + if (this.isText) { throw new Error("NodeType.create can't construct text nodes") } + return new Node$1(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks)) + }; + + // :: (?Object, ?union, ?[Mark]) → Node + // Like [`create`](#model.NodeType.create), but check the given content + // against the node type's content restrictions, and throw an error + // if it doesn't match. + NodeType.prototype.createChecked = function createChecked (attrs, content, marks) { + content = Fragment.from(content); + if (!this.validContent(content)) + { throw new RangeError("Invalid content for node " + this.name) } + return new Node$1(this, this.computeAttrs(attrs), content, Mark.setFrom(marks)) + }; + + // :: (?Object, ?union, ?[Mark]) → ?Node + // Like [`create`](#model.NodeType.create), but see if it is necessary to + // add nodes to the start or end of the given fragment to make it + // fit the node. If no fitting wrapping can be found, return null. + // Note that, due to the fact that required nodes can always be + // created, this will always succeed if you pass null or + // `Fragment.empty` as content. + NodeType.prototype.createAndFill = function createAndFill (attrs, content, marks) { + attrs = this.computeAttrs(attrs); + content = Fragment.from(content); + if (content.size) { + var before = this.contentMatch.fillBefore(content); + if (!before) { return null } + content = before.append(content); + } + var after = this.contentMatch.matchFragment(content).fillBefore(Fragment.empty, true); + if (!after) { return null } + return new Node$1(this, attrs, content.append(after), Mark.setFrom(marks)) + }; + + // :: (Fragment) → bool + // Returns true if the given fragment is valid content for this node + // type with the given attributes. + NodeType.prototype.validContent = function validContent (content) { + var result = this.contentMatch.matchFragment(content); + if (!result || !result.validEnd) { return false } + for (var i = 0; i < content.childCount; i++) + { if (!this.allowsMarks(content.child(i).marks)) { return false } } + return true + }; + + // :: (MarkType) → bool + // Check whether the given mark type is allowed in this node. + NodeType.prototype.allowsMarkType = function allowsMarkType (markType) { + return this.markSet == null || this.markSet.indexOf(markType) > -1 + }; + + // :: ([Mark]) → bool + // Test whether the given set of marks are allowed in this node. + NodeType.prototype.allowsMarks = function allowsMarks (marks) { + if (this.markSet == null) { return true } + for (var i = 0; i < marks.length; i++) { if (!this.allowsMarkType(marks[i].type)) { return false } } + return true + }; + + // :: ([Mark]) → [Mark] + // Removes the marks that are not allowed in this node from the given set. + NodeType.prototype.allowedMarks = function allowedMarks (marks) { + if (this.markSet == null) { return marks } + var copy; + for (var i = 0; i < marks.length; i++) { + if (!this.allowsMarkType(marks[i].type)) { + if (!copy) { copy = marks.slice(0, i); } + } else if (copy) { + copy.push(marks[i]); + } + } + return !copy ? marks : copy.length ? copy : Mark.empty + }; + + NodeType.compile = function compile (nodes, schema) { + var result = Object.create(null); + nodes.forEach(function (name, spec) { return result[name] = new NodeType(name, schema, spec); }); + + var topType = schema.spec.topNode || "doc"; + if (!result[topType]) { throw new RangeError("Schema is missing its top node type ('" + topType + "')") } + if (!result.text) { throw new RangeError("Every schema needs a 'text' type") } + for (var _ in result.text.attrs) { throw new RangeError("The text node type should not have attributes") } + + return result + }; + + Object.defineProperties( NodeType.prototype, prototypeAccessors$5 ); + + // Attribute descriptors + + var Attribute = function Attribute(options) { + this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default"); + this.default = options.default; + }; + + var prototypeAccessors$1$3 = { isRequired: { configurable: true } }; + + prototypeAccessors$1$3.isRequired.get = function () { + return !this.hasDefault + }; + + Object.defineProperties( Attribute.prototype, prototypeAccessors$1$3 ); + + // Marks + + // ::- Like nodes, marks (which are associated with nodes to signify + // things like emphasis or being part of a link) are + // [tagged](#model.Mark.type) with type objects, which are + // instantiated once per `Schema`. + var MarkType = function MarkType(name, rank, schema, spec) { + // :: string + // The name of the mark type. + this.name = name; + + // :: Schema + // The schema that this mark type instance is part of. + this.schema = schema; + + // :: MarkSpec + // The spec on which the type is based. + this.spec = spec; + + this.attrs = initAttrs(spec.attrs); + + this.rank = rank; + this.excluded = null; + var defaults = defaultAttrs(this.attrs); + this.instance = defaults && new Mark(this, defaults); + }; + + // :: (?Object) → Mark + // Create a mark of this type. `attrs` may be `null` or an object + // containing only some of the mark's attributes. The others, if + // they have defaults, will be added. + MarkType.prototype.create = function create (attrs) { + if (!attrs && this.instance) { return this.instance } + return new Mark(this, computeAttrs(this.attrs, attrs)) + }; + + MarkType.compile = function compile (marks, schema) { + var result = Object.create(null), rank = 0; + marks.forEach(function (name, spec) { return result[name] = new MarkType(name, rank++, schema, spec); }); + return result + }; + + // :: ([Mark]) → [Mark] + // When there is a mark of this type in the given set, a new set + // without it is returned. Otherwise, the input set is returned. + MarkType.prototype.removeFromSet = function removeFromSet (set) { + for (var i = 0; i < set.length; i++) + { if (set[i].type == this) + { return set.slice(0, i).concat(set.slice(i + 1)) } } + return set + }; + + // :: ([Mark]) → ?Mark + // Tests whether there is a mark of this type in the given set. + MarkType.prototype.isInSet = function isInSet (set) { + for (var i = 0; i < set.length; i++) + { if (set[i].type == this) { return set[i] } } + }; + + // :: (MarkType) → bool + // Queries whether a given mark type is + // [excluded](#model.MarkSpec.excludes) by this one. + MarkType.prototype.excludes = function excludes (other) { + return this.excluded.indexOf(other) > -1 + }; + + // SchemaSpec:: interface + // An object describing a schema, as passed to the [`Schema`](#model.Schema) + // constructor. + // + // nodes:: union, OrderedMap> + // The node types in this schema. Maps names to + // [`NodeSpec`](#model.NodeSpec) objects that describe the node type + // associated with that name. Their order is significant—it + // determines which [parse rules](#model.NodeSpec.parseDOM) take + // precedence by default, and which nodes come first in a given + // [group](#model.NodeSpec.group). + // + // marks:: ?union, OrderedMap> + // The mark types that exist in this schema. The order in which they + // are provided determines the order in which [mark + // sets](#model.Mark.addToSet) are sorted and in which [parse + // rules](#model.MarkSpec.parseDOM) are tried. + // + // topNode:: ?string + // The name of the default top-level node for the schema. Defaults + // to `"doc"`. + + // NodeSpec:: interface + // + // content:: ?string + // The content expression for this node, as described in the [schema + // guide](/docs/guide/#schema.content_expressions). When not given, + // the node does not allow any content. + // + // marks:: ?string + // The marks that are allowed inside of this node. May be a + // space-separated string referring to mark names or groups, `"_"` + // to explicitly allow all marks, or `""` to disallow marks. When + // not given, nodes with inline content default to allowing all + // marks, other nodes default to not allowing marks. + // + // group:: ?string + // The group or space-separated groups to which this node belongs, + // which can be referred to in the content expressions for the + // schema. + // + // inline:: ?bool + // Should be set to true for inline nodes. (Implied for text nodes.) + // + // atom:: ?bool + // Can be set to true to indicate that, though this isn't a [leaf + // node](#model.NodeType.isLeaf), it doesn't have directly editable + // content and should be treated as a single unit in the view. + // + // attrs:: ?Object + // The attributes that nodes of this type get. + // + // selectable:: ?bool + // Controls whether nodes of this type can be selected as a [node + // selection](#state.NodeSelection). Defaults to true for non-text + // nodes. + // + // draggable:: ?bool + // Determines whether nodes of this type can be dragged without + // being selected. Defaults to false. + // + // code:: ?bool + // Can be used to indicate that this node contains code, which + // causes some commands to behave differently. + // + // defining:: ?bool + // Determines whether this node is considered an important parent + // node during replace operations (such as paste). Non-defining (the + // default) nodes get dropped when their entire content is replaced, + // whereas defining nodes persist and wrap the inserted content. + // Likewise, in _inserted_ content the defining parents of the + // content are preserved when possible. Typically, + // non-default-paragraph textblock types, and possibly list items, + // are marked as defining. + // + // isolating:: ?bool + // When enabled (default is false), the sides of nodes of this type + // count as boundaries that regular editing operations, like + // backspacing or lifting, won't cross. An example of a node that + // should probably have this enabled is a table cell. + // + // toDOM:: ?(node: Node) → DOMOutputSpec + // Defines the default way a node of this type should be serialized + // to DOM/HTML (as used by + // [`DOMSerializer.fromSchema`](#model.DOMSerializer^fromSchema)). + // Should return a DOM node or an [array + // structure](#model.DOMOutputSpec) that describes one, with an + // optional number zero (“hole”) in it to indicate where the node's + // content should be inserted. + // + // For text nodes, the default is to create a text DOM node. Though + // it is possible to create a serializer where text is rendered + // differently, this is not supported inside the editor, so you + // shouldn't override that in your text node spec. + // + // parseDOM:: ?[ParseRule] + // Associates DOM parser information with this node, which can be + // used by [`DOMParser.fromSchema`](#model.DOMParser^fromSchema) to + // automatically derive a parser. The `node` field in the rules is + // implied (the name of this node will be filled in automatically). + // If you supply your own parser, you do not need to also specify + // parsing rules in your schema. + // + // toDebugString:: ?(node: Node) -> string + // Defines the default way a node of this type should be serialized + // to a string representation for debugging (e.g. in error messages). + + // MarkSpec:: interface + // + // attrs:: ?Object + // The attributes that marks of this type get. + // + // inclusive:: ?bool + // Whether this mark should be active when the cursor is positioned + // at its end (or at its start when that is also the start of the + // parent node). Defaults to true. + // + // excludes:: ?string + // Determines which other marks this mark can coexist with. Should + // be a space-separated strings naming other marks or groups of marks. + // When a mark is [added](#model.Mark.addToSet) to a set, all marks + // that it excludes are removed in the process. If the set contains + // any mark that excludes the new mark but is not, itself, excluded + // by the new mark, the mark can not be added an the set. You can + // use the value `"_"` to indicate that the mark excludes all + // marks in the schema. + // + // Defaults to only being exclusive with marks of the same type. You + // can set it to an empty string (or any string not containing the + // mark's own name) to allow multiple marks of a given type to + // coexist (as long as they have different attributes). + // + // group:: ?string + // The group or space-separated groups to which this mark belongs. + // + // spanning:: ?bool + // Determines whether marks of this type can span multiple adjacent + // nodes when serialized to DOM/HTML. Defaults to true. + // + // toDOM:: ?(mark: Mark, inline: bool) → DOMOutputSpec + // Defines the default way marks of this type should be serialized + // to DOM/HTML. When the resulting spec contains a hole, that is + // where the marked content is placed. Otherwise, it is appended to + // the top node. + // + // parseDOM:: ?[ParseRule] + // Associates DOM parser information with this mark (see the + // corresponding [node spec field](#model.NodeSpec.parseDOM)). The + // `mark` field in the rules is implied. + + // AttributeSpec:: interface + // + // Used to [define](#model.NodeSpec.attrs) attributes on nodes or + // marks. + // + // default:: ?any + // The default value for this attribute, to use when no explicit + // value is provided. Attributes that have no default must be + // provided whenever a node or mark of a type that has them is + // created. + + // ::- A document schema. Holds [node](#model.NodeType) and [mark + // type](#model.MarkType) objects for the nodes and marks that may + // occur in conforming documents, and provides functionality for + // creating and deserializing such documents. + var Schema = function Schema(spec) { + // :: SchemaSpec + // The [spec](#model.SchemaSpec) on which the schema is based, + // with the added guarantee that its `nodes` and `marks` + // properties are + // [`OrderedMap`](https://github.com/marijnh/orderedmap) instances + // (not raw objects). + this.spec = {}; + for (var prop in spec) { this.spec[prop] = spec[prop]; } + this.spec.nodes = orderedmap.from(spec.nodes); + this.spec.marks = orderedmap.from(spec.marks); + + // :: Object + // An object mapping the schema's node names to node type objects. + this.nodes = NodeType.compile(this.spec.nodes, this); + + // :: Object + // A map from mark names to mark type objects. + this.marks = MarkType.compile(this.spec.marks, this); + + var contentExprCache = Object.create(null); + for (var prop$1 in this.nodes) { + if (prop$1 in this.marks) + { throw new RangeError(prop$1 + " can not be both a node and a mark") } + var type = this.nodes[prop$1], contentExpr = type.spec.content || "", markExpr = type.spec.marks; + type.contentMatch = contentExprCache[contentExpr] || + (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes)); + type.inlineContent = type.contentMatch.inlineContent; + type.markSet = markExpr == "_" ? null : + markExpr ? gatherMarks(this, markExpr.split(" ")) : + markExpr == "" || !type.inlineContent ? [] : null; + } + for (var prop$2 in this.marks) { + var type$1 = this.marks[prop$2], excl = type$1.spec.excludes; + type$1.excluded = excl == null ? [type$1] : excl == "" ? [] : gatherMarks(this, excl.split(" ")); + } + + this.nodeFromJSON = this.nodeFromJSON.bind(this); + this.markFromJSON = this.markFromJSON.bind(this); + + // :: NodeType + // The type of the [default top node](#model.SchemaSpec.topNode) + // for this schema. + this.topNodeType = this.nodes[this.spec.topNode || "doc"]; + + // :: Object + // An object for storing whatever values modules may want to + // compute and cache per schema. (If you want to store something + // in it, try to use property names unlikely to clash.) + this.cached = Object.create(null); + this.cached.wrappings = Object.create(null); + }; + + // :: (union, ?Object, ?union, ?[Mark]) → Node + // Create a node in this schema. The `type` may be a string or a + // `NodeType` instance. Attributes will be extended + // with defaults, `content` may be a `Fragment`, + // `null`, a `Node`, or an array of nodes. + Schema.prototype.node = function node (type, attrs, content, marks) { + if (typeof type == "string") + { type = this.nodeType(type); } + else if (!(type instanceof NodeType)) + { throw new RangeError("Invalid node type: " + type) } + else if (type.schema != this) + { throw new RangeError("Node type from different schema used (" + type.name + ")") } + + return type.createChecked(attrs, content, marks) + }; + + // :: (string, ?[Mark]) → Node + // Create a text node in the schema. Empty text nodes are not + // allowed. + Schema.prototype.text = function text (text$1, marks) { + var type = this.nodes.text; + return new TextNode(type, type.defaultAttrs, text$1, Mark.setFrom(marks)) + }; + + // :: (union, ?Object) → Mark + // Create a mark with the given type and attributes. + Schema.prototype.mark = function mark (type, attrs) { + if (typeof type == "string") { type = this.marks[type]; } + return type.create(attrs) + }; + + // :: (Object) → Node + // Deserialize a node from its JSON representation. This method is + // bound. + Schema.prototype.nodeFromJSON = function nodeFromJSON (json) { + return Node$1.fromJSON(this, json) + }; + + // :: (Object) → Mark + // Deserialize a mark from its JSON representation. This method is + // bound. + Schema.prototype.markFromJSON = function markFromJSON (json) { + return Mark.fromJSON(this, json) + }; + + Schema.prototype.nodeType = function nodeType (name) { + var found = this.nodes[name]; + if (!found) { throw new RangeError("Unknown node type: " + name) } + return found + }; + + function gatherMarks(schema, marks) { + var found = []; + for (var i = 0; i < marks.length; i++) { + var name = marks[i], mark = schema.marks[name], ok = mark; + if (mark) { + found.push(mark); + } else { + for (var prop in schema.marks) { + var mark$1 = schema.marks[prop]; + if (name == "_" || (mark$1.spec.group && mark$1.spec.group.split(" ").indexOf(name) > -1)) + { found.push(ok = mark$1); } + } + } + if (!ok) { throw new SyntaxError("Unknown mark type: '" + marks[i] + "'") } + } + return found + } + + // ParseOptions:: interface + // These are the options recognized by the + // [`parse`](#model.DOMParser.parse) and + // [`parseSlice`](#model.DOMParser.parseSlice) methods. + // + // preserveWhitespace:: ?union + // By default, whitespace is collapsed as per HTML's rules. Pass + // `true` to preserve whitespace, but normalize newlines to + // spaces, and `"full"` to preserve whitespace entirely. + // + // findPositions:: ?[{node: dom.Node, offset: number}] + // When given, the parser will, beside parsing the content, + // record the document positions of the given DOM positions. It + // will do so by writing to the objects, adding a `pos` property + // that holds the document position. DOM positions that are not + // in the parsed content will not be written to. + // + // from:: ?number + // The child node index to start parsing from. + // + // to:: ?number + // The child node index to stop parsing at. + // + // topNode:: ?Node + // By default, the content is parsed into the schema's default + // [top node type](#model.Schema.topNodeType). You can pass this + // option to use the type and attributes from a different node + // as the top container. + // + // topMatch:: ?ContentMatch + // Provide the starting content match that content parsed into the + // top node is matched against. + // + // context:: ?ResolvedPos + // A set of additional nodes to count as + // [context](#model.ParseRule.context) when parsing, above the + // given [top node](#model.ParseOptions.topNode). + + // ParseRule:: interface + // A value that describes how to parse a given DOM node or inline + // style as a ProseMirror node or mark. + // + // tag:: ?string + // A CSS selector describing the kind of DOM elements to match. A + // single rule should have _either_ a `tag` or a `style` property. + // + // namespace:: ?string + // The namespace to match. This should be used with `tag`. + // Nodes are only matched when the namespace matches or this property + // is null. + // + // style:: ?string + // A CSS property name to match. When given, this rule matches + // inline styles that list that property. May also have the form + // `"property=value"`, in which case the rule only matches if the + // property's value exactly matches the given value. (For more + // complicated filters, use [`getAttrs`](#model.ParseRule.getAttrs) + // and return false to indicate that the match failed.) + // + // priority:: ?number + // Can be used to change the order in which the parse rules in a + // schema are tried. Those with higher priority come first. Rules + // without a priority are counted as having priority 50. This + // property is only meaningful in a schema—when directly + // constructing a parser, the order of the rule array is used. + // + // context:: ?string + // When given, restricts this rule to only match when the current + // context—the parent nodes into which the content is being + // parsed—matches this expression. Should contain one or more node + // names or node group names followed by single or double slashes. + // For example `"paragraph/"` means the rule only matches when the + // parent node is a paragraph, `"blockquote/paragraph/"` restricts + // it to be in a paragraph that is inside a blockquote, and + // `"section//"` matches any position inside a section—a double + // slash matches any sequence of ancestor nodes. To allow multiple + // different contexts, they can be separated by a pipe (`|`) + // character, as in `"blockquote/|list_item/"`. + // + // node:: ?string + // The name of the node type to create when this rule matches. Only + // valid for rules with a `tag` property, not for style rules. Each + // rule should have one of a `node`, `mark`, or `ignore` property + // (except when it appears in a [node](#model.NodeSpec.parseDOM) or + // [mark spec](#model.MarkSpec.parseDOM), in which case the `node` + // or `mark` property will be derived from its position). + // + // mark:: ?string + // The name of the mark type to wrap the matched content in. + // + // ignore:: ?bool + // When true, ignore content that matches this rule. + // + // closeParent:: ?bool + // When true, finding an element that matches this rule will close + // the current node. + // + // skip:: ?bool + // When true, ignore the node that matches this rule, but do parse + // its content. + // + // attrs:: ?Object + // Attributes for the node or mark created by this rule. When + // `getAttrs` is provided, it takes precedence. + // + // getAttrs:: ?(union) → ?union + // A function used to compute the attributes for the node or mark + // created by this rule. Can also be used to describe further + // conditions the DOM element or style must match. When it returns + // `false`, the rule won't match. When it returns null or undefined, + // that is interpreted as an empty/default set of attributes. + // + // Called with a DOM Element for `tag` rules, and with a string (the + // style's value) for `style` rules. + // + // contentElement:: ?union + // For `tag` rules that produce non-leaf nodes or marks, by default + // the content of the DOM element is parsed as content of the mark + // or node. If the child nodes are in a descendent node, this may be + // a CSS selector string that the parser must use to find the actual + // content element, or a function that returns the actual content + // element to the parser. + // + // getContent:: ?(dom.Node, schema: Schema) → Fragment + // Can be used to override the content of a matched node. When + // present, instead of parsing the node's child nodes, the result of + // this function is used. + // + // preserveWhitespace:: ?union + // Controls whether whitespace should be preserved when parsing the + // content inside the matched element. `false` means whitespace may + // be collapsed, `true` means that whitespace should be preserved + // but newlines normalized to spaces, and `"full"` means that + // newlines should also be preserved. + + // ::- A DOM parser represents a strategy for parsing DOM content into + // a ProseMirror document conforming to a given schema. Its behavior + // is defined by an array of [rules](#model.ParseRule). + var DOMParser$1 = function DOMParser(schema, rules) { + var this$1 = this; + + // :: Schema + // The schema into which the parser parses. + this.schema = schema; + // :: [ParseRule] + // The set of [parse rules](#model.ParseRule) that the parser + // uses, in order of precedence. + this.rules = rules; + this.tags = []; + this.styles = []; + + rules.forEach(function (rule) { + if (rule.tag) { this$1.tags.push(rule); } + else if (rule.style) { this$1.styles.push(rule); } + }); + + // Only normalize list elements when lists in the schema can't directly contain themselves + this.normalizeLists = !this.tags.some(function (r) { + if (!/^(ul|ol)\b/.test(r.tag) || !r.node) { return false } + var node = schema.nodes[r.node]; + return node.contentMatch.matchType(node) + }); + }; + + // :: (dom.Node, ?ParseOptions) → Node + // Parse a document from the content of a DOM node. + DOMParser$1.prototype.parse = function parse (dom, options) { + if ( options === void 0 ) options = {}; + + var context = new ParseContext(this, options, false); + context.addAll(dom, null, options.from, options.to); + return context.finish() + }; + + // :: (dom.Node, ?ParseOptions) → Slice + // Parses the content of the given DOM node, like + // [`parse`](#model.DOMParser.parse), and takes the same set of + // options. But unlike that method, which produces a whole node, + // this one returns a slice that is open at the sides, meaning that + // the schema constraints aren't applied to the start of nodes to + // the left of the input and the end of nodes at the end. + DOMParser$1.prototype.parseSlice = function parseSlice (dom, options) { + if ( options === void 0 ) options = {}; + + var context = new ParseContext(this, options, true); + context.addAll(dom, null, options.from, options.to); + return Slice.maxOpen(context.finish()) + }; + + DOMParser$1.prototype.matchTag = function matchTag (dom, context) { + for (var i = 0; i < this.tags.length; i++) { + var rule = this.tags[i]; + if (matches(dom, rule.tag) && + (rule.namespace === undefined || dom.namespaceURI == rule.namespace) && + (!rule.context || context.matchesContext(rule.context))) { + if (rule.getAttrs) { + var result = rule.getAttrs(dom); + if (result === false) { continue } + rule.attrs = result; + } + return rule + } + } + }; + + DOMParser$1.prototype.matchStyle = function matchStyle (prop, value, context) { + for (var i = 0; i < this.styles.length; i++) { + var rule = this.styles[i]; + if (rule.style.indexOf(prop) != 0 || + rule.context && !context.matchesContext(rule.context) || + // Test that the style string either precisely matches the prop, + // or has an '=' sign after the prop, followed by the given + // value. + rule.style.length > prop.length && + (rule.style.charCodeAt(prop.length) != 61 || rule.style.slice(prop.length + 1) != value)) + { continue } + if (rule.getAttrs) { + var result = rule.getAttrs(value); + if (result === false) { continue } + rule.attrs = result; + } + return rule + } + }; + + // : (Schema) → [ParseRule] + DOMParser$1.schemaRules = function schemaRules (schema) { + var result = []; + function insert(rule) { + var priority = rule.priority == null ? 50 : rule.priority, i = 0; + for (; i < result.length; i++) { + var next = result[i], nextPriority = next.priority == null ? 50 : next.priority; + if (nextPriority < priority) { break } + } + result.splice(i, 0, rule); + } + + var loop = function ( name ) { + var rules = schema.marks[name].spec.parseDOM; + if (rules) { rules.forEach(function (rule) { + insert(rule = copy$1(rule)); + rule.mark = name; + }); } + }; + + for (var name in schema.marks) loop( name ); + var loop$1 = function ( name ) { + var rules$1 = schema.nodes[name$1].spec.parseDOM; + if (rules$1) { rules$1.forEach(function (rule) { + insert(rule = copy$1(rule)); + rule.node = name$1; + }); } + }; + + for (var name$1 in schema.nodes) loop$1(); + return result + }; + + // :: (Schema) → DOMParser + // Construct a DOM parser using the parsing rules listed in a + // schema's [node specs](#model.NodeSpec.parseDOM), reordered by + // [priority](#model.ParseRule.priority). + DOMParser$1.fromSchema = function fromSchema (schema) { + return schema.cached.domParser || + (schema.cached.domParser = new DOMParser$1(schema, DOMParser$1.schemaRules(schema))) + }; + + // : Object The block-level tags in HTML5 + var blockTags = { + address: true, article: true, aside: true, blockquote: true, canvas: true, + dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true, + footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true, + h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true, + output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true + }; + + // : Object The tags that we normally ignore. + var ignoreTags = { + head: true, noscript: true, object: true, script: true, style: true, title: true + }; + + // : Object List tags. + var listTags = {ol: true, ul: true}; + + // Using a bitfield for node context options + var OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4; + + function wsOptionsFor(preserveWhitespace) { + return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0) + } + + var NodeContext = function NodeContext(type, attrs, marks, pendingMarks, solid, match, options) { + this.type = type; + this.attrs = attrs; + this.solid = solid; + this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch); + this.options = options; + this.content = []; + // Marks applied to this node itself + this.marks = marks; + // Marks applied to its children + this.activeMarks = Mark.none; + // Marks that can't apply here, but will be used in children if possible + this.pendingMarks = pendingMarks; + // Nested Marks with same type + this.stashMarks = []; + }; + + NodeContext.prototype.findWrapping = function findWrapping (node) { + if (!this.match) { + if (!this.type) { return [] } + var fill = this.type.contentMatch.fillBefore(Fragment.from(node)); + if (fill) { + this.match = this.type.contentMatch.matchFragment(fill); + } else { + var start = this.type.contentMatch, wrap; + if (wrap = start.findWrapping(node.type)) { + this.match = start; + return wrap + } else { + return null + } + } + } + return this.match.findWrapping(node.type) + }; + + NodeContext.prototype.finish = function finish (openEnd) { + if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace + var last = this.content[this.content.length - 1], m; + if (last && last.isText && (m = /[ \t\r\n\u000c]+$/.exec(last.text))) { + if (last.text.length == m[0].length) { this.content.pop(); } + else { this.content[this.content.length - 1] = last.withText(last.text.slice(0, last.text.length - m[0].length)); } + } + } + var content = Fragment.from(this.content); + if (!openEnd && this.match) + { content = content.append(this.match.fillBefore(Fragment.empty, true)); } + return this.type ? this.type.create(this.attrs, content, this.marks) : content + }; + + NodeContext.prototype.popFromStashMark = function popFromStashMark (markType) { + for (var i = this.stashMarks.length - 1; i >= 0; i--) + { if (this.stashMarks[i].type == markType) { return this.stashMarks.splice(i, 1)[0] } } + }; + + NodeContext.prototype.applyPending = function applyPending (nextType) { + for (var i = 0, pending = this.pendingMarks; i < pending.length; i++) { + var mark = pending[i]; + if ((this.type ? this.type.allowsMarkType(mark.type) : markMayApply(mark.type, nextType)) && + !mark.isInSet(this.activeMarks)) { + var found = findSameTypeInSet(mark, this.activeMarks); + if (found) { this.stashMarks.push(found); } + this.activeMarks = mark.addToSet(this.activeMarks); + this.pendingMarks = mark.removeFromSet(this.pendingMarks); + } + } + }; + + var ParseContext = function ParseContext(parser, options, open) { + // : DOMParser The parser we are using. + this.parser = parser; + // : Object The options passed to this parse. + this.options = options; + this.isOpen = open; + var topNode = options.topNode, topContext; + var topOptions = wsOptionsFor(options.preserveWhitespace) | (open ? OPT_OPEN_LEFT : 0); + if (topNode) + { topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, Mark.none, true, + options.topMatch || topNode.type.contentMatch, topOptions); } + else if (open) + { topContext = new NodeContext(null, null, Mark.none, Mark.none, true, null, topOptions); } + else + { topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, Mark.none, true, null, topOptions); } + this.nodes = [topContext]; + // : [Mark] The current set of marks + this.open = 0; + this.find = options.findPositions; + this.needsBlock = false; + }; + + var prototypeAccessors$6 = { top: { configurable: true },currentPos: { configurable: true } }; + + prototypeAccessors$6.top.get = function () { + return this.nodes[this.open] + }; + + // : (dom.Node) + // Add a DOM node to the content. Text is inserted as text node, + // otherwise, the node is passed to `addElement` or, if it has a + // `style` attribute, `addElementWithStyles`. + ParseContext.prototype.addDOM = function addDOM (dom) { + if (dom.nodeType == 3) { + this.addTextNode(dom); + } else if (dom.nodeType == 1) { + var style = dom.getAttribute("style"); + var marks = style ? this.readStyles(parseStyles(style)) : null, top = this.top; + if (marks != null) { for (var i = 0; i < marks.length; i++) { this.addPendingMark(marks[i]); } } + this.addElement(dom); + if (marks != null) { for (var i$1 = 0; i$1 < marks.length; i$1++) { this.removePendingMark(marks[i$1], top); } } + } + }; + + ParseContext.prototype.addTextNode = function addTextNode (dom) { + var value = dom.nodeValue; + var top = this.top; + if ((top.type ? top.type.inlineContent : top.content.length && top.content[0].isInline) || /[^ \t\r\n\u000c]/.test(value)) { + if (!(top.options & OPT_PRESERVE_WS)) { + value = value.replace(/[ \t\r\n\u000c]+/g, " "); + // If this starts with whitespace, and there is no node before it, or + // a hard break, or a text node that ends with whitespace, strip the + // leading space. + if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) { + var nodeBefore = top.content[top.content.length - 1]; + var domNodeBefore = dom.previousSibling; + if (!nodeBefore || + (domNodeBefore && domNodeBefore.nodeName == 'BR') || + (nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text))) + { value = value.slice(1); } + } + } else if (!(top.options & OPT_PRESERVE_WS_FULL)) { + value = value.replace(/\r?\n|\r/g, " "); + } + if (value) { this.insertNode(this.parser.schema.text(value)); } + this.findInText(dom); + } else { + this.findInside(dom); + } + }; + + // : (dom.Element) + // Try to find a handler for the given tag and use that to parse. If + // none is found, the element's content nodes are added directly. + ParseContext.prototype.addElement = function addElement (dom) { + var name = dom.nodeName.toLowerCase(); + if (listTags.hasOwnProperty(name) && this.parser.normalizeLists) { normalizeList(dom); } + var rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) || this.parser.matchTag(dom, this); + if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) { + this.findInside(dom); + } else if (!rule || rule.skip || rule.closeParent) { + if (rule && rule.closeParent) { this.open = Math.max(0, this.open - 1); } + else if (rule && rule.skip.nodeType) { dom = rule.skip; } + var sync, top = this.top, oldNeedsBlock = this.needsBlock; + if (blockTags.hasOwnProperty(name)) { + sync = true; + if (!top.type) { this.needsBlock = true; } + } else if (!dom.firstChild) { + this.leafFallback(dom); + return + } + this.addAll(dom); + if (sync) { this.sync(top); } + this.needsBlock = oldNeedsBlock; + } else { + this.addElementByRule(dom, rule); + } + }; + + // Called for leaf DOM nodes that would otherwise be ignored + ParseContext.prototype.leafFallback = function leafFallback (dom) { + if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent) + { this.addTextNode(dom.ownerDocument.createTextNode("\n")); } + }; + + // Run any style parser associated with the node's styles. Either + // return an array of marks, or null to indicate some of the styles + // had a rule with `ignore` set. + ParseContext.prototype.readStyles = function readStyles (styles) { + var marks = Mark.none; + for (var i = 0; i < styles.length; i += 2) { + var rule = this.parser.matchStyle(styles[i], styles[i + 1], this); + if (!rule) { continue } + if (rule.ignore) { return null } + marks = this.parser.schema.marks[rule.mark].create(rule.attrs).addToSet(marks); + } + return marks + }; + + // : (dom.Element, ParseRule) → bool + // Look up a handler for the given node. If none are found, return + // false. Otherwise, apply it, use its return value to drive the way + // the node's content is wrapped, and return true. + ParseContext.prototype.addElementByRule = function addElementByRule (dom, rule) { + var this$1 = this; + + var sync, nodeType, markType, mark; + if (rule.node) { + nodeType = this.parser.schema.nodes[rule.node]; + if (!nodeType.isLeaf) { + sync = this.enter(nodeType, rule.attrs, rule.preserveWhitespace); + } else if (!this.insertNode(nodeType.create(rule.attrs))) { + this.leafFallback(dom); + } + } else { + markType = this.parser.schema.marks[rule.mark]; + mark = markType.create(rule.attrs); + this.addPendingMark(mark); + } + var startIn = this.top; + + if (nodeType && nodeType.isLeaf) { + this.findInside(dom); + } else if (rule.getContent) { + this.findInside(dom); + rule.getContent(dom, this.parser.schema).forEach(function (node) { return this$1.insertNode(node); }); + } else { + var contentDOM = rule.contentElement; + if (typeof contentDOM == "string") { contentDOM = dom.querySelector(contentDOM); } + else if (typeof contentDOM == "function") { contentDOM = contentDOM(dom); } + if (!contentDOM) { contentDOM = dom; } + this.findAround(dom, contentDOM, true); + this.addAll(contentDOM, sync); + } + if (sync) { this.sync(startIn); this.open--; } + if (mark) { this.removePendingMark(mark, startIn); } + }; + + // : (dom.Node, ?NodeBuilder, ?number, ?number) + // Add all child nodes between `startIndex` and `endIndex` (or the + // whole node, if not given). If `sync` is passed, use it to + // synchronize after every block element. + ParseContext.prototype.addAll = function addAll (parent, sync, startIndex, endIndex) { + var index = startIndex || 0; + for (var dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, + end = endIndex == null ? null : parent.childNodes[endIndex]; + dom != end; dom = dom.nextSibling, ++index) { + this.findAtPoint(parent, index); + this.addDOM(dom); + if (sync && blockTags.hasOwnProperty(dom.nodeName.toLowerCase())) + { this.sync(sync); } + } + this.findAtPoint(parent, index); + }; + + // Try to find a way to fit the given node type into the current + // context. May add intermediate wrappers and/or leave non-solid + // nodes that we're in. + ParseContext.prototype.findPlace = function findPlace (node) { + var route, sync; + for (var depth = this.open; depth >= 0; depth--) { + var cx = this.nodes[depth]; + var found = cx.findWrapping(node); + if (found && (!route || route.length > found.length)) { + route = found; + sync = cx; + if (!found.length) { break } + } + if (cx.solid) { break } + } + if (!route) { return false } + this.sync(sync); + for (var i = 0; i < route.length; i++) + { this.enterInner(route[i], null, false); } + return true + }; + + // : (Node) → ?Node + // Try to insert the given node, adjusting the context when needed. + ParseContext.prototype.insertNode = function insertNode (node) { + if (node.isInline && this.needsBlock && !this.top.type) { + var block = this.textblockFromContext(); + if (block) { this.enterInner(block); } + } + if (this.findPlace(node)) { + this.closeExtra(); + var top = this.top; + top.applyPending(node.type); + if (top.match) { top.match = top.match.matchType(node.type); } + var marks = top.activeMarks; + for (var i = 0; i < node.marks.length; i++) + { if (!top.type || top.type.allowsMarkType(node.marks[i].type)) + { marks = node.marks[i].addToSet(marks); } } + top.content.push(node.mark(marks)); + return true + } + return false + }; + + // : (NodeType, ?Object) → bool + // Try to start a node of the given type, adjusting the context when + // necessary. + ParseContext.prototype.enter = function enter (type, attrs, preserveWS) { + var ok = this.findPlace(type.create(attrs)); + if (ok) { this.enterInner(type, attrs, true, preserveWS); } + return ok + }; + + // Open a node of the given type + ParseContext.prototype.enterInner = function enterInner (type, attrs, solid, preserveWS) { + this.closeExtra(); + var top = this.top; + top.applyPending(type); + top.match = top.match && top.match.matchType(type, attrs); + var options = preserveWS == null ? top.options & ~OPT_OPEN_LEFT : wsOptionsFor(preserveWS); + if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0) { options |= OPT_OPEN_LEFT; } + this.nodes.push(new NodeContext(type, attrs, top.activeMarks, top.pendingMarks, solid, null, options)); + this.open++; + }; + + // Make sure all nodes above this.open are finished and added to + // their parents + ParseContext.prototype.closeExtra = function closeExtra (openEnd) { + var i = this.nodes.length - 1; + if (i > this.open) { + for (; i > this.open; i--) { this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd)); } + this.nodes.length = this.open + 1; + } + }; + + ParseContext.prototype.finish = function finish () { + this.open = 0; + this.closeExtra(this.isOpen); + return this.nodes[0].finish(this.isOpen || this.options.topOpen) + }; + + ParseContext.prototype.sync = function sync (to) { + for (var i = this.open; i >= 0; i--) { if (this.nodes[i] == to) { + this.open = i; + return + } } + }; + + prototypeAccessors$6.currentPos.get = function () { + this.closeExtra(); + var pos = 0; + for (var i = this.open; i >= 0; i--) { + var content = this.nodes[i].content; + for (var j = content.length - 1; j >= 0; j--) + { pos += content[j].nodeSize; } + if (i) { pos++; } + } + return pos + }; + + ParseContext.prototype.findAtPoint = function findAtPoint (parent, offset) { + if (this.find) { for (var i = 0; i < this.find.length; i++) { + if (this.find[i].node == parent && this.find[i].offset == offset) + { this.find[i].pos = this.currentPos; } + } } + }; + + ParseContext.prototype.findInside = function findInside (parent) { + if (this.find) { for (var i = 0; i < this.find.length; i++) { + if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) + { this.find[i].pos = this.currentPos; } + } } + }; + + ParseContext.prototype.findAround = function findAround (parent, content, before) { + if (parent != content && this.find) { for (var i = 0; i < this.find.length; i++) { + if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) { + var pos = content.compareDocumentPosition(this.find[i].node); + if (pos & (before ? 2 : 4)) + { this.find[i].pos = this.currentPos; } + } + } } + }; + + ParseContext.prototype.findInText = function findInText (textNode) { + if (this.find) { for (var i = 0; i < this.find.length; i++) { + if (this.find[i].node == textNode) + { this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset); } + } } + }; + + // : (string) → bool + // Determines whether the given [context + // string](#ParseRule.context) matches this context. + ParseContext.prototype.matchesContext = function matchesContext (context) { + var this$1 = this; + + if (context.indexOf("|") > -1) + { return context.split(/\s*\|\s*/).some(this.matchesContext, this) } + + var parts = context.split("/"); + var option = this.options.context; + var useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type); + var minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1); + var match = function (i, depth) { + for (; i >= 0; i--) { + var part = parts[i]; + if (part == "") { + if (i == parts.length - 1 || i == 0) { continue } + for (; depth >= minDepth; depth--) + { if (match(i - 1, depth)) { return true } } + return false + } else { + var next = depth > 0 || (depth == 0 && useRoot) ? this$1.nodes[depth].type + : option && depth >= minDepth ? option.node(depth - minDepth).type + : null; + if (!next || (next.name != part && next.groups.indexOf(part) == -1)) + { return false } + depth--; + } + } + return true + }; + return match(parts.length - 1, this.open) + }; + + ParseContext.prototype.textblockFromContext = function textblockFromContext () { + var $context = this.options.context; + if ($context) { for (var d = $context.depth; d >= 0; d--) { + var deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType; + if (deflt && deflt.isTextblock && deflt.defaultAttrs) { return deflt } + } } + for (var name in this.parser.schema.nodes) { + var type = this.parser.schema.nodes[name]; + if (type.isTextblock && type.defaultAttrs) { return type } + } + }; + + ParseContext.prototype.addPendingMark = function addPendingMark (mark) { + var found = findSameTypeInSet(mark, this.top.pendingMarks); + if (found) { this.top.stashMarks.push(found); } + this.top.pendingMarks = mark.addToSet(this.top.pendingMarks); + }; + + ParseContext.prototype.removePendingMark = function removePendingMark (mark, upto) { + for (var depth = this.open; depth >= 0; depth--) { + var level = this.nodes[depth]; + var found = level.pendingMarks.lastIndexOf(mark); + if (found > -1) { + level.pendingMarks = mark.removeFromSet(level.pendingMarks); + } else { + level.activeMarks = mark.removeFromSet(level.activeMarks); + var stashMark = level.popFromStashMark(mark.type); + if (stashMark) { level.activeMarks = stashMark.addToSet(level.activeMarks); } + } + if (level == upto) { break } + } + }; + + Object.defineProperties( ParseContext.prototype, prototypeAccessors$6 ); + + // Kludge to work around directly nested list nodes produced by some + // tools and allowed by browsers to mean that the nested list is + // actually part of the list item above it. + function normalizeList(dom) { + for (var child = dom.firstChild, prevItem = null; child; child = child.nextSibling) { + var name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null; + if (name && listTags.hasOwnProperty(name) && prevItem) { + prevItem.appendChild(child); + child = prevItem; + } else if (name == "li") { + prevItem = child; + } else if (name) { + prevItem = null; + } + } + } + + // Apply a CSS selector. + function matches(dom, selector) { + return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector) + } + + // : (string) → [string] + // Tokenize a style attribute into property/value pairs. + function parseStyles(style) { + var re = /\s*([\w-]+)\s*:\s*([^;]+)/g, m, result = []; + while (m = re.exec(style)) { result.push(m[1], m[2].trim()); } + return result + } + + function copy$1(obj) { + var copy = {}; + for (var prop in obj) { copy[prop] = obj[prop]; } + return copy + } + + // Used when finding a mark at the top level of a fragment parse. + // Checks whether it would be reasonable to apply a given mark type to + // a given node, by looking at the way the mark occurs in the schema. + function markMayApply(markType, nodeType) { + var nodes = nodeType.schema.nodes; + var loop = function ( name ) { + var parent = nodes[name]; + if (!parent.allowsMarkType(markType)) { return } + var seen = [], scan = function (match) { + seen.push(match); + for (var i = 0; i < match.edgeCount; i++) { + var ref = match.edge(i); + var type = ref.type; + var next = ref.next; + if (type == nodeType) { return true } + if (seen.indexOf(next) < 0 && scan(next)) { return true } + } + }; + if (scan(parent.contentMatch)) { return { v: true } } + }; + + for (var name in nodes) { + var returned = loop( name ); + + if ( returned ) return returned.v; + } + } + + function findSameTypeInSet(mark, set) { + for (var i = 0; i < set.length; i++) { + if (mark.type == set[i].type) { return set[i] } + } + } + + // DOMOutputSpec:: interface + // A description of a DOM structure. Can be either a string, which is + // interpreted as a text node, a DOM node, which is interpreted as + // itself, a `{dom: Node, contentDOM: ?Node}` object, or an array. + // + // An array describes a DOM element. The first value in the array + // should be a string—the name of the DOM element, optionally prefixed + // by a namespace URL and a space. If the second element is plain + // object, it is interpreted as a set of attributes for the element. + // Any elements after that (including the 2nd if it's not an attribute + // object) are interpreted as children of the DOM elements, and must + // either be valid `DOMOutputSpec` values, or the number zero. + // + // The number zero (pronounced “hole”) is used to indicate the place + // where a node's child nodes should be inserted. If it occurs in an + // output spec, it should be the only child element in its parent + // node. + + // ::- A DOM serializer knows how to convert ProseMirror nodes and + // marks of various types to DOM nodes. + var DOMSerializer = function DOMSerializer(nodes, marks) { + // :: Object<(node: Node) → DOMOutputSpec> + // The node serialization functions. + this.nodes = nodes || {}; + // :: Object + // The mark serialization functions. + this.marks = marks || {}; + }; + + // :: (Fragment, ?Object) → dom.DocumentFragment + // Serialize the content of this fragment to a DOM fragment. When + // not in the browser, the `document` option, containing a DOM + // document, should be passed so that the serializer can create + // nodes. + DOMSerializer.prototype.serializeFragment = function serializeFragment (fragment, options, target) { + var this$1 = this; + if ( options === void 0 ) options = {}; + + if (!target) { target = doc$1(options).createDocumentFragment(); } + + var top = target, active = null; + fragment.forEach(function (node) { + if (active || node.marks.length) { + if (!active) { active = []; } + var keep = 0, rendered = 0; + while (keep < active.length && rendered < node.marks.length) { + var next = node.marks[rendered]; + if (!this$1.marks[next.type.name]) { rendered++; continue } + if (!next.eq(active[keep]) || next.type.spec.spanning === false) { break } + keep += 2; rendered++; + } + while (keep < active.length) { + top = active.pop(); + active.pop(); + } + while (rendered < node.marks.length) { + var add = node.marks[rendered++]; + var markDOM = this$1.serializeMark(add, node.isInline, options); + if (markDOM) { + active.push(add, top); + top.appendChild(markDOM.dom); + top = markDOM.contentDOM || markDOM.dom; + } + } + } + top.appendChild(this$1.serializeNode(node, options)); + }); + + return target + }; + + // :: (Node, ?Object) → dom.Node + // Serialize this node to a DOM node. This can be useful when you + // need to serialize a part of a document, as opposed to the whole + // document. To serialize a whole document, use + // [`serializeFragment`](#model.DOMSerializer.serializeFragment) on + // its [content](#model.Node.content). + DOMSerializer.prototype.serializeNode = function serializeNode (node, options) { + if ( options === void 0 ) options = {}; + + var ref = + DOMSerializer.renderSpec(doc$1(options), this.nodes[node.type.name](node)); + var dom = ref.dom; + var contentDOM = ref.contentDOM; + if (contentDOM) { + if (node.isLeaf) + { throw new RangeError("Content hole not allowed in a leaf node spec") } + if (options.onContent) + { options.onContent(node, contentDOM, options); } + else + { this.serializeFragment(node.content, options, contentDOM); } + } + return dom + }; + + DOMSerializer.prototype.serializeNodeAndMarks = function serializeNodeAndMarks (node, options) { + if ( options === void 0 ) options = {}; + + var dom = this.serializeNode(node, options); + for (var i = node.marks.length - 1; i >= 0; i--) { + var wrap = this.serializeMark(node.marks[i], node.isInline, options); + if (wrap) { + (wrap.contentDOM || wrap.dom).appendChild(dom); + dom = wrap.dom; + } + } + return dom + }; + + DOMSerializer.prototype.serializeMark = function serializeMark (mark, inline, options) { + if ( options === void 0 ) options = {}; + + var toDOM = this.marks[mark.type.name]; + return toDOM && DOMSerializer.renderSpec(doc$1(options), toDOM(mark, inline)) + }; + + // :: (dom.Document, DOMOutputSpec) → {dom: dom.Node, contentDOM: ?dom.Node} + // Render an [output spec](#model.DOMOutputSpec) to a DOM node. If + // the spec has a hole (zero) in it, `contentDOM` will point at the + // node with the hole. + DOMSerializer.renderSpec = function renderSpec (doc, structure, xmlNS) { + if ( xmlNS === void 0 ) xmlNS = null; + + if (typeof structure == "string") + { return {dom: doc.createTextNode(structure)} } + if (structure.nodeType != null) + { return {dom: structure} } + if (structure.dom && structure.dom.nodeType != null) + { return structure } + var tagName = structure[0], space = tagName.indexOf(" "); + if (space > 0) { + xmlNS = tagName.slice(0, space); + tagName = tagName.slice(space + 1); + } + var contentDOM = null, dom = xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName); + var attrs = structure[1], start = 1; + if (attrs && typeof attrs == "object" && attrs.nodeType == null && !Array.isArray(attrs)) { + start = 2; + for (var name in attrs) { if (attrs[name] != null) { + var space$1 = name.indexOf(" "); + if (space$1 > 0) { dom.setAttributeNS(name.slice(0, space$1), name.slice(space$1 + 1), attrs[name]); } + else { dom.setAttribute(name, attrs[name]); } + } } + } + for (var i = start; i < structure.length; i++) { + var child = structure[i]; + if (child === 0) { + if (i < structure.length - 1 || i > start) + { throw new RangeError("Content hole must be the only child of its parent node") } + return {dom: dom, contentDOM: dom} + } else { + var ref = DOMSerializer.renderSpec(doc, child, xmlNS); + var inner = ref.dom; + var innerContent = ref.contentDOM; + dom.appendChild(inner); + if (innerContent) { + if (contentDOM) { throw new RangeError("Multiple content holes") } + contentDOM = innerContent; + } + } + } + return {dom: dom, contentDOM: contentDOM} + }; + + // :: (Schema) → DOMSerializer + // Build a serializer using the [`toDOM`](#model.NodeSpec.toDOM) + // properties in a schema's node and mark specs. + DOMSerializer.fromSchema = function fromSchema (schema) { + return schema.cached.domSerializer || + (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema))) + }; + + // : (Schema) → Object<(node: Node) → DOMOutputSpec> + // Gather the serializers in a schema's node specs into an object. + // This can be useful as a base to build a custom serializer from. + DOMSerializer.nodesFromSchema = function nodesFromSchema (schema) { + var result = gatherToDOM(schema.nodes); + if (!result.text) { result.text = function (node) { return node.text; }; } + return result + }; + + // : (Schema) → Object<(mark: Mark) → DOMOutputSpec> + // Gather the serializers in a schema's mark specs into an object. + DOMSerializer.marksFromSchema = function marksFromSchema (schema) { + return gatherToDOM(schema.marks) + }; + + function gatherToDOM(obj) { + var result = {}; + for (var name in obj) { + var toDOM = obj[name].spec.toDOM; + if (toDOM) { result[name] = toDOM; } + } + return result + } + + function doc$1(options) { + // declare global: window + return options.document || window.document + } + + // Mappable:: interface + // There are several things that positions can be mapped through. + // Such objects conform to this interface. + // + // map:: (pos: number, assoc: ?number) → number + // Map a position through this object. When given, `assoc` (should + // be -1 or 1, defaults to 1) determines with which side the + // position is associated, which determines in which direction to + // move when a chunk of content is inserted at the mapped position. + // + // mapResult:: (pos: number, assoc: ?number) → MapResult + // Map a position, and return an object containing additional + // information about the mapping. The result's `deleted` field tells + // you whether the position was deleted (completely enclosed in a + // replaced range) during the mapping. When content on only one side + // is deleted, the position itself is only considered deleted when + // `assoc` points in the direction of the deleted content. + + // Recovery values encode a range index and an offset. They are + // represented as numbers, because tons of them will be created when + // mapping, for example, a large number of decorations. The number's + // lower 16 bits provide the index, the remaining bits the offset. + // + // Note: We intentionally don't use bit shift operators to en- and + // decode these, since those clip to 32 bits, which we might in rare + // cases want to overflow. A 64-bit float can represent 48-bit + // integers precisely. + + var lower16 = 0xffff; + var factor16 = Math.pow(2, 16); + + function makeRecover(index, offset) { return index + offset * factor16 } + function recoverIndex(value) { return value & lower16 } + function recoverOffset(value) { return (value - (value & lower16)) / factor16 } + + // ::- An object representing a mapped position with extra + // information. + var MapResult = function MapResult(pos, deleted, recover) { + if ( deleted === void 0 ) deleted = false; + if ( recover === void 0 ) recover = null; + + // :: number The mapped version of the position. + this.pos = pos; + // :: bool Tells you whether the position was deleted, that is, + // whether the step removed its surroundings from the document. + this.deleted = deleted; + this.recover = recover; + }; + + // :: class extends Mappable + // A map describing the deletions and insertions made by a step, which + // can be used to find the correspondence between positions in the + // pre-step version of a document and the same position in the + // post-step version. + var StepMap = function StepMap(ranges, inverted) { + if ( inverted === void 0 ) inverted = false; + + this.ranges = ranges; + this.inverted = inverted; + }; + + StepMap.prototype.recover = function recover (value) { + var diff = 0, index = recoverIndex(value); + if (!this.inverted) { for (var i = 0; i < index; i++) + { diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1]; } } + return this.ranges[index * 3] + diff + recoverOffset(value) + }; + + // : (number, ?number) → MapResult + StepMap.prototype.mapResult = function mapResult (pos, assoc) { + if ( assoc === void 0 ) assoc = 1; + return this._map(pos, assoc, false) }; + + // : (number, ?number) → number + StepMap.prototype.map = function map (pos, assoc) { + if ( assoc === void 0 ) assoc = 1; + return this._map(pos, assoc, true) }; + + StepMap.prototype._map = function _map (pos, assoc, simple) { + var diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; + for (var i = 0; i < this.ranges.length; i += 3) { + var start = this.ranges[i] - (this.inverted ? diff : 0); + if (start > pos) { break } + var oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize; + if (pos <= end) { + var side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc; + var result = start + diff + (side < 0 ? 0 : newSize); + if (simple) { return result } + var recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start); + return new MapResult(result, assoc < 0 ? pos != start : pos != end, recover) + } + diff += newSize - oldSize; + } + return simple ? pos + diff : new MapResult(pos + diff) + }; + + StepMap.prototype.touches = function touches (pos, recover) { + var diff = 0, index = recoverIndex(recover); + var oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; + for (var i = 0; i < this.ranges.length; i += 3) { + var start = this.ranges[i] - (this.inverted ? diff : 0); + if (start > pos) { break } + var oldSize = this.ranges[i + oldIndex], end = start + oldSize; + if (pos <= end && i == index * 3) { return true } + diff += this.ranges[i + newIndex] - oldSize; + } + return false + }; + + // :: ((oldStart: number, oldEnd: number, newStart: number, newEnd: number)) + // Calls the given function on each of the changed ranges included in + // this map. + StepMap.prototype.forEach = function forEach (f) { + var oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; + for (var i = 0, diff = 0; i < this.ranges.length; i += 3) { + var start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff); + var oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex]; + f(oldStart, oldStart + oldSize, newStart, newStart + newSize); + diff += newSize - oldSize; + } + }; + + // :: () → StepMap + // Create an inverted version of this map. The result can be used to + // map positions in the post-step document to the pre-step document. + StepMap.prototype.invert = function invert () { + return new StepMap(this.ranges, !this.inverted) + }; + + StepMap.prototype.toString = function toString () { + return (this.inverted ? "-" : "") + JSON.stringify(this.ranges) + }; + + // :: (n: number) → StepMap + // Create a map that moves all positions by offset `n` (which may be + // negative). This can be useful when applying steps meant for a + // sub-document to a larger document, or vice-versa. + StepMap.offset = function offset (n) { + return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]) + }; + + StepMap.empty = new StepMap([]); + + // :: class extends Mappable + // A mapping represents a pipeline of zero or more [step + // maps](#transform.StepMap). It has special provisions for losslessly + // handling mapping positions through a series of steps in which some + // steps are inverted versions of earlier steps. (This comes up when + // ‘[rebasing](/docs/guide/#transform.rebasing)’ steps for + // collaboration or history management.) + var Mapping = function Mapping(maps, mirror, from, to) { + // :: [StepMap] + // The step maps in this mapping. + this.maps = maps || []; + // :: number + // The starting position in the `maps` array, used when `map` or + // `mapResult` is called. + this.from = from || 0; + // :: number + // The end position in the `maps` array. + this.to = to == null ? this.maps.length : to; + this.mirror = mirror; + }; + + // :: (?number, ?number) → Mapping + // Create a mapping that maps only through a part of this one. + Mapping.prototype.slice = function slice (from, to) { + if ( from === void 0 ) from = 0; + if ( to === void 0 ) to = this.maps.length; + + return new Mapping(this.maps, this.mirror, from, to) + }; + + Mapping.prototype.copy = function copy () { + return new Mapping(this.maps.slice(), this.mirror && this.mirror.slice(), this.from, this.to) + }; + + // :: (StepMap, ?number) + // Add a step map to the end of this mapping. If `mirrors` is + // given, it should be the index of the step map that is the mirror + // image of this one. + Mapping.prototype.appendMap = function appendMap (map, mirrors) { + this.to = this.maps.push(map); + if (mirrors != null) { this.setMirror(this.maps.length - 1, mirrors); } + }; + + // :: (Mapping) + // Add all the step maps in a given mapping to this one (preserving + // mirroring information). + Mapping.prototype.appendMapping = function appendMapping (mapping) { + for (var i = 0, startSize = this.maps.length; i < mapping.maps.length; i++) { + var mirr = mapping.getMirror(i); + this.appendMap(mapping.maps[i], mirr != null && mirr < i ? startSize + mirr : null); + } + }; + + // :: (number) → ?number + // Finds the offset of the step map that mirrors the map at the + // given offset, in this mapping (as per the second argument to + // `appendMap`). + Mapping.prototype.getMirror = function getMirror (n) { + if (this.mirror) { for (var i = 0; i < this.mirror.length; i++) + { if (this.mirror[i] == n) { return this.mirror[i + (i % 2 ? -1 : 1)] } } } + }; + + Mapping.prototype.setMirror = function setMirror (n, m) { + if (!this.mirror) { this.mirror = []; } + this.mirror.push(n, m); + }; + + // :: (Mapping) + // Append the inverse of the given mapping to this one. + Mapping.prototype.appendMappingInverted = function appendMappingInverted (mapping) { + for (var i = mapping.maps.length - 1, totalSize = this.maps.length + mapping.maps.length; i >= 0; i--) { + var mirr = mapping.getMirror(i); + this.appendMap(mapping.maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : null); + } + }; + + // :: () → Mapping + // Create an inverted version of this mapping. + Mapping.prototype.invert = function invert () { + var inverse = new Mapping; + inverse.appendMappingInverted(this); + return inverse + }; + + // : (number, ?number) → number + // Map a position through this mapping. + Mapping.prototype.map = function map (pos, assoc) { + if ( assoc === void 0 ) assoc = 1; + + if (this.mirror) { return this._map(pos, assoc, true) } + for (var i = this.from; i < this.to; i++) + { pos = this.maps[i].map(pos, assoc); } + return pos + }; + + // : (number, ?number) → MapResult + // Map a position through this mapping, returning a mapping + // result. + Mapping.prototype.mapResult = function mapResult (pos, assoc) { + if ( assoc === void 0 ) assoc = 1; + return this._map(pos, assoc, false) }; + + Mapping.prototype._map = function _map (pos, assoc, simple) { + var deleted = false; + + for (var i = this.from; i < this.to; i++) { + var map = this.maps[i], result = map.mapResult(pos, assoc); + if (result.recover != null) { + var corr = this.getMirror(i); + if (corr != null && corr > i && corr < this.to) { + i = corr; + pos = this.maps[corr].recover(result.recover); + continue + } + } + + if (result.deleted) { deleted = true; } + pos = result.pos; + } + + return simple ? pos : new MapResult(pos, deleted) + }; + + function TransformError(message) { + var err = Error.call(this, message); + err.__proto__ = TransformError.prototype; + return err + } + + TransformError.prototype = Object.create(Error.prototype); + TransformError.prototype.constructor = TransformError; + TransformError.prototype.name = "TransformError"; + + // ::- Abstraction to build up and track an array of + // [steps](#transform.Step) representing a document transformation. + // + // Most transforming methods return the `Transform` object itself, so + // that they can be chained. + var Transform = function Transform(doc) { + // :: Node + // The current document (the result of applying the steps in the + // transform). + this.doc = doc; + // :: [Step] + // The steps in this transform. + this.steps = []; + // :: [Node] + // The documents before each of the steps. + this.docs = []; + // :: Mapping + // A mapping with the maps for each of the steps in this transform. + this.mapping = new Mapping; + }; + + var prototypeAccessors$7 = { before: { configurable: true },docChanged: { configurable: true } }; + + // :: Node The starting document. + prototypeAccessors$7.before.get = function () { return this.docs.length ? this.docs[0] : this.doc }; + + // :: (step: Step) → this + // Apply a new step in this transform, saving the result. Throws an + // error when the step fails. + Transform.prototype.step = function step (object) { + var result = this.maybeStep(object); + if (result.failed) { throw new TransformError(result.failed) } + return this + }; + + // :: (Step) → StepResult + // Try to apply a step in this transformation, ignoring it if it + // fails. Returns the step result. + Transform.prototype.maybeStep = function maybeStep (step) { + var result = step.apply(this.doc); + if (!result.failed) { this.addStep(step, result.doc); } + return result + }; + + // :: bool + // True when the document has been changed (when there are any + // steps). + prototypeAccessors$7.docChanged.get = function () { + return this.steps.length > 0 + }; + + Transform.prototype.addStep = function addStep (step, doc) { + this.docs.push(this.doc); + this.steps.push(step); + this.mapping.appendMap(step.getMap()); + this.doc = doc; + }; + + Object.defineProperties( Transform.prototype, prototypeAccessors$7 ); + + function mustOverride() { throw new Error("Override me") } + + var stepsByID = Object.create(null); + + // ::- A step object represents an atomic change. It generally applies + // only to the document it was created for, since the positions + // stored in it will only make sense for that document. + // + // New steps are defined by creating classes that extend `Step`, + // overriding the `apply`, `invert`, `map`, `getMap` and `fromJSON` + // methods, and registering your class with a unique + // JSON-serialization identifier using + // [`Step.jsonID`](#transform.Step^jsonID). + var Step = function Step () {}; + + Step.prototype.apply = function apply (_doc) { return mustOverride() }; + + // :: () → StepMap + // Get the step map that represents the changes made by this step, + // and which can be used to transform between positions in the old + // and the new document. + Step.prototype.getMap = function getMap () { return StepMap.empty }; + + // :: (doc: Node) → Step + // Create an inverted version of this step. Needs the document as it + // was before the step as argument. + Step.prototype.invert = function invert (_doc) { return mustOverride() }; + + // :: (mapping: Mappable) → ?Step + // Map this step through a mappable thing, returning either a + // version of that step with its positions adjusted, or `null` if + // the step was entirely deleted by the mapping. + Step.prototype.map = function map (_mapping) { return mustOverride() }; + + // :: (other: Step) → ?Step + // Try to merge this step with another one, to be applied directly + // after it. Returns the merged step when possible, null if the + // steps can't be merged. + Step.prototype.merge = function merge (_other) { return null }; + + // :: () → Object + // Create a JSON-serializeable representation of this step. When + // defining this for a custom subclass, make sure the result object + // includes the step type's [JSON id](#transform.Step^jsonID) under + // the `stepType` property. + Step.prototype.toJSON = function toJSON () { return mustOverride() }; + + // :: (Schema, Object) → Step + // Deserialize a step from its JSON representation. Will call + // through to the step class' own implementation of this method. + Step.fromJSON = function fromJSON (schema, json) { + if (!json || !json.stepType) { throw new RangeError("Invalid input for Step.fromJSON") } + var type = stepsByID[json.stepType]; + if (!type) { throw new RangeError(("No step type " + (json.stepType) + " defined")) } + return type.fromJSON(schema, json) + }; + + // :: (string, constructor) + // To be able to serialize steps to JSON, each step needs a string + // ID to attach to its JSON representation. Use this method to + // register an ID for your step classes. Try to pick something + // that's unlikely to clash with steps from other modules. + Step.jsonID = function jsonID (id, stepClass) { + if (id in stepsByID) { throw new RangeError("Duplicate use of step JSON ID " + id) } + stepsByID[id] = stepClass; + stepClass.prototype.jsonID = id; + return stepClass + }; + + // ::- The result of [applying](#transform.Step.apply) a step. Contains either a + // new document or a failure value. + var StepResult = function StepResult(doc, failed) { + // :: ?Node The transformed document. + this.doc = doc; + // :: ?string Text providing information about a failed step. + this.failed = failed; + }; + + // :: (Node) → StepResult + // Create a successful step result. + StepResult.ok = function ok (doc) { return new StepResult(doc, null) }; + + // :: (string) → StepResult + // Create a failed step result. + StepResult.fail = function fail (message) { return new StepResult(null, message) }; + + // :: (Node, number, number, Slice) → StepResult + // Call [`Node.replace`](#model.Node.replace) with the given + // arguments. Create a successful result if it succeeds, and a + // failed one if it throws a `ReplaceError`. + StepResult.fromReplace = function fromReplace (doc, from, to, slice) { + try { + return StepResult.ok(doc.replace(from, to, slice)) + } catch (e) { + if (e instanceof ReplaceError) { return StepResult.fail(e.message) } + throw e + } + }; + + // ::- Replace a part of the document with a slice of new content. + var ReplaceStep = /*@__PURE__*/(function (Step) { + function ReplaceStep(from, to, slice, structure) { + Step.call(this); + this.from = from; + this.to = to; + this.slice = slice; + this.structure = !!structure; + } + + if ( Step ) ReplaceStep.__proto__ = Step; + ReplaceStep.prototype = Object.create( Step && Step.prototype ); + ReplaceStep.prototype.constructor = ReplaceStep; + + ReplaceStep.prototype.apply = function apply (doc) { + if (this.structure && contentBetween(doc, this.from, this.to)) + { return StepResult.fail("Structure replace would overwrite content") } + return StepResult.fromReplace(doc, this.from, this.to, this.slice) + }; + + ReplaceStep.prototype.getMap = function getMap () { + return new StepMap([this.from, this.to - this.from, this.slice.size]) + }; + + ReplaceStep.prototype.invert = function invert (doc) { + return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to)) + }; + + ReplaceStep.prototype.map = function map (mapping) { + var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); + if (from.deleted && to.deleted) { return null } + return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice) + }; + + ReplaceStep.prototype.merge = function merge (other) { + if (!(other instanceof ReplaceStep) || other.structure != this.structure) { return null } + + if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) { + var slice = this.slice.size + other.slice.size == 0 ? Slice.empty + : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd); + return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure) + } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) { + var slice$1 = this.slice.size + other.slice.size == 0 ? Slice.empty + : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd); + return new ReplaceStep(other.from, this.to, slice$1, this.structure) + } else { + return null + } + }; + + ReplaceStep.prototype.toJSON = function toJSON () { + var json = {stepType: "replace", from: this.from, to: this.to}; + if (this.slice.size) { json.slice = this.slice.toJSON(); } + if (this.structure) { json.structure = true; } + return json + }; + + ReplaceStep.fromJSON = function fromJSON (schema, json) { + if (typeof json.from != "number" || typeof json.to != "number") + { throw new RangeError("Invalid input for ReplaceStep.fromJSON") } + return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure) + }; + + return ReplaceStep; + }(Step)); + + Step.jsonID("replace", ReplaceStep); + + // ::- Replace a part of the document with a slice of content, but + // preserve a range of the replaced content by moving it into the + // slice. + var ReplaceAroundStep = /*@__PURE__*/(function (Step) { + function ReplaceAroundStep(from, to, gapFrom, gapTo, slice, insert, structure) { + Step.call(this); + this.from = from; + this.to = to; + this.gapFrom = gapFrom; + this.gapTo = gapTo; + this.slice = slice; + this.insert = insert; + this.structure = !!structure; + } + + if ( Step ) ReplaceAroundStep.__proto__ = Step; + ReplaceAroundStep.prototype = Object.create( Step && Step.prototype ); + ReplaceAroundStep.prototype.constructor = ReplaceAroundStep; + + ReplaceAroundStep.prototype.apply = function apply (doc) { + if (this.structure && (contentBetween(doc, this.from, this.gapFrom) || + contentBetween(doc, this.gapTo, this.to))) + { return StepResult.fail("Structure gap-replace would overwrite content") } + + var gap = doc.slice(this.gapFrom, this.gapTo); + if (gap.openStart || gap.openEnd) + { return StepResult.fail("Gap is not a flat range") } + var inserted = this.slice.insertAt(this.insert, gap.content); + if (!inserted) { return StepResult.fail("Content does not fit in gap") } + return StepResult.fromReplace(doc, this.from, this.to, inserted) + }; + + ReplaceAroundStep.prototype.getMap = function getMap () { + return new StepMap([this.from, this.gapFrom - this.from, this.insert, + this.gapTo, this.to - this.gapTo, this.slice.size - this.insert]) + }; + + ReplaceAroundStep.prototype.invert = function invert (doc) { + var gap = this.gapTo - this.gapFrom; + return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, + this.from + this.insert, this.from + this.insert + gap, + doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), + this.gapFrom - this.from, this.structure) + }; + + ReplaceAroundStep.prototype.map = function map (mapping) { + var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); + var gapFrom = mapping.map(this.gapFrom, -1), gapTo = mapping.map(this.gapTo, 1); + if ((from.deleted && to.deleted) || gapFrom < from.pos || gapTo > to.pos) { return null } + return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure) + }; + + ReplaceAroundStep.prototype.toJSON = function toJSON () { + var json = {stepType: "replaceAround", from: this.from, to: this.to, + gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert}; + if (this.slice.size) { json.slice = this.slice.toJSON(); } + if (this.structure) { json.structure = true; } + return json + }; + + ReplaceAroundStep.fromJSON = function fromJSON (schema, json) { + if (typeof json.from != "number" || typeof json.to != "number" || + typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number") + { throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON") } + return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, + Slice.fromJSON(schema, json.slice), json.insert, !!json.structure) + }; + + return ReplaceAroundStep; + }(Step)); + + Step.jsonID("replaceAround", ReplaceAroundStep); + + function contentBetween(doc, from, to) { + var $from = doc.resolve(from), dist = to - from, depth = $from.depth; + while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) { + depth--; + dist--; + } + if (dist > 0) { + var next = $from.node(depth).maybeChild($from.indexAfter(depth)); + while (dist > 0) { + if (!next || next.isLeaf) { return true } + next = next.firstChild; + dist--; + } + } + return false + } + + function canCut(node, start, end) { + return (start == 0 || node.canReplace(start, node.childCount)) && + (end == node.childCount || node.canReplace(0, end)) + } + + // :: (NodeRange) → ?number + // Try to find a target depth to which the content in the given range + // can be lifted. Will not go across + // [isolating](#model.NodeSpec.isolating) parent nodes. + function liftTarget(range) { + var parent = range.parent; + var content = parent.content.cutByIndex(range.startIndex, range.endIndex); + for (var depth = range.depth;; --depth) { + var node = range.$from.node(depth); + var index = range.$from.index(depth), endIndex = range.$to.indexAfter(depth); + if (depth < range.depth && node.canReplace(index, endIndex, content)) + { return depth } + if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex)) { break } + } + } + + // :: (NodeRange, number) → this + // Split the content in the given range off from its parent, if there + // is sibling content before or after it, and move it up the tree to + // the depth specified by `target`. You'll probably want to use + // [`liftTarget`](#transform.liftTarget) to compute `target`, to make + // sure the lift is valid. + Transform.prototype.lift = function(range, target) { + var $from = range.$from; + var $to = range.$to; + var depth = range.depth; + + var gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1); + var start = gapStart, end = gapEnd; + + var before = Fragment.empty, openStart = 0; + for (var d = depth, splitting = false; d > target; d--) + { if (splitting || $from.index(d) > 0) { + splitting = true; + before = Fragment.from($from.node(d).copy(before)); + openStart++; + } else { + start--; + } } + var after = Fragment.empty, openEnd = 0; + for (var d$1 = depth, splitting$1 = false; d$1 > target; d$1--) + { if (splitting$1 || $to.after(d$1 + 1) < $to.end(d$1)) { + splitting$1 = true; + after = Fragment.from($to.node(d$1).copy(after)); + openEnd++; + } else { + end++; + } } + + return this.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, + new Slice(before.append(after), openStart, openEnd), + before.size - openStart, true)) + }; + + // :: (NodeRange, NodeType, ?Object, ?NodeRange) → ?[{type: NodeType, attrs: ?Object}] + // Try to find a valid way to wrap the content in the given range in a + // node of the given type. May introduce extra nodes around and inside + // the wrapper node, if necessary. Returns null if no valid wrapping + // could be found. When `innerRange` is given, that range's content is + // used as the content to fit into the wrapping, instead of the + // content of `range`. + function findWrapping(range, nodeType, attrs, innerRange) { + if ( innerRange === void 0 ) innerRange = range; + + var around = findWrappingOutside(range, nodeType); + var inner = around && findWrappingInside(innerRange, nodeType); + if (!inner) { return null } + return around.map(withAttrs).concat({type: nodeType, attrs: attrs}).concat(inner.map(withAttrs)) + } + + function withAttrs(type) { return {type: type, attrs: null} } + + function findWrappingOutside(range, type) { + var parent = range.parent; + var startIndex = range.startIndex; + var endIndex = range.endIndex; + var around = parent.contentMatchAt(startIndex).findWrapping(type); + if (!around) { return null } + var outer = around.length ? around[0] : type; + return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null + } + + function findWrappingInside(range, type) { + var parent = range.parent; + var startIndex = range.startIndex; + var endIndex = range.endIndex; + var inner = parent.child(startIndex); + var inside = type.contentMatch.findWrapping(inner.type); + if (!inside) { return null } + var lastType = inside.length ? inside[inside.length - 1] : type; + var innerMatch = lastType.contentMatch; + for (var i = startIndex; innerMatch && i < endIndex; i++) + { innerMatch = innerMatch.matchType(parent.child(i).type); } + if (!innerMatch || !innerMatch.validEnd) { return null } + return inside + } + + // :: (NodeRange, [{type: NodeType, attrs: ?Object}]) → this + // Wrap the given [range](#model.NodeRange) in the given set of wrappers. + // The wrappers are assumed to be valid in this position, and should + // probably be computed with [`findWrapping`](#transform.findWrapping). + Transform.prototype.wrap = function(range, wrappers) { + var content = Fragment.empty; + for (var i = wrappers.length - 1; i >= 0; i--) + { content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content)); } + + var start = range.start, end = range.end; + return this.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true)) + }; + + // :: (number, ?number, NodeType, ?Object) → this + // Set the type of all textblocks (partly) between `from` and `to` to + // the given node type with the given attributes. + Transform.prototype.setBlockType = function(from, to, type, attrs) { + var this$1 = this; + if ( to === void 0 ) to = from; + + if (!type.isTextblock) { throw new RangeError("Type given to setBlockType should be a textblock") } + var mapFrom = this.steps.length; + this.doc.nodesBetween(from, to, function (node, pos) { + if (node.isTextblock && !node.hasMarkup(type, attrs) && canChangeType(this$1.doc, this$1.mapping.slice(mapFrom).map(pos), type)) { + // Ensure all markup that isn't allowed in the new node type is cleared + this$1.clearIncompatible(this$1.mapping.slice(mapFrom).map(pos, 1), type); + var mapping = this$1.mapping.slice(mapFrom); + var startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1); + this$1.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, + new Slice(Fragment.from(type.create(attrs, null, node.marks)), 0, 0), 1, true)); + return false + } + }); + return this + }; + + function canChangeType(doc, pos, type) { + var $pos = doc.resolve(pos), index = $pos.index(); + return $pos.parent.canReplaceWith(index, index + 1, type) + } + + // :: (number, ?NodeType, ?Object, ?[Mark]) → this + // Change the type, attributes, and/or marks of the node at `pos`. + // When `type` isn't given, the existing node type is preserved, + Transform.prototype.setNodeMarkup = function(pos, type, attrs, marks) { + var node = this.doc.nodeAt(pos); + if (!node) { throw new RangeError("No node at given position") } + if (!type) { type = node.type; } + var newNode = type.create(attrs, null, marks || node.marks); + if (node.isLeaf) + { return this.replaceWith(pos, pos + node.nodeSize, newNode) } + + if (!type.validContent(node.content)) + { throw new RangeError("Invalid content for node type " + type.name) } + + return this.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, + new Slice(Fragment.from(newNode), 0, 0), 1, true)) + }; + + // :: (Node, number, number, ?[?{type: NodeType, attrs: ?Object}]) → bool + // Check whether splitting at the given position is allowed. + function canSplit(doc, pos, depth, typesAfter) { + if ( depth === void 0 ) depth = 1; + + var $pos = doc.resolve(pos), base = $pos.depth - depth; + var innerType = (typesAfter && typesAfter[typesAfter.length - 1]) || $pos.parent; + if (base < 0 || $pos.parent.type.spec.isolating || + !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) || + !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount))) + { return false } + for (var d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) { + var node = $pos.node(d), index$1 = $pos.index(d); + if (node.type.spec.isolating) { return false } + var rest = node.content.cutByIndex(index$1, node.childCount); + var after = (typesAfter && typesAfter[i]) || node; + if (after != node) { rest = rest.replaceChild(0, after.type.create(after.attrs)); } + if (!node.canReplace(index$1 + 1, node.childCount) || !after.type.validContent(rest)) + { return false } + } + var index = $pos.indexAfter(base); + var baseType = typesAfter && typesAfter[0]; + return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type) + } + + // :: (number, ?number, ?[?{type: NodeType, attrs: ?Object}]) → this + // Split the node at the given position, and optionally, if `depth` is + // greater than one, any number of nodes above that. By default, the + // parts split off will inherit the node type of the original node. + // This can be changed by passing an array of types and attributes to + // use after the split. + Transform.prototype.split = function(pos, depth, typesAfter) { + if ( depth === void 0 ) depth = 1; + + var $pos = this.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty; + for (var d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) { + before = Fragment.from($pos.node(d).copy(before)); + var typeAfter = typesAfter && typesAfter[i]; + after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after)); + } + return this.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true)) + }; + + // :: (Node, number) → bool + // Test whether the blocks before and after a given position can be + // joined. + function canJoin(doc, pos) { + var $pos = doc.resolve(pos), index = $pos.index(); + return joinable$1($pos.nodeBefore, $pos.nodeAfter) && + $pos.parent.canReplace(index, index + 1) + } + + function joinable$1(a, b) { + return a && b && !a.isLeaf && a.canAppend(b) + } + + // :: (Node, number, ?number) → ?number + // Find an ancestor of the given position that can be joined to the + // block before (or after if `dir` is positive). Returns the joinable + // point, if any. + function joinPoint(doc, pos, dir) { + if ( dir === void 0 ) dir = -1; + + var $pos = doc.resolve(pos); + for (var d = $pos.depth;; d--) { + var before = (void 0), after = (void 0), index = $pos.index(d); + if (d == $pos.depth) { + before = $pos.nodeBefore; + after = $pos.nodeAfter; + } else if (dir > 0) { + before = $pos.node(d + 1); + index++; + after = $pos.node(d).maybeChild(index); + } else { + before = $pos.node(d).maybeChild(index - 1); + after = $pos.node(d + 1); + } + if (before && !before.isTextblock && joinable$1(before, after) && + $pos.node(d).canReplace(index, index + 1)) { return pos } + if (d == 0) { break } + pos = dir < 0 ? $pos.before(d) : $pos.after(d); + } + } + + // :: (number, ?number) → this + // Join the blocks around the given position. If depth is 2, their + // last and first siblings are also joined, and so on. + Transform.prototype.join = function(pos, depth) { + if ( depth === void 0 ) depth = 1; + + var step = new ReplaceStep(pos - depth, pos + depth, Slice.empty, true); + return this.step(step) + }; + + // :: (Node, number, NodeType) → ?number + // Try to find a point where a node of the given type can be inserted + // near `pos`, by searching up the node hierarchy when `pos` itself + // isn't a valid place but is at the start or end of a node. Return + // null if no position was found. + function insertPoint(doc, pos, nodeType) { + var $pos = doc.resolve(pos); + if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType)) { return pos } + + if ($pos.parentOffset == 0) + { for (var d = $pos.depth - 1; d >= 0; d--) { + var index = $pos.index(d); + if ($pos.node(d).canReplaceWith(index, index, nodeType)) { return $pos.before(d + 1) } + if (index > 0) { return null } + } } + if ($pos.parentOffset == $pos.parent.content.size) + { for (var d$1 = $pos.depth - 1; d$1 >= 0; d$1--) { + var index$1 = $pos.indexAfter(d$1); + if ($pos.node(d$1).canReplaceWith(index$1, index$1, nodeType)) { return $pos.after(d$1 + 1) } + if (index$1 < $pos.node(d$1).childCount) { return null } + } } + } + + // :: (Node, number, Slice) → ?number + // Finds a position at or around the given position where the given + // slice can be inserted. Will look at parent nodes' nearest boundary + // and try there, even if the original position wasn't directly at the + // start or end of that node. Returns null when no position was found. + function dropPoint(doc, pos, slice) { + var $pos = doc.resolve(pos); + if (!slice.content.size) { return pos } + var content = slice.content; + for (var i = 0; i < slice.openStart; i++) { content = content.firstChild.content; } + for (var pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) { + for (var d = $pos.depth; d >= 0; d--) { + var bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1; + var insertPos = $pos.index(d) + (bias > 0 ? 1 : 0); + if (pass == 1 + ? $pos.node(d).canReplace(insertPos, insertPos, content) + : $pos.node(d).contentMatchAt(insertPos).findWrapping(content.firstChild.type)) + { return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1) } + } + } + return null + } + + function mapFragment(fragment, f, parent) { + var mapped = []; + for (var i = 0; i < fragment.childCount; i++) { + var child = fragment.child(i); + if (child.content.size) { child = child.copy(mapFragment(child.content, f, child)); } + if (child.isInline) { child = f(child, parent, i); } + mapped.push(child); + } + return Fragment.fromArray(mapped) + } + + // ::- Add a mark to all inline content between two positions. + var AddMarkStep = /*@__PURE__*/(function (Step) { + function AddMarkStep(from, to, mark) { + Step.call(this); + this.from = from; + this.to = to; + this.mark = mark; + } + + if ( Step ) AddMarkStep.__proto__ = Step; + AddMarkStep.prototype = Object.create( Step && Step.prototype ); + AddMarkStep.prototype.constructor = AddMarkStep; + + AddMarkStep.prototype.apply = function apply (doc) { + var this$1 = this; + + var oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from); + var parent = $from.node($from.sharedDepth(this.to)); + var slice = new Slice(mapFragment(oldSlice.content, function (node, parent) { + if (!parent.type.allowsMarkType(this$1.mark.type)) { return node } + return node.mark(this$1.mark.addToSet(node.marks)) + }, parent), oldSlice.openStart, oldSlice.openEnd); + return StepResult.fromReplace(doc, this.from, this.to, slice) + }; + + AddMarkStep.prototype.invert = function invert () { + return new RemoveMarkStep(this.from, this.to, this.mark) + }; + + AddMarkStep.prototype.map = function map (mapping) { + var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); + if (from.deleted && to.deleted || from.pos >= to.pos) { return null } + return new AddMarkStep(from.pos, to.pos, this.mark) + }; + + AddMarkStep.prototype.merge = function merge (other) { + if (other instanceof AddMarkStep && + other.mark.eq(this.mark) && + this.from <= other.to && this.to >= other.from) + { return new AddMarkStep(Math.min(this.from, other.from), + Math.max(this.to, other.to), this.mark) } + }; + + AddMarkStep.prototype.toJSON = function toJSON () { + return {stepType: "addMark", mark: this.mark.toJSON(), + from: this.from, to: this.to} + }; + + AddMarkStep.fromJSON = function fromJSON (schema, json) { + if (typeof json.from != "number" || typeof json.to != "number") + { throw new RangeError("Invalid input for AddMarkStep.fromJSON") } + return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark)) + }; + + return AddMarkStep; + }(Step)); + + Step.jsonID("addMark", AddMarkStep); + + // ::- Remove a mark from all inline content between two positions. + var RemoveMarkStep = /*@__PURE__*/(function (Step) { + function RemoveMarkStep(from, to, mark) { + Step.call(this); + this.from = from; + this.to = to; + this.mark = mark; + } + + if ( Step ) RemoveMarkStep.__proto__ = Step; + RemoveMarkStep.prototype = Object.create( Step && Step.prototype ); + RemoveMarkStep.prototype.constructor = RemoveMarkStep; + + RemoveMarkStep.prototype.apply = function apply (doc) { + var this$1 = this; + + var oldSlice = doc.slice(this.from, this.to); + var slice = new Slice(mapFragment(oldSlice.content, function (node) { + return node.mark(this$1.mark.removeFromSet(node.marks)) + }), oldSlice.openStart, oldSlice.openEnd); + return StepResult.fromReplace(doc, this.from, this.to, slice) + }; + + RemoveMarkStep.prototype.invert = function invert () { + return new AddMarkStep(this.from, this.to, this.mark) + }; + + RemoveMarkStep.prototype.map = function map (mapping) { + var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); + if (from.deleted && to.deleted || from.pos >= to.pos) { return null } + return new RemoveMarkStep(from.pos, to.pos, this.mark) + }; + + RemoveMarkStep.prototype.merge = function merge (other) { + if (other instanceof RemoveMarkStep && + other.mark.eq(this.mark) && + this.from <= other.to && this.to >= other.from) + { return new RemoveMarkStep(Math.min(this.from, other.from), + Math.max(this.to, other.to), this.mark) } + }; + + RemoveMarkStep.prototype.toJSON = function toJSON () { + return {stepType: "removeMark", mark: this.mark.toJSON(), + from: this.from, to: this.to} + }; + + RemoveMarkStep.fromJSON = function fromJSON (schema, json) { + if (typeof json.from != "number" || typeof json.to != "number") + { throw new RangeError("Invalid input for RemoveMarkStep.fromJSON") } + return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark)) + }; + + return RemoveMarkStep; + }(Step)); + + Step.jsonID("removeMark", RemoveMarkStep); + + // :: (number, number, Mark) → this + // Add the given mark to the inline content between `from` and `to`. + Transform.prototype.addMark = function(from, to, mark) { + var this$1 = this; + + var removed = [], added = [], removing = null, adding = null; + this.doc.nodesBetween(from, to, function (node, pos, parent) { + if (!node.isInline) { return } + var marks = node.marks; + if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) { + var start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to); + var newSet = mark.addToSet(marks); + + for (var i = 0; i < marks.length; i++) { + if (!marks[i].isInSet(newSet)) { + if (removing && removing.to == start && removing.mark.eq(marks[i])) + { removing.to = end; } + else + { removed.push(removing = new RemoveMarkStep(start, end, marks[i])); } + } + } + + if (adding && adding.to == start) + { adding.to = end; } + else + { added.push(adding = new AddMarkStep(start, end, mark)); } + } + }); + + removed.forEach(function (s) { return this$1.step(s); }); + added.forEach(function (s) { return this$1.step(s); }); + return this + }; + + // :: (number, number, ?union) → this + // Remove marks from inline nodes between `from` and `to`. When `mark` + // is a single mark, remove precisely that mark. When it is a mark type, + // remove all marks of that type. When it is null, remove all marks of + // any type. + Transform.prototype.removeMark = function(from, to, mark) { + var this$1 = this; + if ( mark === void 0 ) mark = null; + + var matched = [], step = 0; + this.doc.nodesBetween(from, to, function (node, pos) { + if (!node.isInline) { return } + step++; + var toRemove = null; + if (mark instanceof MarkType) { + var found = mark.isInSet(node.marks); + if (found) { toRemove = [found]; } + } else if (mark) { + if (mark.isInSet(node.marks)) { toRemove = [mark]; } + } else { + toRemove = node.marks; + } + if (toRemove && toRemove.length) { + var end = Math.min(pos + node.nodeSize, to); + for (var i = 0; i < toRemove.length; i++) { + var style = toRemove[i], found$1 = (void 0); + for (var j = 0; j < matched.length; j++) { + var m = matched[j]; + if (m.step == step - 1 && style.eq(matched[j].style)) { found$1 = m; } + } + if (found$1) { + found$1.to = end; + found$1.step = step; + } else { + matched.push({style: style, from: Math.max(pos, from), to: end, step: step}); + } + } + } + }); + matched.forEach(function (m) { return this$1.step(new RemoveMarkStep(m.from, m.to, m.style)); }); + return this + }; + + // :: (number, NodeType, ?ContentMatch) → this + // Removes all marks and nodes from the content of the node at `pos` + // that don't match the given new parent node type. Accepts an + // optional starting [content match](#model.ContentMatch) as third + // argument. + Transform.prototype.clearIncompatible = function(pos, parentType, match) { + if ( match === void 0 ) match = parentType.contentMatch; + + var node = this.doc.nodeAt(pos); + var delSteps = [], cur = pos + 1; + for (var i = 0; i < node.childCount; i++) { + var child = node.child(i), end = cur + child.nodeSize; + var allowed = match.matchType(child.type, child.attrs); + if (!allowed) { + delSteps.push(new ReplaceStep(cur, end, Slice.empty)); + } else { + match = allowed; + for (var j = 0; j < child.marks.length; j++) { if (!parentType.allowsMarkType(child.marks[j].type)) + { this.step(new RemoveMarkStep(cur, end, child.marks[j])); } } + } + cur = end; + } + if (!match.validEnd) { + var fill = match.fillBefore(Fragment.empty, true); + this.replace(cur, cur, new Slice(fill, 0, 0)); + } + for (var i$1 = delSteps.length - 1; i$1 >= 0; i$1--) { this.step(delSteps[i$1]); } + return this + }; + + // :: (Node, number, ?number, ?Slice) → ?Step + // ‘Fit’ a slice into a given position in the document, producing a + // [step](#transform.Step) that inserts it. Will return null if + // there's no meaningful way to insert the slice here, or inserting it + // would be a no-op (an empty slice over an empty range). + function replaceStep(doc, from, to, slice) { + if ( to === void 0 ) to = from; + if ( slice === void 0 ) slice = Slice.empty; + + if (from == to && !slice.size) { return null } + + var $from = doc.resolve(from), $to = doc.resolve(to); + // Optimization -- avoid work if it's obvious that it's not needed. + if (fitsTrivially($from, $to, slice)) { return new ReplaceStep(from, to, slice) } + return new Fitter($from, $to, slice).fit() + } + + // :: (number, ?number, ?Slice) → this + // Replace the part of the document between `from` and `to` with the + // given `slice`. + Transform.prototype.replace = function(from, to, slice) { + if ( to === void 0 ) to = from; + if ( slice === void 0 ) slice = Slice.empty; + + var step = replaceStep(this.doc, from, to, slice); + if (step) { this.step(step); } + return this + }; + + // :: (number, number, union) → this + // Replace the given range with the given content, which may be a + // fragment, node, or array of nodes. + Transform.prototype.replaceWith = function(from, to, content) { + return this.replace(from, to, new Slice(Fragment.from(content), 0, 0)) + }; + + // :: (number, number) → this + // Delete the content between the given positions. + Transform.prototype.delete = function(from, to) { + return this.replace(from, to, Slice.empty) + }; + + // :: (number, union) → this + // Insert the given content at the given position. + Transform.prototype.insert = function(pos, content) { + return this.replaceWith(pos, pos, content) + }; + + function fitsTrivially($from, $to, slice) { + return !slice.openStart && !slice.openEnd && $from.start() == $to.start() && + $from.parent.canReplace($from.index(), $to.index(), slice.content) + } + + // Algorithm for 'placing' the elements of a slice into a gap: + // + // We consider the content of each node that is open to the left to be + // independently placeable. I.e. in , when the + // paragraph on the left is open, "foo" can be placed (somewhere on + // the left side of the replacement gap) independently from p("bar"). + // + // This class tracks the state of the placement progress in the + // following properties: + // + // - `frontier` holds a stack of `{type, match}` objects that + // represent the open side of the replacement. It starts at + // `$from`, then moves forward as content is placed, and is finally + // reconciled with `$to`. + // + // - `unplaced` is a slice that represents the content that hasn't + // been placed yet. + // + // - `placed` is a fragment of placed content. Its open-start value + // is implicit in `$from`, and its open-end value in `frontier`. + var Fitter = function Fitter($from, $to, slice) { + this.$to = $to; + this.$from = $from; + this.unplaced = slice; + + this.frontier = []; + for (var i = 0; i <= $from.depth; i++) { + var node = $from.node(i); + this.frontier.push({ + type: node.type, + match: node.contentMatchAt($from.indexAfter(i)) + }); + } + + this.placed = Fragment.empty; + for (var i$1 = $from.depth; i$1 > 0; i$1--) + { this.placed = Fragment.from($from.node(i$1).copy(this.placed)); } + }; + + var prototypeAccessors$1$4 = { depth: { configurable: true } }; + + prototypeAccessors$1$4.depth.get = function () { return this.frontier.length - 1 }; + + Fitter.prototype.fit = function fit () { + // As long as there's unplaced content, try to place some of it. + // If that fails, either increase the open score of the unplaced + // slice, or drop nodes from it, and then try again. + while (this.unplaced.size) { + var fit = this.findFittable(); + if (fit) { this.placeNodes(fit); } + else { this.openMore() || this.dropNode(); } + } + // When there's inline content directly after the frontier _and_ + // directly after `this.$to`, we must generate a `ReplaceAround` + // step that pulls that content into the node after the frontier. + // That means the fitting must be done to the end of the textblock + // node after `this.$to`, not `this.$to` itself. + var moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth; + var $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline)); + if (!$to) { return null } + + // If closing to `$to` succeeded, create a step + var content = this.placed, openStart = $from.depth, openEnd = $to.depth; + while (openStart && openEnd && content.childCount == 1) { // Normalize by dropping open parent nodes + content = content.firstChild.content; + openStart--; openEnd--; + } + var slice = new Slice(content, openStart, openEnd); + if (moveInline > -1) + { return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize) } + if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps + { return new ReplaceStep($from.pos, $to.pos, slice) } + }; + + // Find a position on the start spine of `this.unplaced` that has + // content that can be moved somewhere on the frontier. Returns two + // depths, one for the slice and one for the frontier. + Fitter.prototype.findFittable = function findFittable () { + // Only try wrapping nodes (pass 2) after finding a place without + // wrapping failed. + for (var pass = 1; pass <= 2; pass++) { + for (var sliceDepth = this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) { + var fragment = (void 0), parent = (void 0); + if (sliceDepth) { + parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild; + fragment = parent.content; + } else { + fragment = this.unplaced.content; + } + var first = fragment.firstChild; + for (var frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) { + var ref = this.frontier[frontierDepth]; + var type = ref.type; + var match = ref.match; + var wrap = (void 0), inject = (void 0); + // In pass 1, if the next node matches, or there is no next + // node but the parents look compatible, we've found a + // place. + if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false)) + : type.compatibleContent(parent.type))) + { return {sliceDepth: sliceDepth, frontierDepth: frontierDepth, parent: parent, inject: inject} } + // In pass 2, look for a set of wrapping nodes that make + // `first` fit here. + else if (pass == 2 && first && (wrap = match.findWrapping(first.type))) + { return {sliceDepth: sliceDepth, frontierDepth: frontierDepth, parent: parent, wrap: wrap} } + // Don't continue looking further up if the parent node + // would fit here. + if (parent && match.matchType(parent.type)) { break } + } + } + } + }; + + Fitter.prototype.openMore = function openMore () { + var ref = this.unplaced; + var content = ref.content; + var openStart = ref.openStart; + var openEnd = ref.openEnd; + var inner = contentAt(content, openStart); + if (!inner.childCount || inner.firstChild.isLeaf) { return false } + this.unplaced = new Slice(content, openStart + 1, + Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0)); + return true + }; + + Fitter.prototype.dropNode = function dropNode () { + var ref = this.unplaced; + var content = ref.content; + var openStart = ref.openStart; + var openEnd = ref.openEnd; + var inner = contentAt(content, openStart); + if (inner.childCount <= 1 && openStart > 0) { + var openAtEnd = content.size - openStart <= openStart + inner.size; + this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, + openAtEnd ? openStart - 1 : openEnd); + } else { + this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd); + } + }; + + // : ({sliceDepth: number, frontierDepth: number, parent: ?Node, wrap: ?[NodeType], inject: ?Fragment}) + // Move content from the unplaced slice at `sliceDepth` to the + // frontier node at `frontierDepth`. Close that frontier node when + // applicable. + Fitter.prototype.placeNodes = function placeNodes (ref) { + var sliceDepth = ref.sliceDepth; + var frontierDepth = ref.frontierDepth; + var parent = ref.parent; + var inject = ref.inject; + var wrap = ref.wrap; + + while (this.depth > frontierDepth) { this.closeFrontierNode(); } + if (wrap) { for (var i = 0; i < wrap.length; i++) { this.openFrontierNode(wrap[i]); } } + + var slice = this.unplaced, fragment = parent ? parent.content : slice.content; + var openStart = slice.openStart - sliceDepth; + var taken = 0, add = []; + var ref$1 = this.frontier[frontierDepth]; + var match = ref$1.match; + var type = ref$1.type; + if (inject) { + for (var i$1 = 0; i$1 < inject.childCount; i$1++) { add.push(inject.child(i$1)); } + match = match.matchFragment(inject); + } + // Computes the amount of (end) open nodes at the end of the + // fragment. When 0, the parent is open, but no more. When + // negative, nothing is open. + var openEndCount = (fragment.size + sliceDepth) - (slice.content.size - slice.openEnd); + // Scan over the fragment, fitting as many child nodes as + // possible. + while (taken < fragment.childCount) { + var next = fragment.child(taken), matches = match.matchType(next.type); + if (!matches) { break } + taken++; + if (taken > 1 || openStart == 0 || next.content.size) { // Drop empty open nodes + match = matches; + add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, + taken == fragment.childCount ? openEndCount : -1)); + } + } + var toEnd = taken == fragment.childCount; + if (!toEnd) { openEndCount = -1; } + + this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add)); + this.frontier[frontierDepth].match = match; + + // If the parent types match, and the entire node was moved, and + // it's not open, close this frontier node right away. + if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type) { this.closeFrontierNode(); } + + // Add new frontier nodes for any open nodes at the end. + for (var i$2 = 0, cur = fragment; i$2 < openEndCount; i$2++) { + var node = cur.lastChild; + this.frontier.push({type: node.type, match: node.contentMatchAt(node.childCount)}); + cur = node.content; + } + + // Update `this.unplaced`. Drop the entire node from which we + // placed it we got to its end, otherwise just drop the placed + // nodes. + this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd) + : sliceDepth == 0 ? Slice.empty + : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), + sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1); + }; + + Fitter.prototype.mustMoveInline = function mustMoveInline () { + if (!this.$to.parent.isTextblock || this.$to.end() == this.$to.pos) { return -1 } + var top = this.frontier[this.depth], level; + if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) || + (this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth)) { return -1 } + + var ref = this.$to; + var depth = ref.depth; + var after = this.$to.after(depth); + while (depth > 1 && after == this.$to.end(--depth)) { ++after; } + return after + }; + + Fitter.prototype.findCloseLevel = function findCloseLevel ($to) { + scan: for (var i = Math.min(this.depth, $to.depth); i >= 0; i--) { + var ref = this.frontier[i]; + var match = ref.match; + var type = ref.type; + var dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1)); + var fit = contentAfterFits($to, i, type, match, dropInner); + if (!fit) { continue } + for (var d = i - 1; d >= 0; d--) { + var ref$1 = this.frontier[d]; + var match$1 = ref$1.match; + var type$1 = ref$1.type; + var matches = contentAfterFits($to, d, type$1, match$1, true); + if (!matches || matches.childCount) { continue scan } + } + return {depth: i, fit: fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to} + } + }; + + Fitter.prototype.close = function close ($to) { + var close = this.findCloseLevel($to); + if (!close) { return null } + + while (this.depth > close.depth) { this.closeFrontierNode(); } + if (close.fit.childCount) { this.placed = addToFragment(this.placed, close.depth, close.fit); } + $to = close.move; + for (var d = close.depth + 1; d <= $to.depth; d++) { + var node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d)); + this.openFrontierNode(node.type, node.attrs, add); + } + return $to + }; + + Fitter.prototype.openFrontierNode = function openFrontierNode (type, attrs, content) { + var top = this.frontier[this.depth]; + top.match = top.match.matchType(type); + this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content))); + this.frontier.push({type: type, match: type.contentMatch}); + }; + + Fitter.prototype.closeFrontierNode = function closeFrontierNode () { + var open = this.frontier.pop(); + var add = open.match.fillBefore(Fragment.empty, true); + if (add.childCount) { this.placed = addToFragment(this.placed, this.frontier.length, add); } + }; + + Object.defineProperties( Fitter.prototype, prototypeAccessors$1$4 ); + + function dropFromFragment(fragment, depth, count) { + if (depth == 0) { return fragment.cutByIndex(count) } + return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count))) + } + + function addToFragment(fragment, depth, content) { + if (depth == 0) { return fragment.append(content) } + return fragment.replaceChild(fragment.childCount - 1, + fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content))) + } + + function contentAt(fragment, depth) { + for (var i = 0; i < depth; i++) { fragment = fragment.firstChild.content; } + return fragment + } + + function closeNodeStart(node, openStart, openEnd) { + if (openStart <= 0) { return node } + var frag = node.content; + if (openStart > 1) + { frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0)); } + if (openStart > 0) { + frag = node.type.contentMatch.fillBefore(frag).append(frag); + if (openEnd <= 0) { frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true)); } + } + return node.copy(frag) + } + + function contentAfterFits($to, depth, type, match, open) { + var node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth); + if (index == node.childCount && !type.compatibleContent(node.type)) { return null } + var fit = match.fillBefore(node.content, true, index); + return fit && !invalidMarks(type, node.content, index) ? fit : null + } + + function invalidMarks(type, fragment, start) { + for (var i = start; i < fragment.childCount; i++) + { if (!type.allowsMarks(fragment.child(i).marks)) { return true } } + return false + } + + // :: (number, number, Slice) → this + // Replace a range of the document with a given slice, using `from`, + // `to`, and the slice's [`openStart`](#model.Slice.openStart) property + // as hints, rather than fixed start and end points. This method may + // grow the replaced area or close open nodes in the slice in order to + // get a fit that is more in line with WYSIWYG expectations, by + // dropping fully covered parent nodes of the replaced region when + // they are marked [non-defining](#model.NodeSpec.defining), or + // including an open parent node from the slice that _is_ marked as + // [defining](#model.NodeSpec.defining). + // + // This is the method, for example, to handle paste. The similar + // [`replace`](#transform.Transform.replace) method is a more + // primitive tool which will _not_ move the start and end of its given + // range, and is useful in situations where you need more precise + // control over what happens. + Transform.prototype.replaceRange = function(from, to, slice) { + if (!slice.size) { return this.deleteRange(from, to) } + + var $from = this.doc.resolve(from), $to = this.doc.resolve(to); + if (fitsTrivially($from, $to, slice)) + { return this.step(new ReplaceStep(from, to, slice)) } + + var targetDepths = coveredDepths($from, this.doc.resolve(to)); + // Can't replace the whole document, so remove 0 if it's present + if (targetDepths[targetDepths.length - 1] == 0) { targetDepths.pop(); } + // Negative numbers represent not expansion over the whole node at + // that depth, but replacing from $from.before(-D) to $to.pos. + var preferredTarget = -($from.depth + 1); + targetDepths.unshift(preferredTarget); + // This loop picks a preferred target depth, if one of the covering + // depths is not outside of a defining node, and adds negative + // depths for any depth that has $from at its start and does not + // cross a defining node. + for (var d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) { + var spec = $from.node(d).type.spec; + if (spec.defining || spec.isolating) { break } + if (targetDepths.indexOf(d) > -1) { preferredTarget = d; } + else if ($from.before(d) == pos) { targetDepths.splice(1, 0, -d); } + } + // Try to fit each possible depth of the slice into each possible + // target depth, starting with the preferred depths. + var preferredTargetIndex = targetDepths.indexOf(preferredTarget); + + var leftNodes = [], preferredDepth = slice.openStart; + for (var content = slice.content, i = 0;; i++) { + var node = content.firstChild; + leftNodes.push(node); + if (i == slice.openStart) { break } + content = node.content; + } + // Back up if the node directly above openStart, or the node above + // that separated only by a non-defining textblock node, is defining. + if (preferredDepth > 0 && leftNodes[preferredDepth - 1].type.spec.defining && + $from.node(preferredTargetIndex).type != leftNodes[preferredDepth - 1].type) + { preferredDepth -= 1; } + else if (preferredDepth >= 2 && leftNodes[preferredDepth - 1].isTextblock && leftNodes[preferredDepth - 2].type.spec.defining && + $from.node(preferredTargetIndex).type != leftNodes[preferredDepth - 2].type) + { preferredDepth -= 2; } + + for (var j = slice.openStart; j >= 0; j--) { + var openDepth = (j + preferredDepth + 1) % (slice.openStart + 1); + var insert = leftNodes[openDepth]; + if (!insert) { continue } + for (var i$1 = 0; i$1 < targetDepths.length; i$1++) { + // Loop over possible expansion levels, starting with the + // preferred one + var targetDepth = targetDepths[(i$1 + preferredTargetIndex) % targetDepths.length], expand = true; + if (targetDepth < 0) { expand = false; targetDepth = -targetDepth; } + var parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1); + if (parent.canReplaceWith(index, index, insert.type, insert.marks)) + { return this.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, + new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), + openDepth, slice.openEnd)) } + } + } + + var startSteps = this.steps.length; + for (var i$2 = targetDepths.length - 1; i$2 >= 0; i$2--) { + this.replace(from, to, slice); + if (this.steps.length > startSteps) { break } + var depth = targetDepths[i$2]; + if (i$2 < 0) { continue } + from = $from.before(depth); to = $to.after(depth); + } + return this + }; + + function closeFragment(fragment, depth, oldOpen, newOpen, parent) { + if (depth < oldOpen) { + var first = fragment.firstChild; + fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first))); + } + if (depth > newOpen) { + var match = parent.contentMatchAt(0); + var start = match.fillBefore(fragment).append(fragment); + fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true)); + } + return fragment + } + + // :: (number, number, Node) → this + // Replace the given range with a node, but use `from` and `to` as + // hints, rather than precise positions. When from and to are the same + // and are at the start or end of a parent node in which the given + // node doesn't fit, this method may _move_ them out towards a parent + // that does allow the given node to be placed. When the given range + // completely covers a parent node, this method may completely replace + // that parent node. + Transform.prototype.replaceRangeWith = function(from, to, node) { + if (!node.isInline && from == to && this.doc.resolve(from).parent.content.size) { + var point = insertPoint(this.doc, from, node.type); + if (point != null) { from = to = point; } + } + return this.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0)) + }; + + // :: (number, number) → this + // Delete the given range, expanding it to cover fully covered + // parent nodes until a valid replace is found. + Transform.prototype.deleteRange = function(from, to) { + var $from = this.doc.resolve(from), $to = this.doc.resolve(to); + var covered = coveredDepths($from, $to); + for (var i = 0; i < covered.length; i++) { + var depth = covered[i], last = i == covered.length - 1; + if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd) + { return this.delete($from.start(depth), $to.end(depth)) } + if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1)))) + { return this.delete($from.before(depth), $to.after(depth)) } + } + for (var d = 1; d <= $from.depth && d <= $to.depth; d++) { + if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d) + { return this.delete($from.before(d), to) } + } + return this.delete(from, to) + }; + + // : (ResolvedPos, ResolvedPos) → [number] + // Returns an array of all depths for which $from - $to spans the + // whole content of the nodes at that depth. + function coveredDepths($from, $to) { + var result = [], minDepth = Math.min($from.depth, $to.depth); + for (var d = minDepth; d >= 0; d--) { + var start = $from.start(d); + if (start < $from.pos - ($from.depth - d) || + $to.end(d) > $to.pos + ($to.depth - d) || + $from.node(d).type.spec.isolating || + $to.node(d).type.spec.isolating) { break } + if (start == $to.start(d)) { result.push(d); } + } + return result + } + + var classesById = Object.create(null); + + // ::- Superclass for editor selections. Every selection type should + // extend this. Should not be instantiated directly. + var Selection = function Selection($anchor, $head, ranges) { + // :: [SelectionRange] + // The ranges covered by the selection. + this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))]; + // :: ResolvedPos + // The resolved anchor of the selection (the side that stays in + // place when the selection is modified). + this.$anchor = $anchor; + // :: ResolvedPos + // The resolved head of the selection (the side that moves when + // the selection is modified). + this.$head = $head; + }; + + var prototypeAccessors$8 = { anchor: { configurable: true },head: { configurable: true },from: { configurable: true },to: { configurable: true },$from: { configurable: true },$to: { configurable: true },empty: { configurable: true } }; + + // :: number + // The selection's anchor, as an unresolved position. + prototypeAccessors$8.anchor.get = function () { return this.$anchor.pos }; + + // :: number + // The selection's head. + prototypeAccessors$8.head.get = function () { return this.$head.pos }; + + // :: number + // The lower bound of the selection's main range. + prototypeAccessors$8.from.get = function () { return this.$from.pos }; + + // :: number + // The upper bound of the selection's main range. + prototypeAccessors$8.to.get = function () { return this.$to.pos }; + + // :: ResolvedPos + // The resolved lowerbound of the selection's main range. + prototypeAccessors$8.$from.get = function () { + return this.ranges[0].$from + }; + + // :: ResolvedPos + // The resolved upper bound of the selection's main range. + prototypeAccessors$8.$to.get = function () { + return this.ranges[0].$to + }; + + // :: bool + // Indicates whether the selection contains any content. + prototypeAccessors$8.empty.get = function () { + var ranges = this.ranges; + for (var i = 0; i < ranges.length; i++) + { if (ranges[i].$from.pos != ranges[i].$to.pos) { return false } } + return true + }; + + // eq:: (Selection) → bool + // Test whether the selection is the same as another selection. + + // map:: (doc: Node, mapping: Mappable) → Selection + // Map this selection through a [mappable](#transform.Mappable) thing. `doc` + // should be the new document to which we are mapping. + + // :: () → Slice + // Get the content of this selection as a slice. + Selection.prototype.content = function content () { + return this.$from.node(0).slice(this.from, this.to, true) + }; + + // :: (Transaction, ?Slice) + // Replace the selection with a slice or, if no slice is given, + // delete the selection. Will append to the given transaction. + Selection.prototype.replace = function replace (tr, content) { + if ( content === void 0 ) content = Slice.empty; + + // Put the new selection at the position after the inserted + // content. When that ended in an inline node, search backwards, + // to get the position after that node. If not, search forward. + var lastNode = content.content.lastChild, lastParent = null; + for (var i = 0; i < content.openEnd; i++) { + lastParent = lastNode; + lastNode = lastNode.lastChild; + } + + var mapFrom = tr.steps.length, ranges = this.ranges; + for (var i$1 = 0; i$1 < ranges.length; i$1++) { + var ref = ranges[i$1]; + var $from = ref.$from; + var $to = ref.$to; + var mapping = tr.mapping.slice(mapFrom); + tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i$1 ? Slice.empty : content); + if (i$1 == 0) + { selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1); } + } + }; + + // :: (Transaction, Node) + // Replace the selection with the given node, appending the changes + // to the given transaction. + Selection.prototype.replaceWith = function replaceWith (tr, node) { + var mapFrom = tr.steps.length, ranges = this.ranges; + for (var i = 0; i < ranges.length; i++) { + var ref = ranges[i]; + var $from = ref.$from; + var $to = ref.$to; + var mapping = tr.mapping.slice(mapFrom); + var from = mapping.map($from.pos), to = mapping.map($to.pos); + if (i) { + tr.deleteRange(from, to); + } else { + tr.replaceRangeWith(from, to, node); + selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1); + } + } + }; + + // toJSON:: () → Object + // Convert the selection to a JSON representation. When implementing + // this for a custom selection class, make sure to give the object a + // `type` property whose value matches the ID under which you + // [registered](#state.Selection^jsonID) your class. + + // :: (ResolvedPos, number, ?bool) → ?Selection + // Find a valid cursor or leaf node selection starting at the given + // position and searching back if `dir` is negative, and forward if + // positive. When `textOnly` is true, only consider cursor + // selections. Will return null when no valid selection position is + // found. + Selection.findFrom = function findFrom ($pos, dir, textOnly) { + var inner = $pos.parent.inlineContent ? new TextSelection($pos) + : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly); + if (inner) { return inner } + + for (var depth = $pos.depth - 1; depth >= 0; depth--) { + var found = dir < 0 + ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly) + : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly); + if (found) { return found } + } + }; + + // :: (ResolvedPos, ?number) → Selection + // Find a valid cursor or leaf node selection near the given + // position. Searches forward first by default, but if `bias` is + // negative, it will search backwards first. + Selection.near = function near ($pos, bias) { + if ( bias === void 0 ) bias = 1; + + return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0)) + }; + + // :: (Node) → Selection + // Find the cursor or leaf node selection closest to the start of + // the given document. Will return an + // [`AllSelection`](#state.AllSelection) if no valid position + // exists. + Selection.atStart = function atStart (doc) { + return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc) + }; + + // :: (Node) → Selection + // Find the cursor or leaf node selection closest to the end of the + // given document. + Selection.atEnd = function atEnd (doc) { + return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc) + }; + + // :: (Node, Object) → Selection + // Deserialize the JSON representation of a selection. Must be + // implemented for custom classes (as a static class method). + Selection.fromJSON = function fromJSON (doc, json) { + if (!json || !json.type) { throw new RangeError("Invalid input for Selection.fromJSON") } + var cls = classesById[json.type]; + if (!cls) { throw new RangeError(("No selection type " + (json.type) + " defined")) } + return cls.fromJSON(doc, json) + }; + + // :: (string, constructor) + // To be able to deserialize selections from JSON, custom selection + // classes must register themselves with an ID string, so that they + // can be disambiguated. Try to pick something that's unlikely to + // clash with classes from other modules. + Selection.jsonID = function jsonID (id, selectionClass) { + if (id in classesById) { throw new RangeError("Duplicate use of selection JSON ID " + id) } + classesById[id] = selectionClass; + selectionClass.prototype.jsonID = id; + return selectionClass + }; + + // :: () → SelectionBookmark + // Get a [bookmark](#state.SelectionBookmark) for this selection, + // which is a value that can be mapped without having access to a + // current document, and later resolved to a real selection for a + // given document again. (This is used mostly by the history to + // track and restore old selections.) The default implementation of + // this method just converts the selection to a text selection and + // returns the bookmark for that. + Selection.prototype.getBookmark = function getBookmark () { + return TextSelection.between(this.$anchor, this.$head).getBookmark() + }; + + Object.defineProperties( Selection.prototype, prototypeAccessors$8 ); + + // :: bool + // Controls whether, when a selection of this type is active in the + // browser, the selected range should be visible to the user. Defaults + // to `true`. + Selection.prototype.visible = true; + + // SelectionBookmark:: interface + // A lightweight, document-independent representation of a selection. + // You can define a custom bookmark type for a custom selection class + // to make the history handle it well. + // + // map:: (mapping: Mapping) → SelectionBookmark + // Map the bookmark through a set of changes. + // + // resolve:: (doc: Node) → Selection + // Resolve the bookmark to a real selection again. This may need to + // do some error checking and may fall back to a default (usually + // [`TextSelection.between`](#state.TextSelection^between)) if + // mapping made the bookmark invalid. + + // ::- Represents a selected range in a document. + var SelectionRange = function SelectionRange($from, $to) { + // :: ResolvedPos + // The lower bound of the range. + this.$from = $from; + // :: ResolvedPos + // The upper bound of the range. + this.$to = $to; + }; + + // ::- A text selection represents a classical editor selection, with + // a head (the moving side) and anchor (immobile side), both of which + // point into textblock nodes. It can be empty (a regular cursor + // position). + var TextSelection = /*@__PURE__*/(function (Selection) { + function TextSelection($anchor, $head) { + if ( $head === void 0 ) $head = $anchor; + + Selection.call(this, $anchor, $head); + } + + if ( Selection ) TextSelection.__proto__ = Selection; + TextSelection.prototype = Object.create( Selection && Selection.prototype ); + TextSelection.prototype.constructor = TextSelection; + + var prototypeAccessors$1 = { $cursor: { configurable: true } }; + + // :: ?ResolvedPos + // Returns a resolved position if this is a cursor selection (an + // empty text selection), and null otherwise. + prototypeAccessors$1.$cursor.get = function () { return this.$anchor.pos == this.$head.pos ? this.$head : null }; + + TextSelection.prototype.map = function map (doc, mapping) { + var $head = doc.resolve(mapping.map(this.head)); + if (!$head.parent.inlineContent) { return Selection.near($head) } + var $anchor = doc.resolve(mapping.map(this.anchor)); + return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head) + }; + + TextSelection.prototype.replace = function replace (tr, content) { + if ( content === void 0 ) content = Slice.empty; + + Selection.prototype.replace.call(this, tr, content); + if (content == Slice.empty) { + var marks = this.$from.marksAcross(this.$to); + if (marks) { tr.ensureMarks(marks); } + } + }; + + TextSelection.prototype.eq = function eq (other) { + return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head + }; + + TextSelection.prototype.getBookmark = function getBookmark () { + return new TextBookmark(this.anchor, this.head) + }; + + TextSelection.prototype.toJSON = function toJSON () { + return {type: "text", anchor: this.anchor, head: this.head} + }; + + TextSelection.fromJSON = function fromJSON (doc, json) { + if (typeof json.anchor != "number" || typeof json.head != "number") + { throw new RangeError("Invalid input for TextSelection.fromJSON") } + return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head)) + }; + + // :: (Node, number, ?number) → TextSelection + // Create a text selection from non-resolved positions. + TextSelection.create = function create (doc, anchor, head) { + if ( head === void 0 ) head = anchor; + + var $anchor = doc.resolve(anchor); + return new this($anchor, head == anchor ? $anchor : doc.resolve(head)) + }; + + // :: (ResolvedPos, ResolvedPos, ?number) → Selection + // Return a text selection that spans the given positions or, if + // they aren't text positions, find a text selection near them. + // `bias` determines whether the method searches forward (default) + // or backwards (negative number) first. Will fall back to calling + // [`Selection.near`](#state.Selection^near) when the document + // doesn't contain a valid text position. + TextSelection.between = function between ($anchor, $head, bias) { + var dPos = $anchor.pos - $head.pos; + if (!bias || dPos) { bias = dPos >= 0 ? 1 : -1; } + if (!$head.parent.inlineContent) { + var found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true); + if (found) { $head = found.$head; } + else { return Selection.near($head, bias) } + } + if (!$anchor.parent.inlineContent) { + if (dPos == 0) { + $anchor = $head; + } else { + $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor; + if (($anchor.pos < $head.pos) != (dPos < 0)) { $anchor = $head; } + } + } + return new TextSelection($anchor, $head) + }; + + Object.defineProperties( TextSelection.prototype, prototypeAccessors$1 ); + + return TextSelection; + }(Selection)); + + Selection.jsonID("text", TextSelection); + + var TextBookmark = function TextBookmark(anchor, head) { + this.anchor = anchor; + this.head = head; + }; + TextBookmark.prototype.map = function map (mapping) { + return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head)) + }; + TextBookmark.prototype.resolve = function resolve (doc) { + return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head)) + }; + + // ::- A node selection is a selection that points at a single node. + // All nodes marked [selectable](#model.NodeSpec.selectable) can be + // the target of a node selection. In such a selection, `from` and + // `to` point directly before and after the selected node, `anchor` + // equals `from`, and `head` equals `to`.. + var NodeSelection = /*@__PURE__*/(function (Selection) { + function NodeSelection($pos) { + var node = $pos.nodeAfter; + var $end = $pos.node(0).resolve($pos.pos + node.nodeSize); + Selection.call(this, $pos, $end); + // :: Node The selected node. + this.node = node; + } + + if ( Selection ) NodeSelection.__proto__ = Selection; + NodeSelection.prototype = Object.create( Selection && Selection.prototype ); + NodeSelection.prototype.constructor = NodeSelection; + + NodeSelection.prototype.map = function map (doc, mapping) { + var ref = mapping.mapResult(this.anchor); + var deleted = ref.deleted; + var pos = ref.pos; + var $pos = doc.resolve(pos); + if (deleted) { return Selection.near($pos) } + return new NodeSelection($pos) + }; + + NodeSelection.prototype.content = function content () { + return new Slice(Fragment.from(this.node), 0, 0) + }; + + NodeSelection.prototype.eq = function eq (other) { + return other instanceof NodeSelection && other.anchor == this.anchor + }; + + NodeSelection.prototype.toJSON = function toJSON () { + return {type: "node", anchor: this.anchor} + }; + + NodeSelection.prototype.getBookmark = function getBookmark () { return new NodeBookmark(this.anchor) }; + + NodeSelection.fromJSON = function fromJSON (doc, json) { + if (typeof json.anchor != "number") + { throw new RangeError("Invalid input for NodeSelection.fromJSON") } + return new NodeSelection(doc.resolve(json.anchor)) + }; + + // :: (Node, number) → NodeSelection + // Create a node selection from non-resolved positions. + NodeSelection.create = function create (doc, from) { + return new this(doc.resolve(from)) + }; + + // :: (Node) → bool + // Determines whether the given node may be selected as a node + // selection. + NodeSelection.isSelectable = function isSelectable (node) { + return !node.isText && node.type.spec.selectable !== false + }; + + return NodeSelection; + }(Selection)); + + NodeSelection.prototype.visible = false; + + Selection.jsonID("node", NodeSelection); + + var NodeBookmark = function NodeBookmark(anchor) { + this.anchor = anchor; + }; + NodeBookmark.prototype.map = function map (mapping) { + var ref = mapping.mapResult(this.anchor); + var deleted = ref.deleted; + var pos = ref.pos; + return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos) + }; + NodeBookmark.prototype.resolve = function resolve (doc) { + var $pos = doc.resolve(this.anchor), node = $pos.nodeAfter; + if (node && NodeSelection.isSelectable(node)) { return new NodeSelection($pos) } + return Selection.near($pos) + }; + + // ::- A selection type that represents selecting the whole document + // (which can not necessarily be expressed with a text selection, when + // there are for example leaf block nodes at the start or end of the + // document). + var AllSelection = /*@__PURE__*/(function (Selection) { + function AllSelection(doc) { + Selection.call(this, doc.resolve(0), doc.resolve(doc.content.size)); + } + + if ( Selection ) AllSelection.__proto__ = Selection; + AllSelection.prototype = Object.create( Selection && Selection.prototype ); + AllSelection.prototype.constructor = AllSelection; + + AllSelection.prototype.replace = function replace (tr, content) { + if ( content === void 0 ) content = Slice.empty; + + if (content == Slice.empty) { + tr.delete(0, tr.doc.content.size); + var sel = Selection.atStart(tr.doc); + if (!sel.eq(tr.selection)) { tr.setSelection(sel); } + } else { + Selection.prototype.replace.call(this, tr, content); + } + }; + + AllSelection.prototype.toJSON = function toJSON () { return {type: "all"} }; + + AllSelection.fromJSON = function fromJSON (doc) { return new AllSelection(doc) }; + + AllSelection.prototype.map = function map (doc) { return new AllSelection(doc) }; + + AllSelection.prototype.eq = function eq (other) { return other instanceof AllSelection }; + + AllSelection.prototype.getBookmark = function getBookmark () { return AllBookmark }; + + return AllSelection; + }(Selection)); + + Selection.jsonID("all", AllSelection); + + var AllBookmark = { + map: function map() { return this }, + resolve: function resolve(doc) { return new AllSelection(doc) } + }; + + // FIXME we'll need some awareness of text direction when scanning for selections + + // Try to find a selection inside the given node. `pos` points at the + // position where the search starts. When `text` is true, only return + // text selections. + function findSelectionIn(doc, node, pos, index, dir, text) { + if (node.inlineContent) { return TextSelection.create(doc, pos) } + for (var i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) { + var child = node.child(i); + if (!child.isAtom) { + var inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text); + if (inner) { return inner } + } else if (!text && NodeSelection.isSelectable(child)) { + return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0)) + } + pos += child.nodeSize * dir; + } + } + + function selectionToInsertionEnd(tr, startLen, bias) { + var last = tr.steps.length - 1; + if (last < startLen) { return } + var step = tr.steps[last]; + if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) { return } + var map = tr.mapping.maps[last], end; + map.forEach(function (_from, _to, _newFrom, newTo) { if (end == null) { end = newTo; } }); + tr.setSelection(Selection.near(tr.doc.resolve(end), bias)); + } + + var UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4; + + // ::- An editor state transaction, which can be applied to a state to + // create an updated state. Use + // [`EditorState.tr`](#state.EditorState.tr) to create an instance. + // + // Transactions track changes to the document (they are a subclass of + // [`Transform`](#transform.Transform)), but also other state changes, + // like selection updates and adjustments of the set of [stored + // marks](#state.EditorState.storedMarks). In addition, you can store + // metadata properties in a transaction, which are extra pieces of + // information that client code or plugins can use to describe what a + // transacion represents, so that they can update their [own + // state](#state.StateField) accordingly. + // + // The [editor view](#view.EditorView) uses a few metadata properties: + // it will attach a property `"pointer"` with the value `true` to + // selection transactions directly caused by mouse or touch input, and + // a `"uiEvent"` property of that may be `"paste"`, `"cut"`, or `"drop"`. + var Transaction$1 = /*@__PURE__*/(function (Transform) { + function Transaction(state) { + Transform.call(this, state.doc); + // :: number + // The timestamp associated with this transaction, in the same + // format as `Date.now()`. + this.time = Date.now(); + this.curSelection = state.selection; + // The step count for which the current selection is valid. + this.curSelectionFor = 0; + // :: ?[Mark] + // The stored marks set by this transaction, if any. + this.storedMarks = state.storedMarks; + // Bitfield to track which aspects of the state were updated by + // this transaction. + this.updated = 0; + // Object used to store metadata properties for the transaction. + this.meta = Object.create(null); + } + + if ( Transform ) Transaction.__proto__ = Transform; + Transaction.prototype = Object.create( Transform && Transform.prototype ); + Transaction.prototype.constructor = Transaction; + + var prototypeAccessors = { selection: { configurable: true },selectionSet: { configurable: true },storedMarksSet: { configurable: true },isGeneric: { configurable: true },scrolledIntoView: { configurable: true } }; + + // :: Selection + // The transaction's current selection. This defaults to the editor + // selection [mapped](#state.Selection.map) through the steps in the + // transaction, but can be overwritten with + // [`setSelection`](#state.Transaction.setSelection). + prototypeAccessors.selection.get = function () { + if (this.curSelectionFor < this.steps.length) { + this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor)); + this.curSelectionFor = this.steps.length; + } + return this.curSelection + }; + + // :: (Selection) → Transaction + // Update the transaction's current selection. Will determine the + // selection that the editor gets when the transaction is applied. + Transaction.prototype.setSelection = function setSelection (selection) { + if (selection.$from.doc != this.doc) + { throw new RangeError("Selection passed to setSelection must point at the current document") } + this.curSelection = selection; + this.curSelectionFor = this.steps.length; + this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS; + this.storedMarks = null; + return this + }; + + // :: bool + // Whether the selection was explicitly updated by this transaction. + prototypeAccessors.selectionSet.get = function () { + return (this.updated & UPDATED_SEL) > 0 + }; + + // :: (?[Mark]) → Transaction + // Set the current stored marks. + Transaction.prototype.setStoredMarks = function setStoredMarks (marks) { + this.storedMarks = marks; + this.updated |= UPDATED_MARKS; + return this + }; + + // :: ([Mark]) → Transaction + // Make sure the current stored marks or, if that is null, the marks + // at the selection, match the given set of marks. Does nothing if + // this is already the case. + Transaction.prototype.ensureMarks = function ensureMarks (marks) { + if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks)) + { this.setStoredMarks(marks); } + return this + }; + + // :: (Mark) → Transaction + // Add a mark to the set of stored marks. + Transaction.prototype.addStoredMark = function addStoredMark (mark) { + return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks())) + }; + + // :: (union) → Transaction + // Remove a mark or mark type from the set of stored marks. + Transaction.prototype.removeStoredMark = function removeStoredMark (mark) { + return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks())) + }; + + // :: bool + // Whether the stored marks were explicitly set for this transaction. + prototypeAccessors.storedMarksSet.get = function () { + return (this.updated & UPDATED_MARKS) > 0 + }; + + Transaction.prototype.addStep = function addStep (step, doc) { + Transform.prototype.addStep.call(this, step, doc); + this.updated = this.updated & ~UPDATED_MARKS; + this.storedMarks = null; + }; + + // :: (number) → Transaction + // Update the timestamp for the transaction. + Transaction.prototype.setTime = function setTime (time) { + this.time = time; + return this + }; + + // :: (Slice) → Transaction + // Replace the current selection with the given slice. + Transaction.prototype.replaceSelection = function replaceSelection (slice) { + this.selection.replace(this, slice); + return this + }; + + // :: (Node, ?bool) → Transaction + // Replace the selection with the given node. When `inheritMarks` is + // true and the content is inline, it inherits the marks from the + // place where it is inserted. + Transaction.prototype.replaceSelectionWith = function replaceSelectionWith (node, inheritMarks) { + var selection = this.selection; + if (inheritMarks !== false) + { node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : (selection.$from.marksAcross(selection.$to) || Mark.none))); } + selection.replaceWith(this, node); + return this + }; + + // :: () → Transaction + // Delete the selection. + Transaction.prototype.deleteSelection = function deleteSelection () { + this.selection.replace(this); + return this + }; + + // :: (string, from: ?number, to: ?number) → Transaction + // Replace the given range, or the selection if no range is given, + // with a text node containing the given string. + Transaction.prototype.insertText = function insertText (text, from, to) { + if ( to === void 0 ) to = from; + + var schema = this.doc.type.schema; + if (from == null) { + if (!text) { return this.deleteSelection() } + return this.replaceSelectionWith(schema.text(text), true) + } else { + if (!text) { return this.deleteRange(from, to) } + var marks = this.storedMarks; + if (!marks) { + var $from = this.doc.resolve(from); + marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to)); + } + this.replaceRangeWith(from, to, schema.text(text, marks)); + if (!this.selection.empty) { this.setSelection(Selection.near(this.selection.$to)); } + return this + } + }; + + // :: (union, any) → Transaction + // Store a metadata property in this transaction, keyed either by + // name or by plugin. + Transaction.prototype.setMeta = function setMeta (key, value) { + this.meta[typeof key == "string" ? key : key.key] = value; + return this + }; + + // :: (union) → any + // Retrieve a metadata property for a given name or plugin. + Transaction.prototype.getMeta = function getMeta (key) { + return this.meta[typeof key == "string" ? key : key.key] + }; + + // :: bool + // Returns true if this transaction doesn't contain any metadata, + // and can thus safely be extended. + prototypeAccessors.isGeneric.get = function () { + for (var _ in this.meta) { return false } + return true + }; + + // :: () → Transaction + // Indicate that the editor should scroll the selection into view + // when updated to the state produced by this transaction. + Transaction.prototype.scrollIntoView = function scrollIntoView () { + this.updated |= UPDATED_SCROLL; + return this + }; + + prototypeAccessors.scrolledIntoView.get = function () { + return (this.updated & UPDATED_SCROLL) > 0 + }; + + Object.defineProperties( Transaction.prototype, prototypeAccessors ); + + return Transaction; + }(Transform)); + + function bind(f, self) { + return !self || !f ? f : f.bind(self) + } + + var FieldDesc = function FieldDesc(name, desc, self) { + this.name = name; + this.init = bind(desc.init, self); + this.apply = bind(desc.apply, self); + }; + + var baseFields = [ + new FieldDesc("doc", { + init: function init(config) { return config.doc || config.schema.topNodeType.createAndFill() }, + apply: function apply(tr) { return tr.doc } + }), + + new FieldDesc("selection", { + init: function init(config, instance) { return config.selection || Selection.atStart(instance.doc) }, + apply: function apply(tr) { return tr.selection } + }), + + new FieldDesc("storedMarks", { + init: function init(config) { return config.storedMarks || null }, + apply: function apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null } + }), + + new FieldDesc("scrollToSelection", { + init: function init() { return 0 }, + apply: function apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev } + }) + ]; + + // Object wrapping the part of a state object that stays the same + // across transactions. Stored in the state's `config` property. + var Configuration = function Configuration(schema, plugins) { + var this$1 = this; + + this.schema = schema; + this.fields = baseFields.concat(); + this.plugins = []; + this.pluginsByKey = Object.create(null); + if (plugins) { plugins.forEach(function (plugin) { + if (this$1.pluginsByKey[plugin.key]) + { throw new RangeError("Adding different instances of a keyed plugin (" + plugin.key + ")") } + this$1.plugins.push(plugin); + this$1.pluginsByKey[plugin.key] = plugin; + if (plugin.spec.state) + { this$1.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin)); } + }); } + }; + + // ::- The state of a ProseMirror editor is represented by an object + // of this type. A state is a persistent data structure—it isn't + // updated, but rather a new state value is computed from an old one + // using the [`apply`](#state.EditorState.apply) method. + // + // A state holds a number of built-in fields, and plugins can + // [define](#state.PluginSpec.state) additional fields. + var EditorState = function EditorState(config) { + this.config = config; + }; + + var prototypeAccessors$1$5 = { schema: { configurable: true },plugins: { configurable: true },tr: { configurable: true } }; + + // doc:: Node + // The current document. + + // selection:: Selection + // The selection. + + // storedMarks:: ?[Mark] + // A set of marks to apply to the next input. Will be null when + // no explicit marks have been set. + + // :: Schema + // The schema of the state's document. + prototypeAccessors$1$5.schema.get = function () { + return this.config.schema + }; + + // :: [Plugin] + // The plugins that are active in this state. + prototypeAccessors$1$5.plugins.get = function () { + return this.config.plugins + }; + + // :: (Transaction) → EditorState + // Apply the given transaction to produce a new state. + EditorState.prototype.apply = function apply (tr) { + return this.applyTransaction(tr).state + }; + + // : (Transaction) → bool + EditorState.prototype.filterTransaction = function filterTransaction (tr, ignore) { + if ( ignore === void 0 ) ignore = -1; + + for (var i = 0; i < this.config.plugins.length; i++) { if (i != ignore) { + var plugin = this.config.plugins[i]; + if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this)) + { return false } + } } + return true + }; + + // :: (Transaction) → {state: EditorState, transactions: [Transaction]} + // Verbose variant of [`apply`](#state.EditorState.apply) that + // returns the precise transactions that were applied (which might + // be influenced by the [transaction + // hooks](#state.PluginSpec.filterTransaction) of + // plugins) along with the new state. + EditorState.prototype.applyTransaction = function applyTransaction (rootTr) { + if (!this.filterTransaction(rootTr)) { return {state: this, transactions: []} } + + var trs = [rootTr], newState = this.applyInner(rootTr), seen = null; + // This loop repeatedly gives plugins a chance to respond to + // transactions as new transactions are added, making sure to only + // pass the transactions the plugin did not see before. + for (;;) { + var haveNew = false; + for (var i = 0; i < this.config.plugins.length; i++) { + var plugin = this.config.plugins[i]; + if (plugin.spec.appendTransaction) { + var n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this; + var tr = n < trs.length && + plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState); + if (tr && newState.filterTransaction(tr, i)) { + tr.setMeta("appendedTransaction", rootTr); + if (!seen) { + seen = []; + for (var j = 0; j < this.config.plugins.length; j++) + { seen.push(j < i ? {state: newState, n: trs.length} : {state: this, n: 0}); } + } + trs.push(tr); + newState = newState.applyInner(tr); + haveNew = true; + } + if (seen) { seen[i] = {state: newState, n: trs.length}; } + } + } + if (!haveNew) { return {state: newState, transactions: trs} } + } + }; + + // : (Transaction) → EditorState + EditorState.prototype.applyInner = function applyInner (tr) { + if (!tr.before.eq(this.doc)) { throw new RangeError("Applying a mismatched transaction") } + var newInstance = new EditorState(this.config), fields = this.config.fields; + for (var i = 0; i < fields.length; i++) { + var field = fields[i]; + newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance); + } + for (var i$1 = 0; i$1 < applyListeners.length; i$1++) { applyListeners[i$1](this, tr, newInstance); } + return newInstance + }; + + // :: Transaction + // Start a [transaction](#state.Transaction) from this state. + prototypeAccessors$1$5.tr.get = function () { return new Transaction$1(this) }; + + // :: (Object) → EditorState + // Create a new state. + // + // config::- Configuration options. Must contain `schema` or `doc` (or both). + // + // schema:: ?Schema + // The schema to use. + // + // doc:: ?Node + // The starting document. + // + // selection:: ?Selection + // A valid selection in the document. + // + // storedMarks:: ?[Mark] + // The initial set of [stored marks](#state.EditorState.storedMarks). + // + // plugins:: ?[Plugin] + // The plugins that should be active in this state. + EditorState.create = function create (config) { + var $config = new Configuration(config.schema || config.doc.type.schema, config.plugins); + var instance = new EditorState($config); + for (var i = 0; i < $config.fields.length; i++) + { instance[$config.fields[i].name] = $config.fields[i].init(config, instance); } + return instance + }; + + // :: (Object) → EditorState + // Create a new state based on this one, but with an adjusted set of + // active plugins. State fields that exist in both sets of plugins + // are kept unchanged. Those that no longer exist are dropped, and + // those that are new are initialized using their + // [`init`](#state.StateField.init) method, passing in the new + // configuration object.. + // + // config::- configuration options + // + // schema:: ?Schema + // New schema to use. + // + // plugins:: ?[Plugin] + // New set of active plugins. + EditorState.prototype.reconfigure = function reconfigure (config) { + var $config = new Configuration(config.schema || this.schema, config.plugins); + var fields = $config.fields, instance = new EditorState($config); + for (var i = 0; i < fields.length; i++) { + var name = fields[i].name; + instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance); + } + return instance + }; + + // :: (?union, string, number>) → Object + // Serialize this state to JSON. If you want to serialize the state + // of plugins, pass an object mapping property names to use in the + // resulting JSON object to plugin objects. The argument may also be + // a string or number, in which case it is ignored, to support the + // way `JSON.stringify` calls `toString` methods. + EditorState.prototype.toJSON = function toJSON (pluginFields) { + var result = {doc: this.doc.toJSON(), selection: this.selection.toJSON()}; + if (this.storedMarks) { result.storedMarks = this.storedMarks.map(function (m) { return m.toJSON(); }); } + if (pluginFields && typeof pluginFields == 'object') { for (var prop in pluginFields) { + if (prop == "doc" || prop == "selection") + { throw new RangeError("The JSON fields `doc` and `selection` are reserved") } + var plugin = pluginFields[prop], state = plugin.spec.state; + if (state && state.toJSON) { result[prop] = state.toJSON.call(plugin, this[plugin.key]); } + } } + return result + }; + + // :: (Object, Object, ?Object) → EditorState + // Deserialize a JSON representation of a state. `config` should + // have at least a `schema` field, and should contain array of + // plugins to initialize the state with. `pluginFields` can be used + // to deserialize the state of plugins, by associating plugin + // instances with the property names they use in the JSON object. + // + // config::- configuration options + // + // schema:: Schema + // The schema to use. + // + // plugins:: ?[Plugin] + // The set of active plugins. + EditorState.fromJSON = function fromJSON (config, json, pluginFields) { + if (!json) { throw new RangeError("Invalid input for EditorState.fromJSON") } + if (!config.schema) { throw new RangeError("Required config field 'schema' missing") } + var $config = new Configuration(config.schema, config.plugins); + var instance = new EditorState($config); + $config.fields.forEach(function (field) { + if (field.name == "doc") { + instance.doc = Node$1.fromJSON(config.schema, json.doc); + } else if (field.name == "selection") { + instance.selection = Selection.fromJSON(instance.doc, json.selection); + } else if (field.name == "storedMarks") { + if (json.storedMarks) { instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON); } + } else { + if (pluginFields) { for (var prop in pluginFields) { + var plugin = pluginFields[prop], state = plugin.spec.state; + if (plugin.key == field.name && state && state.fromJSON && + Object.prototype.hasOwnProperty.call(json, prop)) { + // This field belongs to a plugin mapped to a JSON field, read it from there. + instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance); + return + } + } } + instance[field.name] = field.init(config, instance); + } + }); + return instance + }; + + // Kludge to allow the view to track mappings between different + // instances of a state. + // + // FIXME this is no longer needed as of prosemirror-view 1.9.0, + // though due to backwards-compat we should probably keep it around + // for a while (if only as a no-op) + EditorState.addApplyListener = function addApplyListener (f) { + applyListeners.push(f); + }; + EditorState.removeApplyListener = function removeApplyListener (f) { + var found = applyListeners.indexOf(f); + if (found > -1) { applyListeners.splice(found, 1); } + }; + + Object.defineProperties( EditorState.prototype, prototypeAccessors$1$5 ); + + var applyListeners = []; + + // PluginSpec:: interface + // + // This is the type passed to the [`Plugin`](#state.Plugin) + // constructor. It provides a definition for a plugin. + // + // props:: ?EditorProps + // The [view props](#view.EditorProps) added by this plugin. Props + // that are functions will be bound to have the plugin instance as + // their `this` binding. + // + // state:: ?StateField + // Allows a plugin to define a [state field](#state.StateField), an + // extra slot in the state object in which it can keep its own data. + // + // key:: ?PluginKey + // Can be used to make this a keyed plugin. You can have only one + // plugin with a given key in a given state, but it is possible to + // access the plugin's configuration and state through the key, + // without having access to the plugin instance object. + // + // view:: ?(EditorView) → Object + // When the plugin needs to interact with the editor view, or + // set something up in the DOM, use this field. The function + // will be called when the plugin's state is associated with an + // editor view. + // + // return::- + // Should return an object with the following optional + // properties: + // + // update:: ?(view: EditorView, prevState: EditorState) + // Called whenever the view's state is updated. + // + // destroy:: ?() + // Called when the view is destroyed or receives a state + // with different plugins. + // + // filterTransaction:: ?(Transaction, EditorState) → bool + // When present, this will be called before a transaction is + // applied by the state, allowing the plugin to cancel it (by + // returning false). + // + // appendTransaction:: ?(transactions: [Transaction], oldState: EditorState, newState: EditorState) → ?Transaction + // Allows the plugin to append another transaction to be applied + // after the given array of transactions. When another plugin + // appends a transaction after this was called, it is called again + // with the new state and new transactions—but only the new + // transactions, i.e. it won't be passed transactions that it + // already saw. + + function bindProps(obj, self, target) { + for (var prop in obj) { + var val = obj[prop]; + if (val instanceof Function) { val = val.bind(self); } + else if (prop == "handleDOMEvents") { val = bindProps(val, self, {}); } + target[prop] = val; + } + return target + } + + // ::- Plugins bundle functionality that can be added to an editor. + // They are part of the [editor state](#state.EditorState) and + // may influence that state and the view that contains it. + var Plugin = function Plugin(spec) { + // :: EditorProps + // The [props](#view.EditorProps) exported by this plugin. + this.props = {}; + if (spec.props) { bindProps(spec.props, this, this.props); } + // :: Object + // The plugin's [spec object](#state.PluginSpec). + this.spec = spec; + this.key = spec.key ? spec.key.key : createKey("plugin"); + }; + + // :: (EditorState) → any + // Extract the plugin's state field from an editor state. + Plugin.prototype.getState = function getState (state) { return state[this.key] }; + + // StateField:: interface + // A plugin spec may provide a state field (under its + // [`state`](#state.PluginSpec.state) property) of this type, which + // describes the state it wants to keep. Functions provided here are + // always called with the plugin instance as their `this` binding. + // + // init:: (config: Object, instance: EditorState) → T + // Initialize the value of the field. `config` will be the object + // passed to [`EditorState.create`](#state.EditorState^create). Note + // that `instance` is a half-initialized state instance, and will + // not have values for plugin fields initialized after this one. + // + // apply:: (tr: Transaction, value: T, oldState: EditorState, newState: EditorState) → T + // Apply the given transaction to this state field, producing a new + // field value. Note that the `newState` argument is again a partially + // constructed state does not yet contain the state from plugins + // coming after this one. + // + // toJSON:: ?(value: T) → * + // Convert this field to JSON. Optional, can be left off to disable + // JSON serialization for the field. + // + // fromJSON:: ?(config: Object, value: *, state: EditorState) → T + // Deserialize the JSON representation of this field. Note that the + // `state` argument is again a half-initialized state. + + var keys$1 = Object.create(null); + + function createKey(name) { + if (name in keys$1) { return name + "$" + ++keys$1[name] } + keys$1[name] = 0; + return name + "$" + } + + // ::- A key is used to [tag](#state.PluginSpec.key) + // plugins in a way that makes it possible to find them, given an + // editor state. Assigning a key does mean only one plugin of that + // type can be active in a state. + var PluginKey = function PluginKey(name) { + if ( name === void 0 ) name = "key"; + this.key = createKey(name); }; + + // :: (EditorState) → ?Plugin + // Get the active plugin with this key, if any, from an editor + // state. + PluginKey.prototype.get = function get (state) { return state.config.pluginsByKey[this.key] }; + + // :: (EditorState) → ?any + // Get the plugin's state from an editor state. + PluginKey.prototype.getState = function getState (state) { return state[this.key] }; + + var result = {}; + + if (typeof navigator != "undefined" && typeof document != "undefined") { + var ie_edge = /Edge\/(\d+)/.exec(navigator.userAgent); + var ie_upto10 = /MSIE \d/.test(navigator.userAgent); + var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); + + result.mac = /Mac/.test(navigator.platform); + var ie = result.ie = !!(ie_upto10 || ie_11up || ie_edge); + result.ie_version = ie_upto10 ? document.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : null; + result.gecko = !ie && /gecko\/(\d+)/i.test(navigator.userAgent); + result.gecko_version = result.gecko && +(/Firefox\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1]; + var chrome = !ie && /Chrome\/(\d+)/.exec(navigator.userAgent); + result.chrome = !!chrome; + result.chrome_version = chrome && +chrome[1]; + result.ios = !ie && /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); + result.android = /Android \d/.test(navigator.userAgent); + result.webkit = "webkitFontSmoothing" in document.documentElement.style; + result.safari = /Apple Computer/.test(navigator.vendor); + result.webkit_version = result.webkit && +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1]; + } + + var domIndex = function(node) { + for (var index = 0;; index++) { + node = node.previousSibling; + if (!node) { return index } + } + }; + + var parentNode = function(node) { + var parent = node.parentNode; + return parent && parent.nodeType == 11 ? parent.host : parent + }; + + var reusedRange = null; + + // Note that this will always return the same range, because DOM range + // objects are every expensive, and keep slowing down subsequent DOM + // updates, for some reason. + var textRange = function(node, from, to) { + var range = reusedRange || (reusedRange = document.createRange()); + range.setEnd(node, to == null ? node.nodeValue.length : to); + range.setStart(node, from || 0); + return range + }; + + // Scans forward and backward through DOM positions equivalent to the + // given one to see if the two are in the same place (i.e. after a + // text node vs at the end of that text node) + var isEquivalentPosition = function(node, off, targetNode, targetOff) { + return targetNode && (scanFor(node, off, targetNode, targetOff, -1) || + scanFor(node, off, targetNode, targetOff, 1)) + }; + + var atomElements = /^(img|br|input|textarea|hr)$/i; + + function scanFor(node, off, targetNode, targetOff, dir) { + for (;;) { + if (node == targetNode && off == targetOff) { return true } + if (off == (dir < 0 ? 0 : nodeSize(node))) { + var parent = node.parentNode; + if (parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == "false") + { return false } + off = domIndex(node) + (dir < 0 ? 0 : 1); + node = parent; + } else if (node.nodeType == 1) { + node = node.childNodes[off + (dir < 0 ? -1 : 0)]; + if (node.contentEditable == "false") { return false } + off = dir < 0 ? nodeSize(node) : 0; + } else { + return false + } + } + } + + function nodeSize(node) { + return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length + } + + function isOnEdge(node, offset, parent) { + for (var atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd;) { + if (node == parent) { return true } + var index = domIndex(node); + node = node.parentNode; + if (!node) { return false } + atStart = atStart && index == 0; + atEnd = atEnd && index == nodeSize(node); + } + } + + function hasBlockDesc(dom) { + var desc; + for (var cur = dom; cur; cur = cur.parentNode) { if (desc = cur.pmViewDesc) { break } } + return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom) + } + + // Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523 + // (isCollapsed inappropriately returns true in shadow dom) + var selectionCollapsed = function(domSel) { + var collapsed = domSel.isCollapsed; + if (collapsed && result.chrome && domSel.rangeCount && !domSel.getRangeAt(0).collapsed) + { collapsed = false; } + return collapsed + }; + + function keyEvent(keyCode, key) { + var event = document.createEvent("Event"); + event.initEvent("keydown", true, true); + event.keyCode = keyCode; + event.key = event.code = key; + return event + } + + function windowRect(doc) { + return {left: 0, right: doc.documentElement.clientWidth, + top: 0, bottom: doc.documentElement.clientHeight} + } + + function getSide(value, side) { + return typeof value == "number" ? value : value[side] + } + + function clientRect(node) { + var rect = node.getBoundingClientRect(); + // Make sure scrollbar width isn't included in the rectangle + return {left: rect.left, right: rect.left + node.clientWidth, + top: rect.top, bottom: rect.top + node.clientHeight} + } + + function scrollRectIntoView(view, rect, startDOM) { + var scrollThreshold = view.someProp("scrollThreshold") || 0, scrollMargin = view.someProp("scrollMargin") || 5; + var doc = view.dom.ownerDocument; + for (var parent = startDOM || view.dom;; parent = parentNode(parent)) { + if (!parent) { break } + if (parent.nodeType != 1) { continue } + var atTop = parent == doc.body || parent.nodeType != 1; + var bounding = atTop ? windowRect(doc) : clientRect(parent); + var moveX = 0, moveY = 0; + if (rect.top < bounding.top + getSide(scrollThreshold, "top")) + { moveY = -(bounding.top - rect.top + getSide(scrollMargin, "top")); } + else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, "bottom")) + { moveY = rect.bottom - bounding.bottom + getSide(scrollMargin, "bottom"); } + if (rect.left < bounding.left + getSide(scrollThreshold, "left")) + { moveX = -(bounding.left - rect.left + getSide(scrollMargin, "left")); } + else if (rect.right > bounding.right - getSide(scrollThreshold, "right")) + { moveX = rect.right - bounding.right + getSide(scrollMargin, "right"); } + if (moveX || moveY) { + if (atTop) { + doc.defaultView.scrollBy(moveX, moveY); + } else { + var startX = parent.scrollLeft, startY = parent.scrollTop; + if (moveY) { parent.scrollTop += moveY; } + if (moveX) { parent.scrollLeft += moveX; } + var dX = parent.scrollLeft - startX, dY = parent.scrollTop - startY; + rect = {left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY}; + } + } + if (atTop) { break } + } + } + + // Store the scroll position of the editor's parent nodes, along with + // the top position of an element near the top of the editor, which + // will be used to make sure the visible viewport remains stable even + // when the size of the content above changes. + function storeScrollPos(view) { + var rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top); + var refDOM, refTop; + for (var x = (rect.left + rect.right) / 2, y = startY + 1; + y < Math.min(innerHeight, rect.bottom); y += 5) { + var dom = view.root.elementFromPoint(x, y); + if (dom == view.dom || !view.dom.contains(dom)) { continue } + var localRect = dom.getBoundingClientRect(); + if (localRect.top >= startY - 20) { + refDOM = dom; + refTop = localRect.top; + break + } + } + return {refDOM: refDOM, refTop: refTop, stack: scrollStack(view.dom)} + } + + function scrollStack(dom) { + var stack = [], doc = dom.ownerDocument; + for (; dom; dom = parentNode(dom)) { + stack.push({dom: dom, top: dom.scrollTop, left: dom.scrollLeft}); + if (dom == doc) { break } + } + return stack + } + + // Reset the scroll position of the editor's parent nodes to that what + // it was before, when storeScrollPos was called. + function resetScrollPos(ref) { + var refDOM = ref.refDOM; + var refTop = ref.refTop; + var stack = ref.stack; + + var newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0; + restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop); + } + + function restoreScrollStack(stack, dTop) { + for (var i = 0; i < stack.length; i++) { + var ref = stack[i]; + var dom = ref.dom; + var top = ref.top; + var left = ref.left; + if (dom.scrollTop != top + dTop) { dom.scrollTop = top + dTop; } + if (dom.scrollLeft != left) { dom.scrollLeft = left; } + } + } + + var preventScrollSupported = null; + // Feature-detects support for .focus({preventScroll: true}), and uses + // a fallback kludge when not supported. + function focusPreventScroll(dom) { + if (dom.setActive) { return dom.setActive() } // in IE + if (preventScrollSupported) { return dom.focus(preventScrollSupported) } + + var stored = scrollStack(dom); + dom.focus(preventScrollSupported == null ? { + get preventScroll() { + preventScrollSupported = {preventScroll: true}; + return true + } + } : undefined); + if (!preventScrollSupported) { + preventScrollSupported = false; + restoreScrollStack(stored, 0); + } + } + + function findOffsetInNode(node, coords) { + var closest, dxClosest = 2e8, coordsClosest, offset = 0; + var rowBot = coords.top, rowTop = coords.top; + for (var child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) { + var rects = (void 0); + if (child.nodeType == 1) { rects = child.getClientRects(); } + else if (child.nodeType == 3) { rects = textRange(child).getClientRects(); } + else { continue } + + for (var i = 0; i < rects.length; i++) { + var rect = rects[i]; + if (rect.top <= rowBot && rect.bottom >= rowTop) { + rowBot = Math.max(rect.bottom, rowBot); + rowTop = Math.min(rect.top, rowTop); + var dx = rect.left > coords.left ? rect.left - coords.left + : rect.right < coords.left ? coords.left - rect.right : 0; + if (dx < dxClosest) { + closest = child; + dxClosest = dx; + coordsClosest = dx && closest.nodeType == 3 ? {left: rect.right < coords.left ? rect.right : rect.left, top: coords.top} : coords; + if (child.nodeType == 1 && dx) + { offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0); } + continue + } + } + if (!closest && (coords.left >= rect.right && coords.top >= rect.top || + coords.left >= rect.left && coords.top >= rect.bottom)) + { offset = childIndex + 1; } + } + } + if (closest && closest.nodeType == 3) { return findOffsetInText(closest, coordsClosest) } + if (!closest || (dxClosest && closest.nodeType == 1)) { return {node: node, offset: offset} } + return findOffsetInNode(closest, coordsClosest) + } + + function findOffsetInText(node, coords) { + var len = node.nodeValue.length; + var range = document.createRange(); + for (var i = 0; i < len; i++) { + range.setEnd(node, i + 1); + range.setStart(node, i); + var rect = singleRect(range, 1); + if (rect.top == rect.bottom) { continue } + if (inRect(coords, rect)) + { return {node: node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0)} } + } + return {node: node, offset: 0} + } + + function inRect(coords, rect) { + return coords.left >= rect.left - 1 && coords.left <= rect.right + 1&& + coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1 + } + + function targetKludge(dom, coords) { + var parent = dom.parentNode; + if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left) + { return parent } + return dom + } + + function posFromElement(view, elt, coords) { + var ref = findOffsetInNode(elt, coords); + var node = ref.node; + var offset = ref.offset; + var bias = -1; + if (node.nodeType == 1 && !node.firstChild) { + var rect = node.getBoundingClientRect(); + bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1; + } + return view.docView.posFromDOM(node, offset, bias) + } + + function posFromCaret(view, node, offset, coords) { + // Browser (in caretPosition/RangeFromPoint) will agressively + // normalize towards nearby inline nodes. Since we are interested in + // positions between block nodes too, we first walk up the hierarchy + // of nodes to see if there are block nodes that the coordinates + // fall outside of. If so, we take the position before/after that + // block. If not, we call `posFromDOM` on the raw node/offset. + var outside = -1; + for (var cur = node;;) { + if (cur == view.dom) { break } + var desc = view.docView.nearestDesc(cur, true); + if (!desc) { return null } + if (desc.node.isBlock && desc.parent) { + var rect = desc.dom.getBoundingClientRect(); + if (rect.left > coords.left || rect.top > coords.top) { outside = desc.posBefore; } + else if (rect.right < coords.left || rect.bottom < coords.top) { outside = desc.posAfter; } + else { break } + } + cur = desc.dom.parentNode; + } + return outside > -1 ? outside : view.docView.posFromDOM(node, offset) + } + + function elementFromPoint(element, coords, box) { + var len = element.childNodes.length; + if (len && box.top < box.bottom) { + for (var startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI;;) { + var child = element.childNodes[i]; + if (child.nodeType == 1) { + var rects = child.getClientRects(); + for (var j = 0; j < rects.length; j++) { + var rect = rects[j]; + if (inRect(coords, rect)) { return elementFromPoint(child, coords, rect) } + } + } + if ((i = (i + 1) % len) == startI) { break } + } + } + return element + } + + // Given an x,y position on the editor, get the position in the document. + function posAtCoords(view, coords) { + var assign, assign$1; + + var root = view.root, node, offset; + if (root.caretPositionFromPoint) { + try { // Firefox throws for this call in hard-to-predict circumstances (#994) + var pos$1 = root.caretPositionFromPoint(coords.left, coords.top); + if (pos$1) { ((assign = pos$1, node = assign.offsetNode, offset = assign.offset)); } + } catch (_) {} + } + if (!node && root.caretRangeFromPoint) { + var range = root.caretRangeFromPoint(coords.left, coords.top); + if (range) { ((assign$1 = range, node = assign$1.startContainer, offset = assign$1.startOffset)); } + } + + var elt = root.elementFromPoint(coords.left, coords.top + 1), pos; + if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) { + var box = view.dom.getBoundingClientRect(); + if (!inRect(coords, box)) { return null } + elt = elementFromPoint(view.dom, coords, box); + if (!elt) { return null } + } + // Safari's caretRangeFromPoint returns nonsense when on a draggable element + if (result.safari && elt.draggable) { node = offset = null; } + elt = targetKludge(elt, coords); + if (node) { + if (result.gecko && node.nodeType == 1) { + // Firefox will sometimes return offsets into nodes, which + // have no actual children, from caretPositionFromPoint (#953) + offset = Math.min(offset, node.childNodes.length); + // It'll also move the returned position before image nodes, + // even if those are behind it. + if (offset < node.childNodes.length) { + var next = node.childNodes[offset], box$1; + if (next.nodeName == "IMG" && (box$1 = next.getBoundingClientRect()).right <= coords.left && + box$1.bottom > coords.top) + { offset++; } + } + } + // Suspiciously specific kludge to work around caret*FromPoint + // never returning a position at the end of the document + if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 && + coords.top > node.lastChild.getBoundingClientRect().bottom) + { pos = view.state.doc.content.size; } + // Ignore positions directly after a BR, since caret*FromPoint + // 'round up' positions that would be more accurately placed + // before the BR node. + else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != "BR") + { pos = posFromCaret(view, node, offset, coords); } + } + if (pos == null) { pos = posFromElement(view, elt, coords); } + + var desc = view.docView.nearestDesc(elt, true); + return {pos: pos, inside: desc ? desc.posAtStart - desc.border : -1} + } + + function singleRect(object, bias) { + var rects = object.getClientRects(); + return !rects.length ? object.getBoundingClientRect() : rects[bias < 0 ? 0 : rects.length - 1] + } + + var BIDI = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + + // : (EditorView, number, number) → {left: number, top: number, right: number, bottom: number} + // Given a position in the document model, get a bounding box of the + // character at that position, relative to the window. + function coordsAtPos(view, pos, side) { + var ref = view.docView.domFromPos(pos); + var node = ref.node; + var offset = ref.offset; + var $pos = view.state.doc.resolve(pos), inline = $pos.parent.inlineContent; + + // These browsers support querying empty text ranges. Prefer that in + // bidi context. + var supportEmptyRange = result.webkit || result.gecko; + if (node.nodeType == 3 && supportEmptyRange && BIDI.test(node.nodeValue)) { + var rect = singleRect(textRange(node, offset, offset), side); + // Firefox returns bad results (the position before the space) + // when querying a position directly after line-broken + // whitespace. Detect this situation and and kludge around it + if (result.gecko && offset && /\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) { + var rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1); + if (rectBefore.top == rect.top) { + var rectAfter = singleRect(textRange(node, offset, offset + 1), -1); + if (rectAfter.top != rect.top) + { return flattenV(rectAfter, rectAfter.left < rectBefore.left) } + } + } + return rect + } + + // Move up the DOM as far as possible when in inline context. + if (inline) { + var parent = $pos.depth ? view.docView.domAfterPos($pos.before()) : view.dom; + while (side < 0 && !offset && node != parent) { + offset = domIndex(node); + node = node.parentNode; + } + while (side >= 0 && offset == nodeSize(node) && node != parent) { + offset = domIndex(node) + 1; + node = node.parentNode; + } + } + + if (node.nodeType == 3) { + if (side < 0) { return flattenV(singleRect(textRange(node, offset - 1, offset), 1), false) } + return flattenV(singleRect(textRange(node, offset, offset + 1), -1), true) + } + + // Return a horizontal line in block context + if (!inline) { + if (offset && (side < 0 || offset == nodeSize(node))) { + var before = node.childNodes[offset - 1]; + if (before.nodeType == 1) { return flattenH(before.getBoundingClientRect(), false) } + } + if (offset < nodeSize(node)) { + var after = node.childNodes[offset]; + if (after.nodeType == 1) { return flattenH(after.getBoundingClientRect(), true) } + } + return flattenH(node.getBoundingClientRect(), side >= 0) + } + + // Inline, not in text node (this is not Bidi-safe) + if (offset && (side < 0 || offset == nodeSize(node))) { + var before$1 = node.childNodes[offset - 1]; + var target = before$1.nodeType == 3 ? textRange(before$1, nodeSize(before$1) - (supportEmptyRange ? 0 : 1)) + // BR nodes tend to only return the rectangle before them + : before$1.nodeType == 1 && before$1.nodeName != "BR" ? before$1 : null; + if (target) { return flattenV(singleRect(target, 1), false) } + } + if (offset < nodeSize(node)) { + var after$1 = node.childNodes[offset]; + var target$1 = after$1.nodeType == 3 ? textRange(after$1, 0, (supportEmptyRange ? 0 : 1)) + : after$1.nodeType == 1 ? after$1 : null; + if (target$1) { return flattenV(singleRect(target$1, -1), true) } + } + // All else failed, just try to get a rectangle for the target node + return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, -side), side >= 0) + } + + function flattenV(rect, left) { + if (rect.width == 0) { return rect } + var x = left ? rect.left : rect.right; + return {top: rect.top, bottom: rect.bottom, left: x, right: x} + } + + function flattenH(rect, top) { + if (rect.height == 0) { return rect } + var y = top ? rect.top : rect.bottom; + return {top: y, bottom: y, left: rect.left, right: rect.right} + } + + function withFlushedState(view, state, f) { + var viewState = view.state, active = view.root.activeElement; + if (viewState != state) { view.updateState(state); } + if (active != view.dom) { view.focus(); } + try { + return f() + } finally { + if (viewState != state) { view.updateState(viewState); } + if (active != view.dom && active) { active.focus(); } + } + } + + // : (EditorView, number, number) + // Whether vertical position motion in a given direction + // from a position would leave a text block. + function endOfTextblockVertical(view, state, dir) { + var sel = state.selection; + var $pos = dir == "up" ? sel.$anchor.min(sel.$head) : sel.$anchor.max(sel.$head); + return withFlushedState(view, state, function () { + var ref = view.docView.domFromPos($pos.pos); + var dom = ref.node; + for (;;) { + var nearest = view.docView.nearestDesc(dom, true); + if (!nearest) { break } + if (nearest.node.isBlock) { dom = nearest.dom; break } + dom = nearest.dom.parentNode; + } + var coords = coordsAtPos(view, $pos.pos, 1); + for (var child = dom.firstChild; child; child = child.nextSibling) { + var boxes = (void 0); + if (child.nodeType == 1) { boxes = child.getClientRects(); } + else if (child.nodeType == 3) { boxes = textRange(child, 0, child.nodeValue.length).getClientRects(); } + else { continue } + for (var i = 0; i < boxes.length; i++) { + var box = boxes[i]; + if (box.bottom > box.top && (dir == "up" ? box.bottom < coords.top + 1 : box.top > coords.bottom - 1)) + { return false } + } + } + return true + }) + } + + var maybeRTL = /[\u0590-\u08ac]/; + + function endOfTextblockHorizontal(view, state, dir) { + var ref = state.selection; + var $head = ref.$head; + if (!$head.parent.isTextblock) { return false } + var offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size; + var sel = getSelection(); + // If the textblock is all LTR, or the browser doesn't support + // Selection.modify (Edge), fall back to a primitive approach + if (!maybeRTL.test($head.parent.textContent) || !sel.modify) + { return dir == "left" || dir == "backward" ? atStart : atEnd } + + return withFlushedState(view, state, function () { + // This is a huge hack, but appears to be the best we can + // currently do: use `Selection.modify` to move the selection by + // one character, and see if that moves the cursor out of the + // textblock (or doesn't move it at all, when at the start/end of + // the document). + var oldRange = sel.getRangeAt(0), oldNode = sel.focusNode, oldOff = sel.focusOffset; + var oldBidiLevel = sel.caretBidiLevel; // Only for Firefox + sel.modify("move", dir, "character"); + var parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom; + var result = !parentDOM.contains(sel.focusNode.nodeType == 1 ? sel.focusNode : sel.focusNode.parentNode) || + (oldNode == sel.focusNode && oldOff == sel.focusOffset); + // Restore the previous selection + sel.removeAllRanges(); + sel.addRange(oldRange); + if (oldBidiLevel != null) { sel.caretBidiLevel = oldBidiLevel; } + return result + }) + } + + var cachedState = null, cachedDir = null, cachedResult = false; + function endOfTextblock(view, state, dir) { + if (cachedState == state && cachedDir == dir) { return cachedResult } + cachedState = state; cachedDir = dir; + return cachedResult = dir == "up" || dir == "down" + ? endOfTextblockVertical(view, state, dir) + : endOfTextblockHorizontal(view, state, dir) + } + + // NodeView:: interface + // + // By default, document nodes are rendered using the result of the + // [`toDOM`](#model.NodeSpec.toDOM) method of their spec, and managed + // entirely by the editor. For some use cases, such as embedded + // node-specific editing interfaces, you want more control over + // the behavior of a node's in-editor representation, and need to + // [define](#view.EditorProps.nodeViews) a custom node view. + // + // Mark views only support `dom` and `contentDOM`, and don't support + // any of the node view methods. + // + // Objects returned as node views must conform to this interface. + // + // dom:: ?dom.Node + // The outer DOM node that represents the document node. When not + // given, the default strategy is used to create a DOM node. + // + // contentDOM:: ?dom.Node + // The DOM node that should hold the node's content. Only meaningful + // if the node view also defines a `dom` property and if its node + // type is not a leaf node type. When this is present, ProseMirror + // will take care of rendering the node's children into it. When it + // is not present, the node view itself is responsible for rendering + // (or deciding not to render) its child nodes. + // + // update:: ?(node: Node, decorations: [Decoration]) → bool + // When given, this will be called when the view is updating itself. + // It will be given a node (possibly of a different type), and an + // array of active decorations (which are automatically drawn, and + // the node view may ignore if it isn't interested in them), and + // should return true if it was able to update to that node, and + // false otherwise. If the node view has a `contentDOM` property (or + // no `dom` property), updating its child nodes will be handled by + // ProseMirror. + // + // selectNode:: ?() + // Can be used to override the way the node's selected status (as a + // node selection) is displayed. + // + // deselectNode:: ?() + // When defining a `selectNode` method, you should also provide a + // `deselectNode` method to remove the effect again. + // + // setSelection:: ?(anchor: number, head: number, root: dom.Document) + // This will be called to handle setting the selection inside the + // node. The `anchor` and `head` positions are relative to the start + // of the node. By default, a DOM selection will be created between + // the DOM positions corresponding to those positions, but if you + // override it you can do something else. + // + // stopEvent:: ?(event: dom.Event) → bool + // Can be used to prevent the editor view from trying to handle some + // or all DOM events that bubble up from the node view. Events for + // which this returns true are not handled by the editor. + // + // ignoreMutation:: ?(dom.MutationRecord) → bool + // Called when a DOM + // [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) + // or a selection change happens within the view. When the change is + // a selection change, the record will have a `type` property of + // `"selection"` (which doesn't occur for native mutation records). + // Return false if the editor should re-read the selection or + // re-parse the range around the mutation, true if it can safely be + // ignored. + // + // destroy:: ?() + // Called when the node view is removed from the editor or the whole + // editor is destroyed. + + // View descriptions are data structures that describe the DOM that is + // used to represent the editor's content. They are used for: + // + // - Incremental redrawing when the document changes + // + // - Figuring out what part of the document a given DOM position + // corresponds to + // + // - Wiring in custom implementations of the editing interface for a + // given node + // + // They form a doubly-linked mutable tree, starting at `view.docView`. + + var NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3; + + // Superclass for the various kinds of descriptions. Defines their + // basic structure and shared methods. + var ViewDesc = function ViewDesc(parent, children, dom, contentDOM) { + this.parent = parent; + this.children = children; + this.dom = dom; + // An expando property on the DOM node provides a link back to its + // description. + dom.pmViewDesc = this; + // This is the node that holds the child views. It may be null for + // descs that don't have children. + this.contentDOM = contentDOM; + this.dirty = NOT_DIRTY; + }; + + var prototypeAccessors$9 = { beforePosition: { configurable: true },size: { configurable: true },border: { configurable: true },posBefore: { configurable: true },posAtStart: { configurable: true },posAfter: { configurable: true },posAtEnd: { configurable: true },contentLost: { configurable: true } }; + + // Used to check whether a given description corresponds to a + // widget/mark/node. + ViewDesc.prototype.matchesWidget = function matchesWidget () { return false }; + ViewDesc.prototype.matchesMark = function matchesMark () { return false }; + ViewDesc.prototype.matchesNode = function matchesNode () { return false }; + ViewDesc.prototype.matchesHack = function matchesHack () { return false }; + + prototypeAccessors$9.beforePosition.get = function () { return false }; + + // : () → ?ParseRule + // When parsing in-editor content (in domchange.js), we allow + // descriptions to determine the parse rules that should be used to + // parse them. + ViewDesc.prototype.parseRule = function parseRule () { return null }; + + // : (dom.Event) → bool + // Used by the editor's event handler to ignore events that come + // from certain descs. + ViewDesc.prototype.stopEvent = function stopEvent () { return false }; + + // The size of the content represented by this desc. + prototypeAccessors$9.size.get = function () { + var size = 0; + for (var i = 0; i < this.children.length; i++) { size += this.children[i].size; } + return size + }; + + // For block nodes, this represents the space taken up by their + // start/end tokens. + prototypeAccessors$9.border.get = function () { return 0 }; + + ViewDesc.prototype.destroy = function destroy () { + this.parent = null; + if (this.dom.pmViewDesc == this) { this.dom.pmViewDesc = null; } + for (var i = 0; i < this.children.length; i++) + { this.children[i].destroy(); } + }; + + ViewDesc.prototype.posBeforeChild = function posBeforeChild (child) { + for (var i = 0, pos = this.posAtStart; i < this.children.length; i++) { + var cur = this.children[i]; + if (cur == child) { return pos } + pos += cur.size; + } + }; + + prototypeAccessors$9.posBefore.get = function () { + return this.parent.posBeforeChild(this) + }; + + prototypeAccessors$9.posAtStart.get = function () { + return this.parent ? this.parent.posBeforeChild(this) + this.border : 0 + }; + + prototypeAccessors$9.posAfter.get = function () { + return this.posBefore + this.size + }; + + prototypeAccessors$9.posAtEnd.get = function () { + return this.posAtStart + this.size - 2 * this.border + }; + + // : (dom.Node, number, ?number) → number + ViewDesc.prototype.localPosFromDOM = function localPosFromDOM (dom, offset, bias) { + // If the DOM position is in the content, use the child desc after + // it to figure out a position. + if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) { + if (bias < 0) { + var domBefore, desc; + if (dom == this.contentDOM) { + domBefore = dom.childNodes[offset - 1]; + } else { + while (dom.parentNode != this.contentDOM) { dom = dom.parentNode; } + domBefore = dom.previousSibling; + } + while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this)) { domBefore = domBefore.previousSibling; } + return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart + } else { + var domAfter, desc$1; + if (dom == this.contentDOM) { + domAfter = dom.childNodes[offset]; + } else { + while (dom.parentNode != this.contentDOM) { dom = dom.parentNode; } + domAfter = dom.nextSibling; + } + while (domAfter && !((desc$1 = domAfter.pmViewDesc) && desc$1.parent == this)) { domAfter = domAfter.nextSibling; } + return domAfter ? this.posBeforeChild(desc$1) : this.posAtEnd + } + } + // Otherwise, use various heuristics, falling back on the bias + // parameter, to determine whether to return the position at the + // start or at the end of this view desc. + var atEnd; + if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) { + atEnd = dom.compareDocumentPosition(this.contentDOM) & 2; + } else if (this.dom.firstChild) { + if (offset == 0) { for (var search = dom;; search = search.parentNode) { + if (search == this.dom) { atEnd = false; break } + if (search.parentNode.firstChild != search) { break } + } } + if (atEnd == null && offset == dom.childNodes.length) { for (var search$1 = dom;; search$1 = search$1.parentNode) { + if (search$1 == this.dom) { atEnd = true; break } + if (search$1.parentNode.lastChild != search$1) { break } + } } + } + return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart + }; + + // Scan up the dom finding the first desc that is a descendant of + // this one. + ViewDesc.prototype.nearestDesc = function nearestDesc (dom, onlyNodes) { + for (var first = true, cur = dom; cur; cur = cur.parentNode) { + var desc = this.getDesc(cur); + if (desc && (!onlyNodes || desc.node)) { + // If dom is outside of this desc's nodeDOM, don't count it. + if (first && desc.nodeDOM && + !(desc.nodeDOM.nodeType == 1 ? desc.nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : desc.nodeDOM == dom)) + { first = false; } + else + { return desc } + } + } + }; + + ViewDesc.prototype.getDesc = function getDesc (dom) { + var desc = dom.pmViewDesc; + for (var cur = desc; cur; cur = cur.parent) { if (cur == this) { return desc } } + }; + + ViewDesc.prototype.posFromDOM = function posFromDOM (dom, offset, bias) { + for (var scan = dom; scan; scan = scan.parentNode) { + var desc = this.getDesc(scan); + if (desc) { return desc.localPosFromDOM(dom, offset, bias) } + } + return -1 + }; + + // : (number) → ?NodeViewDesc + // Find the desc for the node after the given pos, if any. (When a + // parent node overrode rendering, there might not be one.) + ViewDesc.prototype.descAt = function descAt (pos) { + for (var i = 0, offset = 0; i < this.children.length; i++) { + var child = this.children[i], end = offset + child.size; + if (offset == pos && end != offset) { + while (!child.border && child.children.length) { child = child.children[0]; } + return child + } + if (pos < end) { return child.descAt(pos - offset - child.border) } + offset = end; + } + }; + + // : (number) → {node: dom.Node, offset: number} + ViewDesc.prototype.domFromPos = function domFromPos (pos) { + if (!this.contentDOM) { return {node: this.dom, offset: 0} } + for (var offset = 0, i = 0;; i++) { + if (offset == pos) { + while (i < this.children.length && (this.children[i].beforePosition || this.children[i].dom.parentNode != this.contentDOM)) { i++; } + return {node: this.contentDOM, + offset: i == this.children.length ? this.contentDOM.childNodes.length : domIndex(this.children[i].dom)} + } + if (i == this.children.length) { throw new Error("Invalid position " + pos) } + var child = this.children[i], end = offset + child.size; + if (pos < end) { return child.domFromPos(pos - offset - child.border) } + offset = end; + } + }; + + // Used to find a DOM range in a single parent for a given changed + // range. + ViewDesc.prototype.parseRange = function parseRange (from, to, base) { + if ( base === void 0 ) base = 0; + + if (this.children.length == 0) + { return {node: this.contentDOM, from: from, to: to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length} } + + var fromOffset = -1, toOffset = -1; + for (var offset = base, i = 0;; i++) { + var child = this.children[i], end = offset + child.size; + if (fromOffset == -1 && from <= end) { + var childBase = offset + child.border; + // FIXME maybe descend mark views to parse a narrower range? + if (from >= childBase && to <= end - child.border && child.node && + child.contentDOM && this.contentDOM.contains(child.contentDOM)) + { return child.parseRange(from, to, childBase) } + + from = offset; + for (var j = i; j > 0; j--) { + var prev = this.children[j - 1]; + if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) { + fromOffset = domIndex(prev.dom) + 1; + break + } + from -= prev.size; + } + if (fromOffset == -1) { fromOffset = 0; } + } + if (fromOffset > -1 && (end > to || i == this.children.length - 1)) { + to = end; + for (var j$1 = i + 1; j$1 < this.children.length; j$1++) { + var next = this.children[j$1]; + if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) { + toOffset = domIndex(next.dom); + break + } + to += next.size; + } + if (toOffset == -1) { toOffset = this.contentDOM.childNodes.length; } + break + } + offset = end; + } + return {node: this.contentDOM, from: from, to: to, fromOffset: fromOffset, toOffset: toOffset} + }; + + ViewDesc.prototype.emptyChildAt = function emptyChildAt (side) { + if (this.border || !this.contentDOM || !this.children.length) { return false } + var child = this.children[side < 0 ? 0 : this.children.length - 1]; + return child.size == 0 || child.emptyChildAt(side) + }; + + // : (number) → dom.Node + ViewDesc.prototype.domAfterPos = function domAfterPos (pos) { + var ref = this.domFromPos(pos); + var node = ref.node; + var offset = ref.offset; + if (node.nodeType != 1 || offset == node.childNodes.length) + { throw new RangeError("No node after pos " + pos) } + return node.childNodes[offset] + }; + + // : (number, number, dom.Document) + // View descs are responsible for setting any selection that falls + // entirely inside of them, so that custom implementations can do + // custom things with the selection. Note that this falls apart when + // a selection starts in such a node and ends in another, in which + // case we just use whatever domFromPos produces as a best effort. + ViewDesc.prototype.setSelection = function setSelection (anchor, head, root, force) { + // If the selection falls entirely in a child, give it to that child + var from = Math.min(anchor, head), to = Math.max(anchor, head); + for (var i = 0, offset = 0; i < this.children.length; i++) { + var child = this.children[i], end = offset + child.size; + if (from > offset && to < end) + { return child.setSelection(anchor - offset - child.border, head - offset - child.border, root, force) } + offset = end; + } + + var anchorDOM = this.domFromPos(anchor), headDOM = this.domFromPos(head); + var domSel = root.getSelection(); + + var brKludge = false; + // On Firefox, using Selection.collapse to put the cursor after a + // BR node for some reason doesn't always work (#1073). On Safari, + // the cursor sometimes inexplicable visually lags behind its + // reported position in such situations (#1092). + if ((result.gecko || result.safari) && anchor == head) { + var prev = anchorDOM.node.childNodes[anchorDOM.offset - 1]; + brKludge = prev && (prev.nodeName == "BR" || prev.contentEditable == "false"); + } + + if (!(force || brKludge && result.safari) && + isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset) && + isEquivalentPosition(headDOM.node, headDOM.offset, domSel.focusNode, domSel.focusOffset)) + { return } + + // Selection.extend can be used to create an 'inverted' selection + // (one where the focus is before the anchor), but not all + // browsers support it yet. + var domSelExtended = false; + if ((domSel.extend || anchor == head) && !brKludge) { + domSel.collapse(anchorDOM.node, anchorDOM.offset); + try { + if (anchor != head) { domSel.extend(headDOM.node, headDOM.offset); } + domSelExtended = true; + } catch (err) { + // In some cases with Chrome the selection is empty after calling + // collapse, even when it should be valid. This appears to be a bug, but + // it is difficult to isolate. If this happens fallback to the old path + // without using extend. + if (!(err instanceof DOMException)) { throw err } + // declare global: DOMException + } + } + if (!domSelExtended) { + if (anchor > head) { var tmp = anchorDOM; anchorDOM = headDOM; headDOM = tmp; } + var range = document.createRange(); + range.setEnd(headDOM.node, headDOM.offset); + range.setStart(anchorDOM.node, anchorDOM.offset); + domSel.removeAllRanges(); + domSel.addRange(range); + } + }; + + // : (dom.MutationRecord) → bool + ViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) { + return !this.contentDOM && mutation.type != "selection" + }; + + prototypeAccessors$9.contentLost.get = function () { + return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM) + }; + + // Remove a subtree of the element tree that has been touched + // by a DOM change, so that the next update will redraw it. + ViewDesc.prototype.markDirty = function markDirty (from, to) { + for (var offset = 0, i = 0; i < this.children.length; i++) { + var child = this.children[i], end = offset + child.size; + if (offset == end ? from <= end && to >= offset : from < end && to > offset) { + var startInside = offset + child.border, endInside = end - child.border; + if (from >= startInside && to <= endInside) { + this.dirty = from == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY; + if (from == startInside && to == endInside && + (child.contentLost || child.dom.parentNode != this.contentDOM)) { child.dirty = NODE_DIRTY; } + else { child.markDirty(from - startInside, to - startInside); } + return + } else { + child.dirty = NODE_DIRTY; + } + } + offset = end; + } + this.dirty = CONTENT_DIRTY; + }; + + ViewDesc.prototype.markParentsDirty = function markParentsDirty () { + var level = 1; + for (var node = this.parent; node; node = node.parent, level++) { + var dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY; + if (node.dirty < dirty) { node.dirty = dirty; } + } + }; + + Object.defineProperties( ViewDesc.prototype, prototypeAccessors$9 ); + + // Reused array to avoid allocating fresh arrays for things that will + // stay empty anyway. + var nothing = []; + + // A widget desc represents a widget decoration, which is a DOM node + // drawn between the document nodes. + var WidgetViewDesc = /*@__PURE__*/(function (ViewDesc) { + function WidgetViewDesc(parent, widget, view, pos) { + var self, dom = widget.type.toDOM; + if (typeof dom == "function") { dom = dom(view, function () { + if (!self) { return pos } + if (self.parent) { return self.parent.posBeforeChild(self) } + }); } + if (!widget.type.spec.raw) { + if (dom.nodeType != 1) { + var wrap = document.createElement("span"); + wrap.appendChild(dom); + dom = wrap; + } + dom.contentEditable = false; + dom.classList.add("ProseMirror-widget"); + } + ViewDesc.call(this, parent, nothing, dom, null); + this.widget = widget; + self = this; + } + + if ( ViewDesc ) WidgetViewDesc.__proto__ = ViewDesc; + WidgetViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype ); + WidgetViewDesc.prototype.constructor = WidgetViewDesc; + + var prototypeAccessors$1 = { beforePosition: { configurable: true } }; + + prototypeAccessors$1.beforePosition.get = function () { + return this.widget.type.side < 0 + }; + + WidgetViewDesc.prototype.matchesWidget = function matchesWidget (widget) { + return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type) + }; + + WidgetViewDesc.prototype.parseRule = function parseRule () { return {ignore: true} }; + + WidgetViewDesc.prototype.stopEvent = function stopEvent (event) { + var stop = this.widget.spec.stopEvent; + return stop ? stop(event) : false + }; + + WidgetViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) { + return mutation.type != "selection" || this.widget.spec.ignoreSelection + }; + + Object.defineProperties( WidgetViewDesc.prototype, prototypeAccessors$1 ); + + return WidgetViewDesc; + }(ViewDesc)); + + var CompositionViewDesc = /*@__PURE__*/(function (ViewDesc) { + function CompositionViewDesc(parent, dom, textDOM, text) { + ViewDesc.call(this, parent, nothing, dom, null); + this.textDOM = textDOM; + this.text = text; + } + + if ( ViewDesc ) CompositionViewDesc.__proto__ = ViewDesc; + CompositionViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype ); + CompositionViewDesc.prototype.constructor = CompositionViewDesc; + + var prototypeAccessors$2 = { size: { configurable: true } }; + + prototypeAccessors$2.size.get = function () { return this.text.length }; + + CompositionViewDesc.prototype.localPosFromDOM = function localPosFromDOM (dom, offset) { + if (dom != this.textDOM) { return this.posAtStart + (offset ? this.size : 0) } + return this.posAtStart + offset + }; + + CompositionViewDesc.prototype.domFromPos = function domFromPos (pos) { + return {node: this.textDOM, offset: pos} + }; + + CompositionViewDesc.prototype.ignoreMutation = function ignoreMutation (mut) { + return mut.type === 'characterData' && mut.target.nodeValue == mut.oldValue + }; + + Object.defineProperties( CompositionViewDesc.prototype, prototypeAccessors$2 ); + + return CompositionViewDesc; + }(ViewDesc)); + + // A mark desc represents a mark. May have multiple children, + // depending on how the mark is split. Note that marks are drawn using + // a fixed nesting order, for simplicity and predictability, so in + // some cases they will be split more often than would appear + // necessary. + var MarkViewDesc = /*@__PURE__*/(function (ViewDesc) { + function MarkViewDesc(parent, mark, dom, contentDOM) { + ViewDesc.call(this, parent, [], dom, contentDOM); + this.mark = mark; + } + + if ( ViewDesc ) MarkViewDesc.__proto__ = ViewDesc; + MarkViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype ); + MarkViewDesc.prototype.constructor = MarkViewDesc; + + MarkViewDesc.create = function create (parent, mark, inline, view) { + var custom = view.nodeViews[mark.type.name]; + var spec = custom && custom(mark, view, inline); + if (!spec || !spec.dom) + { spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline)); } + return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom) + }; + + MarkViewDesc.prototype.parseRule = function parseRule () { return {mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM} }; + + MarkViewDesc.prototype.matchesMark = function matchesMark (mark) { return this.dirty != NODE_DIRTY && this.mark.eq(mark) }; + + MarkViewDesc.prototype.markDirty = function markDirty (from, to) { + ViewDesc.prototype.markDirty.call(this, from, to); + // Move dirty info to nearest node view + if (this.dirty != NOT_DIRTY) { + var parent = this.parent; + while (!parent.node) { parent = parent.parent; } + if (parent.dirty < this.dirty) { parent.dirty = this.dirty; } + this.dirty = NOT_DIRTY; + } + }; + + MarkViewDesc.prototype.slice = function slice (from, to, view) { + var copy = MarkViewDesc.create(this.parent, this.mark, true, view); + var nodes = this.children, size = this.size; + if (to < size) { nodes = replaceNodes(nodes, to, size, view); } + if (from > 0) { nodes = replaceNodes(nodes, 0, from, view); } + for (var i = 0; i < nodes.length; i++) { nodes[i].parent = copy; } + copy.children = nodes; + return copy + }; + + return MarkViewDesc; + }(ViewDesc)); + + // Node view descs are the main, most common type of view desc, and + // correspond to an actual node in the document. Unlike mark descs, + // they populate their child array themselves. + var NodeViewDesc = /*@__PURE__*/(function (ViewDesc) { + function NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) { + ViewDesc.call(this, parent, node.isLeaf ? nothing : [], dom, contentDOM); + this.nodeDOM = nodeDOM; + this.node = node; + this.outerDeco = outerDeco; + this.innerDeco = innerDeco; + if (contentDOM) { this.updateChildren(view, pos); } + } + + if ( ViewDesc ) NodeViewDesc.__proto__ = ViewDesc; + NodeViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype ); + NodeViewDesc.prototype.constructor = NodeViewDesc; + + var prototypeAccessors$3 = { size: { configurable: true },border: { configurable: true } }; + + // By default, a node is rendered using the `toDOM` method from the + // node type spec. But client code can use the `nodeViews` spec to + // supply a custom node view, which can influence various aspects of + // the way the node works. + // + // (Using subclassing for this was intentionally decided against, + // since it'd require exposing a whole slew of finnicky + // implementation details to the user code that they probably will + // never need.) + NodeViewDesc.create = function create (parent, node, outerDeco, innerDeco, view, pos) { + var assign; + + var custom = view.nodeViews[node.type.name], descObj; + var spec = custom && custom(node, view, function () { + // (This is a function that allows the custom view to find its + // own position) + if (!descObj) { return pos } + if (descObj.parent) { return descObj.parent.posBeforeChild(descObj) } + }, outerDeco); + + var dom = spec && spec.dom, contentDOM = spec && spec.contentDOM; + if (node.isText) { + if (!dom) { dom = document.createTextNode(node.text); } + else if (dom.nodeType != 3) { throw new RangeError("Text must be rendered as a DOM text node") } + } else if (!dom) { + ((assign = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node)), dom = assign.dom, contentDOM = assign.contentDOM)); + } + if (!contentDOM && !node.isText && dom.nodeName != "BR") { // Chrome gets confused by
+ if (!dom.hasAttribute("contenteditable")) { dom.contentEditable = false; } + if (node.type.spec.draggable) { dom.draggable = true; } + } + + var nodeDOM = dom; + dom = applyOuterDeco(dom, outerDeco, node); + + if (spec) + { return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, + spec, view, pos + 1) } + else if (node.isText) + { return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) } + else + { return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos + 1) } + }; + + NodeViewDesc.prototype.parseRule = function parseRule () { + var this$1 = this; + + // Experimental kludge to allow opt-in re-parsing of nodes + if (this.node.type.spec.reparseInView) { return null } + // FIXME the assumption that this can always return the current + // attrs means that if the user somehow manages to change the + // attrs in the dom, that won't be picked up. Not entirely sure + // whether this is a problem + var rule = {node: this.node.type.name, attrs: this.node.attrs}; + if (this.node.type.spec.code) { rule.preserveWhitespace = "full"; } + if (this.contentDOM && !this.contentLost) { rule.contentElement = this.contentDOM; } + else { rule.getContent = function () { return this$1.contentDOM ? Fragment.empty : this$1.node.content; }; } + return rule + }; + + NodeViewDesc.prototype.matchesNode = function matchesNode (node, outerDeco, innerDeco) { + return this.dirty == NOT_DIRTY && node.eq(this.node) && + sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco) + }; + + prototypeAccessors$3.size.get = function () { return this.node.nodeSize }; + + prototypeAccessors$3.border.get = function () { return this.node.isLeaf ? 0 : 1 }; + + // Syncs `this.children` to match `this.node.content` and the local + // decorations, possibly introducing nesting for marks. Then, in a + // separate step, syncs the DOM inside `this.contentDOM` to + // `this.children`. + NodeViewDesc.prototype.updateChildren = function updateChildren (view, pos) { + var this$1 = this; + + var inline = this.node.inlineContent, off = pos; + var composition = inline && view.composing && this.localCompositionNode(view, pos); + var updater = new ViewTreeUpdater(this, composition && composition.node); + iterDeco(this.node, this.innerDeco, function (widget, i, insideNode) { + if (widget.spec.marks) + { updater.syncToMarks(widget.spec.marks, inline, view); } + else if (widget.type.side >= 0 && !insideNode) + { updater.syncToMarks(i == this$1.node.childCount ? Mark.none : this$1.node.child(i).marks, inline, view); } + // If the next node is a desc matching this widget, reuse it, + // otherwise insert the widget as a new view desc. + updater.placeWidget(widget, view, off); + }, function (child, outerDeco, innerDeco, i) { + // Make sure the wrapping mark descs match the node's marks. + updater.syncToMarks(child.marks, inline, view); + // Either find an existing desc that exactly matches this node, + // and drop the descs before it. + updater.findNodeMatch(child, outerDeco, innerDeco, i) || + // Or try updating the next desc to reflect this node. + updater.updateNextNode(child, outerDeco, innerDeco, view, i) || + // Or just add it as a new desc. + updater.addNode(child, outerDeco, innerDeco, view, off); + off += child.nodeSize; + }); + // Drop all remaining descs after the current position. + updater.syncToMarks(nothing, inline, view); + if (this.node.isTextblock) { updater.addTextblockHacks(); } + updater.destroyRest(); + + // Sync the DOM if anything changed + if (updater.changed || this.dirty == CONTENT_DIRTY) { + // May have to protect focused DOM from being changed if a composition is active + if (composition) { this.protectLocalComposition(view, composition); } + renderDescs(this.contentDOM, this.children, view); + if (result.ios) { iosHacks(this.dom); } + } + }; + + NodeViewDesc.prototype.localCompositionNode = function localCompositionNode (view, pos) { + // Only do something if both the selection and a focused text node + // are inside of this node, and the node isn't already part of a + // view that's a child of this view + var ref = view.state.selection; + var from = ref.from; + var to = ref.to; + if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size) { return } + var sel = view.root.getSelection(); + var textNode = nearbyTextNode(sel.focusNode, sel.focusOffset); + if (!textNode || !this.dom.contains(textNode.parentNode)) { return } + + // Find the text in the focused node in the node, stop if it's not + // there (may have been modified through other means, in which + // case it should overwritten) + var text = textNode.nodeValue; + var textPos = findTextInFragment(this.node.content, text, from - pos, to - pos); + + return textPos < 0 ? null : {node: textNode, pos: textPos, text: text} + }; + + NodeViewDesc.prototype.protectLocalComposition = function protectLocalComposition (view, ref) { + var node = ref.node; + var pos = ref.pos; + var text = ref.text; + + // The node is already part of a local view desc, leave it there + if (this.getDesc(node)) { return } + + // Create a composition view for the orphaned nodes + var topNode = node; + for (;; topNode = topNode.parentNode) { + if (topNode.parentNode == this.contentDOM) { break } + while (topNode.previousSibling) { topNode.parentNode.removeChild(topNode.previousSibling); } + while (topNode.nextSibling) { topNode.parentNode.removeChild(topNode.nextSibling); } + if (topNode.pmViewDesc) { topNode.pmViewDesc = null; } + } + var desc = new CompositionViewDesc(this, topNode, node, text); + view.compositionNodes.push(desc); + + // Patch up this.children to contain the composition view + this.children = replaceNodes(this.children, pos, pos + text.length, view, desc); + }; + + // : (Node, [Decoration], DecorationSet, EditorView) → bool + // If this desc be updated to match the given node decoration, + // do so and return true. + NodeViewDesc.prototype.update = function update (node, outerDeco, innerDeco, view) { + if (this.dirty == NODE_DIRTY || + !node.sameMarkup(this.node)) { return false } + this.updateInner(node, outerDeco, innerDeco, view); + return true + }; + + NodeViewDesc.prototype.updateInner = function updateInner (node, outerDeco, innerDeco, view) { + this.updateOuterDeco(outerDeco); + this.node = node; + this.innerDeco = innerDeco; + if (this.contentDOM) { this.updateChildren(view, this.posAtStart); } + this.dirty = NOT_DIRTY; + }; + + NodeViewDesc.prototype.updateOuterDeco = function updateOuterDeco (outerDeco) { + if (sameOuterDeco(outerDeco, this.outerDeco)) { return } + var needsWrap = this.nodeDOM.nodeType != 1; + var oldDOM = this.dom; + this.dom = patchOuterDeco(this.dom, this.nodeDOM, + computeOuterDeco(this.outerDeco, this.node, needsWrap), + computeOuterDeco(outerDeco, this.node, needsWrap)); + if (this.dom != oldDOM) { + oldDOM.pmViewDesc = null; + this.dom.pmViewDesc = this; + } + this.outerDeco = outerDeco; + }; + + // Mark this node as being the selected node. + NodeViewDesc.prototype.selectNode = function selectNode () { + this.nodeDOM.classList.add("ProseMirror-selectednode"); + if (this.contentDOM || !this.node.type.spec.draggable) { this.dom.draggable = true; } + }; + + // Remove selected node marking from this node. + NodeViewDesc.prototype.deselectNode = function deselectNode () { + this.nodeDOM.classList.remove("ProseMirror-selectednode"); + if (this.contentDOM || !this.node.type.spec.draggable) { this.dom.removeAttribute("draggable"); } + }; + + Object.defineProperties( NodeViewDesc.prototype, prototypeAccessors$3 ); + + return NodeViewDesc; + }(ViewDesc)); + + // Create a view desc for the top-level document node, to be exported + // and used by the view class. + function docViewDesc(doc, outerDeco, innerDeco, dom, view) { + applyOuterDeco(dom, outerDeco, doc); + return new NodeViewDesc(null, doc, outerDeco, innerDeco, dom, dom, dom, view, 0) + } + + var TextViewDesc = /*@__PURE__*/(function (NodeViewDesc) { + function TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) { + NodeViewDesc.call(this, parent, node, outerDeco, innerDeco, dom, null, nodeDOM, view); + } + + if ( NodeViewDesc ) TextViewDesc.__proto__ = NodeViewDesc; + TextViewDesc.prototype = Object.create( NodeViewDesc && NodeViewDesc.prototype ); + TextViewDesc.prototype.constructor = TextViewDesc; + + TextViewDesc.prototype.parseRule = function parseRule () { + var skip = this.nodeDOM.parentNode; + while (skip && skip != this.dom && !skip.pmIsDeco) { skip = skip.parentNode; } + return {skip: skip || true} + }; + + TextViewDesc.prototype.update = function update (node, outerDeco, _, view) { + if (this.dirty == NODE_DIRTY || (this.dirty != NOT_DIRTY && !this.inParent()) || + !node.sameMarkup(this.node)) { return false } + this.updateOuterDeco(outerDeco); + if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) { + this.nodeDOM.nodeValue = node.text; + if (view.trackWrites == this.nodeDOM) { view.trackWrites = null; } + } + this.node = node; + this.dirty = NOT_DIRTY; + return true + }; + + TextViewDesc.prototype.inParent = function inParent () { + var parentDOM = this.parent.contentDOM; + for (var n = this.nodeDOM; n; n = n.parentNode) { if (n == parentDOM) { return true } } + return false + }; + + TextViewDesc.prototype.domFromPos = function domFromPos (pos) { + return {node: this.nodeDOM, offset: pos} + }; + + TextViewDesc.prototype.localPosFromDOM = function localPosFromDOM (dom, offset, bias) { + if (dom == this.nodeDOM) { return this.posAtStart + Math.min(offset, this.node.text.length) } + return NodeViewDesc.prototype.localPosFromDOM.call(this, dom, offset, bias) + }; + + TextViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) { + return mutation.type != "characterData" && mutation.type != "selection" + }; + + TextViewDesc.prototype.slice = function slice (from, to, view) { + var node = this.node.cut(from, to), dom = document.createTextNode(node.text); + return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view) + }; + + return TextViewDesc; + }(NodeViewDesc)); + + // A dummy desc used to tag trailing BR or span nodes created to work + // around contentEditable terribleness. + var BRHackViewDesc = /*@__PURE__*/(function (ViewDesc) { + function BRHackViewDesc () { + ViewDesc.apply(this, arguments); + } + + if ( ViewDesc ) BRHackViewDesc.__proto__ = ViewDesc; + BRHackViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype ); + BRHackViewDesc.prototype.constructor = BRHackViewDesc; + + BRHackViewDesc.prototype.parseRule = function parseRule () { return {ignore: true} }; + BRHackViewDesc.prototype.matchesHack = function matchesHack () { return this.dirty == NOT_DIRTY }; + + return BRHackViewDesc; + }(ViewDesc)); + + // A separate subclass is used for customized node views, so that the + // extra checks only have to be made for nodes that are actually + // customized. + var CustomNodeViewDesc = /*@__PURE__*/(function (NodeViewDesc) { + function CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) { + NodeViewDesc.call(this, parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos); + this.spec = spec; + } + + if ( NodeViewDesc ) CustomNodeViewDesc.__proto__ = NodeViewDesc; + CustomNodeViewDesc.prototype = Object.create( NodeViewDesc && NodeViewDesc.prototype ); + CustomNodeViewDesc.prototype.constructor = CustomNodeViewDesc; + + // A custom `update` method gets to decide whether the update goes + // through. If it does, and there's a `contentDOM` node, our logic + // updates the children. + CustomNodeViewDesc.prototype.update = function update (node, outerDeco, innerDeco, view) { + if (this.dirty == NODE_DIRTY) { return false } + if (this.spec.update) { + var result = this.spec.update(node, outerDeco); + if (result) { this.updateInner(node, outerDeco, innerDeco, view); } + return result + } else if (!this.contentDOM && !node.isLeaf) { + return false + } else { + return NodeViewDesc.prototype.update.call(this, node, outerDeco, innerDeco, view) + } + }; + + CustomNodeViewDesc.prototype.selectNode = function selectNode () { + this.spec.selectNode ? this.spec.selectNode() : NodeViewDesc.prototype.selectNode.call(this); + }; + + CustomNodeViewDesc.prototype.deselectNode = function deselectNode () { + this.spec.deselectNode ? this.spec.deselectNode() : NodeViewDesc.prototype.deselectNode.call(this); + }; + + CustomNodeViewDesc.prototype.setSelection = function setSelection (anchor, head, root, force) { + this.spec.setSelection ? this.spec.setSelection(anchor, head, root) + : NodeViewDesc.prototype.setSelection.call(this, anchor, head, root, force); + }; + + CustomNodeViewDesc.prototype.destroy = function destroy () { + if (this.spec.destroy) { this.spec.destroy(); } + NodeViewDesc.prototype.destroy.call(this); + }; + + CustomNodeViewDesc.prototype.stopEvent = function stopEvent (event) { + return this.spec.stopEvent ? this.spec.stopEvent(event) : false + }; + + CustomNodeViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) { + return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : NodeViewDesc.prototype.ignoreMutation.call(this, mutation) + }; + + return CustomNodeViewDesc; + }(NodeViewDesc)); + + // : (dom.Node, [ViewDesc]) + // Sync the content of the given DOM node with the nodes associated + // with the given array of view descs, recursing into mark descs + // because this should sync the subtree for a whole node at a time. + function renderDescs(parentDOM, descs, view) { + var dom = parentDOM.firstChild, written = false; + for (var i = 0; i < descs.length; i++) { + var desc = descs[i], childDOM = desc.dom; + if (childDOM.parentNode == parentDOM) { + while (childDOM != dom) { dom = rm(dom); written = true; } + dom = dom.nextSibling; + } else { + written = true; + parentDOM.insertBefore(childDOM, dom); + } + if (desc instanceof MarkViewDesc) { + var pos = dom ? dom.previousSibling : parentDOM.lastChild; + renderDescs(desc.contentDOM, desc.children, view); + dom = pos ? pos.nextSibling : parentDOM.firstChild; + } + } + while (dom) { dom = rm(dom); written = true; } + if (written && view.trackWrites == parentDOM) { view.trackWrites = null; } + } + + function OuterDecoLevel(nodeName) { + if (nodeName) { this.nodeName = nodeName; } + } + OuterDecoLevel.prototype = Object.create(null); + + var noDeco = [new OuterDecoLevel]; + + function computeOuterDeco(outerDeco, node, needsWrap) { + if (outerDeco.length == 0) { return noDeco } + + var top = needsWrap ? noDeco[0] : new OuterDecoLevel, result = [top]; + + for (var i = 0; i < outerDeco.length; i++) { + var attrs = outerDeco[i].type.attrs, cur = top; + if (!attrs) { continue } + if (attrs.nodeName) + { result.push(cur = new OuterDecoLevel(attrs.nodeName)); } + + for (var name in attrs) { + var val = attrs[name]; + if (val == null) { continue } + if (needsWrap && result.length == 1) + { result.push(cur = top = new OuterDecoLevel(node.isInline ? "span" : "div")); } + if (name == "class") { cur.class = (cur.class ? cur.class + " " : "") + val; } + else if (name == "style") { cur.style = (cur.style ? cur.style + ";" : "") + val; } + else if (name != "nodeName") { cur[name] = val; } + } + } + + return result + } + + function patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) { + // Shortcut for trivial case + if (prevComputed == noDeco && curComputed == noDeco) { return nodeDOM } + + var curDOM = nodeDOM; + for (var i = 0; i < curComputed.length; i++) { + var deco = curComputed[i], prev = prevComputed[i]; + if (i) { + var parent = (void 0); + if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM && + (parent = curDOM.parentNode) && parent.tagName.toLowerCase() == deco.nodeName) { + curDOM = parent; + } else { + parent = document.createElement(deco.nodeName); + parent.pmIsDeco = true; + parent.appendChild(curDOM); + prev = noDeco[0]; + curDOM = parent; + } + } + patchAttributes(curDOM, prev || noDeco[0], deco); + } + return curDOM + } + + function patchAttributes(dom, prev, cur) { + for (var name in prev) + { if (name != "class" && name != "style" && name != "nodeName" && !(name in cur)) + { dom.removeAttribute(name); } } + for (var name$1 in cur) + { if (name$1 != "class" && name$1 != "style" && name$1 != "nodeName" && cur[name$1] != prev[name$1]) + { dom.setAttribute(name$1, cur[name$1]); } } + if (prev.class != cur.class) { + var prevList = prev.class ? prev.class.split(" ") : nothing; + var curList = cur.class ? cur.class.split(" ") : nothing; + for (var i = 0; i < prevList.length; i++) { if (curList.indexOf(prevList[i]) == -1) + { dom.classList.remove(prevList[i]); } } + for (var i$1 = 0; i$1 < curList.length; i$1++) { if (prevList.indexOf(curList[i$1]) == -1) + { dom.classList.add(curList[i$1]); } } + } + if (prev.style != cur.style) { + if (prev.style) { + var prop = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g, m; + while (m = prop.exec(prev.style)) + { dom.style.removeProperty(m[1]); } + } + if (cur.style) + { dom.style.cssText += cur.style; } + } + } + + function applyOuterDeco(dom, deco, node) { + return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1)) + } + + // : ([Decoration], [Decoration]) → bool + function sameOuterDeco(a, b) { + if (a.length != b.length) { return false } + for (var i = 0; i < a.length; i++) { if (!a[i].type.eq(b[i].type)) { return false } } + return true + } + + // Remove a DOM node and return its next sibling. + function rm(dom) { + var next = dom.nextSibling; + dom.parentNode.removeChild(dom); + return next + } + + // Helper class for incrementally updating a tree of mark descs and + // the widget and node descs inside of them. + var ViewTreeUpdater = function ViewTreeUpdater(top, lockedNode) { + this.top = top; + this.lock = lockedNode; + // Index into `this.top`'s child array, represents the current + // update position. + this.index = 0; + // When entering a mark, the current top and index are pushed + // onto this. + this.stack = []; + // Tracks whether anything was changed + this.changed = false; + + var pre = preMatch(top.node.content, top.children); + this.preMatched = pre.nodes; + this.preMatchOffset = pre.offset; + }; + + ViewTreeUpdater.prototype.getPreMatch = function getPreMatch (index) { + return index >= this.preMatchOffset ? this.preMatched[index - this.preMatchOffset] : null + }; + + // Destroy and remove the children between the given indices in + // `this.top`. + ViewTreeUpdater.prototype.destroyBetween = function destroyBetween (start, end) { + if (start == end) { return } + for (var i = start; i < end; i++) { this.top.children[i].destroy(); } + this.top.children.splice(start, end - start); + this.changed = true; + }; + + // Destroy all remaining children in `this.top`. + ViewTreeUpdater.prototype.destroyRest = function destroyRest () { + this.destroyBetween(this.index, this.top.children.length); + }; + + // : ([Mark], EditorView) + // Sync the current stack of mark descs with the given array of + // marks, reusing existing mark descs when possible. + ViewTreeUpdater.prototype.syncToMarks = function syncToMarks (marks, inline, view) { + var keep = 0, depth = this.stack.length >> 1; + var maxKeep = Math.min(depth, marks.length); + while (keep < maxKeep && + (keep == depth - 1 ? this.top : this.stack[(keep + 1) << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false) + { keep++; } + + while (keep < depth) { + this.destroyRest(); + this.top.dirty = NOT_DIRTY; + this.index = this.stack.pop(); + this.top = this.stack.pop(); + depth--; + } + while (depth < marks.length) { + this.stack.push(this.top, this.index + 1); + var found = -1; + for (var i = this.index; i < Math.min(this.index + 3, this.top.children.length); i++) { + if (this.top.children[i].matchesMark(marks[depth])) { found = i; break } + } + if (found > -1) { + if (found > this.index) { + this.changed = true; + this.destroyBetween(this.index, found); + } + this.top = this.top.children[this.index]; + } else { + var markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view); + this.top.children.splice(this.index, 0, markDesc); + this.top = markDesc; + this.changed = true; + } + this.index = 0; + depth++; + } + }; + + // : (Node, [Decoration], DecorationSet) → bool + // Try to find a node desc matching the given data. Skip over it and + // return true when successful. + ViewTreeUpdater.prototype.findNodeMatch = function findNodeMatch (node, outerDeco, innerDeco, index) { + var found = -1, preMatch = index < 0 ? undefined : this.getPreMatch(index), children = this.top.children; + if (preMatch && preMatch.matchesNode(node, outerDeco, innerDeco)) { + found = children.indexOf(preMatch); + } else { + for (var i = this.index, e = Math.min(children.length, i + 5); i < e; i++) { + var child = children[i]; + if (child.matchesNode(node, outerDeco, innerDeco) && this.preMatched.indexOf(child) < 0) { + found = i; + break + } + } + } + if (found < 0) { return false } + this.destroyBetween(this.index, found); + this.index++; + return true + }; + + // : (Node, [Decoration], DecorationSet, EditorView, Fragment, number) → bool + // Try to update the next node, if any, to the given data. Checks + // pre-matches to avoid overwriting nodes that could still be used. + ViewTreeUpdater.prototype.updateNextNode = function updateNextNode (node, outerDeco, innerDeco, view, index) { + for (var i = this.index; i < this.top.children.length; i++) { + var next = this.top.children[i]; + if (next instanceof NodeViewDesc) { + var preMatch = this.preMatched.indexOf(next); + if (preMatch > -1 && preMatch + this.preMatchOffset != index) { return false } + var nextDOM = next.dom; + + // Can't update if nextDOM is or contains this.lock, except if + // it's a text node whose content already matches the new text + // and whose decorations match the new ones. + var locked = this.lock && (nextDOM == this.lock || nextDOM.nodeType == 1 && nextDOM.contains(this.lock.parentNode)) && + !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text && + next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco)); + if (!locked && next.update(node, outerDeco, innerDeco, view)) { + this.destroyBetween(this.index, i); + if (next.dom != nextDOM) { this.changed = true; } + this.index++; + return true + } + break + } + } + return false + }; + + // : (Node, [Decoration], DecorationSet, EditorView) + // Insert the node as a newly created node desc. + ViewTreeUpdater.prototype.addNode = function addNode (node, outerDeco, innerDeco, view, pos) { + this.top.children.splice(this.index++, 0, NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos)); + this.changed = true; + }; + + ViewTreeUpdater.prototype.placeWidget = function placeWidget (widget, view, pos) { + var next = this.index < this.top.children.length ? this.top.children[this.index] : null; + if (next && next.matchesWidget(widget) && (widget == next.widget || !next.widget.type.toDOM.parentNode)) { + this.index++; + } else { + var desc = new WidgetViewDesc(this.top, widget, view, pos); + this.top.children.splice(this.index++, 0, desc); + this.changed = true; + } + }; + + // Make sure a textblock looks and behaves correctly in + // contentEditable. + ViewTreeUpdater.prototype.addTextblockHacks = function addTextblockHacks () { + var lastChild = this.top.children[this.index - 1]; + while (lastChild instanceof MarkViewDesc) { lastChild = lastChild.children[lastChild.children.length - 1]; } + + if (!lastChild || // Empty textblock + !(lastChild instanceof TextViewDesc) || + /\n$/.test(lastChild.node.text)) { + if (this.index < this.top.children.length && this.top.children[this.index].matchesHack()) { + this.index++; + } else { + var dom = document.createElement("br"); + this.top.children.splice(this.index++, 0, new BRHackViewDesc(this.top, nothing, dom, null)); + this.changed = true; + } + } + }; + + // : (Fragment, [ViewDesc]) → [ViewDesc] + // Iterate from the end of the fragment and array of descs to find + // directly matching ones, in order to avoid overeagerly reusing + // those for other nodes. Returns an array whose positions correspond + // to node positions in the fragment, and whose elements are either + // descs matched to the child at that index, or empty. + function preMatch(frag, descs) { + var result = [], end = frag.childCount; + for (var i = descs.length - 1; end > 0 && i >= 0; i--) { + var desc = descs[i], node = desc.node; + if (!node) { continue } + if (node != frag.child(end - 1)) { break } + result.push(desc); + --end; + } + return {nodes: result.reverse(), offset: end} + } + + function compareSide(a, b) { return a.type.side - b.type.side } + + // : (ViewDesc, DecorationSet, (Decoration, number), (Node, [Decoration], DecorationSet, number)) + // This function abstracts iterating over the nodes and decorations in + // a fragment. Calls `onNode` for each node, with its local and child + // decorations. Splits text nodes when there is a decoration starting + // or ending inside of them. Calls `onWidget` for each widget. + function iterDeco(parent, deco, onWidget, onNode) { + var locals = deco.locals(parent), offset = 0; + // Simple, cheap variant for when there are no local decorations + if (locals.length == 0) { + for (var i = 0; i < parent.childCount; i++) { + var child = parent.child(i); + onNode(child, locals, deco.forChild(offset, child), i); + offset += child.nodeSize; + } + return + } + + var decoIndex = 0, active = [], restNode = null; + for (var parentIndex = 0;;) { + if (decoIndex < locals.length && locals[decoIndex].to == offset) { + var widget = locals[decoIndex++], widgets = (void 0); + while (decoIndex < locals.length && locals[decoIndex].to == offset) + { (widgets || (widgets = [widget])).push(locals[decoIndex++]); } + if (widgets) { + widgets.sort(compareSide); + for (var i$1 = 0; i$1 < widgets.length; i$1++) { onWidget(widgets[i$1], parentIndex, !!restNode); } + } else { + onWidget(widget, parentIndex, !!restNode); + } + } + + var child$1 = (void 0), index = (void 0); + if (restNode) { + index = -1; + child$1 = restNode; + restNode = null; + } else if (parentIndex < parent.childCount) { + index = parentIndex; + child$1 = parent.child(parentIndex++); + } else { + break + } + + for (var i$2 = 0; i$2 < active.length; i$2++) { if (active[i$2].to <= offset) { active.splice(i$2--, 1); } } + while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset) + { active.push(locals[decoIndex++]); } + + var end = offset + child$1.nodeSize; + if (child$1.isText) { + var cutAt = end; + if (decoIndex < locals.length && locals[decoIndex].from < cutAt) { cutAt = locals[decoIndex].from; } + for (var i$3 = 0; i$3 < active.length; i$3++) { if (active[i$3].to < cutAt) { cutAt = active[i$3].to; } } + if (cutAt < end) { + restNode = child$1.cut(cutAt - offset); + child$1 = child$1.cut(0, cutAt - offset); + end = cutAt; + index = -1; + } + } + + var outerDeco = !active.length ? nothing + : child$1.isInline && !child$1.isLeaf ? active.filter(function (d) { return !d.inline; }) + : active.slice(); + onNode(child$1, outerDeco, deco.forChild(offset, child$1), index); + offset = end; + } + } + + // List markers in Mobile Safari will mysteriously disappear + // sometimes. This works around that. + function iosHacks(dom) { + if (dom.nodeName == "UL" || dom.nodeName == "OL") { + var oldCSS = dom.style.cssText; + dom.style.cssText = oldCSS + "; list-style: square !important"; + window.getComputedStyle(dom).listStyle; + dom.style.cssText = oldCSS; + } + } + + function nearbyTextNode(node, offset) { + for (;;) { + if (node.nodeType == 3) { return node } + if (node.nodeType == 1 && offset > 0) { + if (node.childNodes.length > offset && node.childNodes[offset].nodeType == 3) + { return node.childNodes[offset] } + node = node.childNodes[offset - 1]; + offset = nodeSize(node); + } else if (node.nodeType == 1 && offset < node.childNodes.length) { + node = node.childNodes[offset]; + offset = 0; + } else { + return null + } + } + } + + // Find a piece of text in an inline fragment, overlapping from-to + function findTextInFragment(frag, text, from, to) { + for (var i = 0, pos = 0; i < frag.childCount && pos <= to;) { + var child = frag.child(i++), childStart = pos; + pos += child.nodeSize; + if (!child.isText) { continue } + var str = child.text; + while (i < frag.childCount) { + var next = frag.child(i++); + pos += next.nodeSize; + if (!next.isText) { break } + str += next.text; + } + if (pos >= from) { + var found = str.lastIndexOf(text, to - childStart); + if (found >= 0 && found + text.length + childStart >= from) + { return childStart + found } + } + } + return -1 + } + + // Replace range from-to in an array of view descs with replacement + // (may be null to just delete). This goes very much against the grain + // of the rest of this code, which tends to create nodes with the + // right shape in one go, rather than messing with them after + // creation, but is necessary in the composition hack. + function replaceNodes(nodes, from, to, view, replacement) { + var result = []; + for (var i = 0, off = 0; i < nodes.length; i++) { + var child = nodes[i], start = off, end = off += child.size; + if (start >= to || end <= from) { + result.push(child); + } else { + if (start < from) { result.push(child.slice(0, from - start, view)); } + if (replacement) { + result.push(replacement); + replacement = null; + } + if (end > to) { result.push(child.slice(to - start, child.size, view)); } + } + } + return result + } + + function selectionFromDOM(view, origin) { + var domSel = view.root.getSelection(), doc = view.state.doc; + if (!domSel.focusNode) { return null } + var nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0; + var head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset); + if (head < 0) { return null } + var $head = doc.resolve(head), $anchor, selection; + if (selectionCollapsed(domSel)) { + $anchor = $head; + while (nearestDesc && !nearestDesc.node) { nearestDesc = nearestDesc.parent; } + if (nearestDesc && nearestDesc.node.isAtom && NodeSelection.isSelectable(nearestDesc.node) && nearestDesc.parent + && !(nearestDesc.node.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) { + var pos = nearestDesc.posBefore; + selection = new NodeSelection(head == pos ? $head : doc.resolve(pos)); + } + } else { + var anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset); + if (anchor < 0) { return null } + $anchor = doc.resolve(anchor); + } + + if (!selection) { + var bias = origin == "pointer" || (view.state.selection.head < $head.pos && !inWidget) ? 1 : -1; + selection = selectionBetween(view, $anchor, $head, bias); + } + return selection + } + + function selectionToDOM(view, force) { + var sel = view.state.selection; + syncNodeSelection(view, sel); + + if (view.editable ? !view.hasFocus() : + !(hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom))) { return } + + view.domObserver.disconnectSelection(); + + if (view.cursorWrapper) { + selectCursorWrapper(view); + } else { + var anchor = sel.anchor; + var head = sel.head; + var resetEditableFrom, resetEditableTo; + if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) { + if (!sel.$from.parent.inlineContent) + { resetEditableFrom = temporarilyEditableNear(view, sel.from); } + if (!sel.empty && !sel.$from.parent.inlineContent) + { resetEditableTo = temporarilyEditableNear(view, sel.to); } + } + view.docView.setSelection(anchor, head, view.root, force); + if (brokenSelectBetweenUneditable) { + if (resetEditableFrom) { resetEditable(resetEditableFrom); } + if (resetEditableTo) { resetEditable(resetEditableTo); } + } + if (sel.visible) { + view.dom.classList.remove("ProseMirror-hideselection"); + } else { + view.dom.classList.add("ProseMirror-hideselection"); + if ("onselectionchange" in document) { removeClassOnSelectionChange(view); } + } + } + + view.domObserver.setCurSelection(); + view.domObserver.connectSelection(); + } + + // Kludge to work around Webkit not allowing a selection to start/end + // between non-editable block nodes. We briefly make something + // editable, set the selection, then set it uneditable again. + + var brokenSelectBetweenUneditable = result.safari || result.chrome && result.chrome_version < 63; + + function temporarilyEditableNear(view, pos) { + var ref = view.docView.domFromPos(pos); + var node = ref.node; + var offset = ref.offset; + var after = offset < node.childNodes.length ? node.childNodes[offset] : null; + var before = offset ? node.childNodes[offset - 1] : null; + if (result.safari && after && after.contentEditable == "false") { return setEditable(after) } + if ((!after || after.contentEditable == "false") && (!before || before.contentEditable == "false")) { + if (after) { return setEditable(after) } + else if (before) { return setEditable(before) } + } + } + + function setEditable(element) { + element.contentEditable = "true"; + if (result.safari && element.draggable) { element.draggable = false; element.wasDraggable = true; } + return element + } + + function resetEditable(element) { + element.contentEditable = "false"; + if (element.wasDraggable) { element.draggable = true; element.wasDraggable = null; } + } + + function removeClassOnSelectionChange(view) { + var doc = view.dom.ownerDocument; + doc.removeEventListener("selectionchange", view.hideSelectionGuard); + var domSel = view.root.getSelection(); + var node = domSel.anchorNode, offset = domSel.anchorOffset; + doc.addEventListener("selectionchange", view.hideSelectionGuard = function () { + if (domSel.anchorNode != node || domSel.anchorOffset != offset) { + doc.removeEventListener("selectionchange", view.hideSelectionGuard); + view.dom.classList.remove("ProseMirror-hideselection"); + } + }); + } + + function selectCursorWrapper(view) { + var domSel = view.root.getSelection(), range = document.createRange(); + var node = view.cursorWrapper.dom, img = node.nodeName == "IMG"; + if (img) { range.setEnd(node.parentNode, domIndex(node) + 1); } + else { range.setEnd(node, 0); } + range.collapse(false); + domSel.removeAllRanges(); + domSel.addRange(range); + // Kludge to kill 'control selection' in IE11 when selecting an + // invisible cursor wrapper, since that would result in those weird + // resize handles and a selection that considers the absolutely + // positioned wrapper, rather than the root editable node, the + // focused element. + if (!img && !view.state.selection.visible && result.ie && result.ie_version <= 11) { + node.disabled = true; + node.disabled = false; + } + } + + function syncNodeSelection(view, sel) { + if (sel instanceof NodeSelection) { + var desc = view.docView.descAt(sel.from); + if (desc != view.lastSelectedViewDesc) { + clearNodeSelection(view); + if (desc) { desc.selectNode(); } + view.lastSelectedViewDesc = desc; + } + } else { + clearNodeSelection(view); + } + } + + // Clear all DOM statefulness of the last node selection. + function clearNodeSelection(view) { + if (view.lastSelectedViewDesc) { + if (view.lastSelectedViewDesc.parent) + { view.lastSelectedViewDesc.deselectNode(); } + view.lastSelectedViewDesc = null; + } + } + + function selectionBetween(view, $anchor, $head, bias) { + return view.someProp("createSelectionBetween", function (f) { return f(view, $anchor, $head); }) + || TextSelection.between($anchor, $head, bias) + } + + function hasFocusAndSelection(view) { + if (view.editable && view.root.activeElement != view.dom) { return false } + return hasSelection(view) + } + + function hasSelection(view) { + var sel = view.root.getSelection(); + if (!sel.anchorNode) { return false } + try { + // Firefox will raise 'permission denied' errors when accessing + // properties of `sel.anchorNode` when it's in a generated CSS + // element. + return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) && + (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode)) + } catch(_) { + return false + } + } + + function anchorInRightPlace(view) { + var anchorDOM = view.docView.domFromPos(view.state.selection.anchor); + var domSel = view.root.getSelection(); + return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset) + } + + function moveSelectionBlock(state, dir) { + var ref = state.selection; + var $anchor = ref.$anchor; + var $head = ref.$head; + var $side = dir > 0 ? $anchor.max($head) : $anchor.min($head); + var $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null; + return $start && Selection.findFrom($start, dir) + } + + function apply(view, sel) { + view.dispatch(view.state.tr.setSelection(sel).scrollIntoView()); + return true + } + + function selectHorizontally(view, dir, mods) { + var sel = view.state.selection; + if (sel instanceof TextSelection) { + if (!sel.empty || mods.indexOf("s") > -1) { + return false + } else if (view.endOfTextblock(dir > 0 ? "right" : "left")) { + var next = moveSelectionBlock(view.state, dir); + if (next && (next instanceof NodeSelection)) { return apply(view, next) } + return false + } else if (!(result.mac && mods.indexOf("m") > -1)) { + var $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc; + if (!node || node.isText) { return false } + var nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos; + if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM)) { return false } + if (NodeSelection.isSelectable(node)) { + return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head)) + } else if (result.webkit) { + // Chrome and Safari will introduce extra pointless cursor + // positions around inline uneditable nodes, so we have to + // take over and move the cursor past them (#937) + return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize))) + } else { + return false + } + } + } else if (sel instanceof NodeSelection && sel.node.isInline) { + return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from)) + } else { + var next$1 = moveSelectionBlock(view.state, dir); + if (next$1) { return apply(view, next$1) } + return false + } + } + + function nodeLen(node) { + return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length + } + + function isIgnorable(dom) { + var desc = dom.pmViewDesc; + return desc && desc.size == 0 && (dom.nextSibling || dom.nodeName != "BR") + } + + // Make sure the cursor isn't directly after one or more ignored + // nodes, which will confuse the browser's cursor motion logic. + function skipIgnoredNodesLeft(view) { + var sel = view.root.getSelection(); + var node = sel.focusNode, offset = sel.focusOffset; + if (!node) { return } + var moveNode, moveOffset, force = false; + // Gecko will do odd things when the selection is directly in front + // of a non-editable node, so in that case, move it into the next + // node if possible. Issue prosemirror/prosemirror#832. + if (result.gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset])) { force = true; } + for (;;) { + if (offset > 0) { + if (node.nodeType != 1) { + break + } else { + var before = node.childNodes[offset - 1]; + if (isIgnorable(before)) { + moveNode = node; + moveOffset = --offset; + } else if (before.nodeType == 3) { + node = before; + offset = node.nodeValue.length; + } else { break } + } + } else if (isBlockNode(node)) { + break + } else { + var prev = node.previousSibling; + while (prev && isIgnorable(prev)) { + moveNode = node.parentNode; + moveOffset = domIndex(prev); + prev = prev.previousSibling; + } + if (!prev) { + node = node.parentNode; + if (node == view.dom) { break } + offset = 0; + } else { + node = prev; + offset = nodeLen(node); + } + } + } + if (force) { setSelFocus(view, sel, node, offset); } + else if (moveNode) { setSelFocus(view, sel, moveNode, moveOffset); } + } + + // Make sure the cursor isn't directly before one or more ignored + // nodes. + function skipIgnoredNodesRight(view) { + var sel = view.root.getSelection(); + var node = sel.focusNode, offset = sel.focusOffset; + if (!node) { return } + var len = nodeLen(node); + var moveNode, moveOffset; + for (;;) { + if (offset < len) { + if (node.nodeType != 1) { break } + var after = node.childNodes[offset]; + if (isIgnorable(after)) { + moveNode = node; + moveOffset = ++offset; + } + else { break } + } else if (isBlockNode(node)) { + break + } else { + var next = node.nextSibling; + while (next && isIgnorable(next)) { + moveNode = next.parentNode; + moveOffset = domIndex(next) + 1; + next = next.nextSibling; + } + if (!next) { + node = node.parentNode; + if (node == view.dom) { break } + offset = len = 0; + } else { + node = next; + offset = 0; + len = nodeLen(node); + } + } + } + if (moveNode) { setSelFocus(view, sel, moveNode, moveOffset); } + } + + function isBlockNode(dom) { + var desc = dom.pmViewDesc; + return desc && desc.node && desc.node.isBlock + } + + function setSelFocus(view, sel, node, offset) { + if (selectionCollapsed(sel)) { + var range = document.createRange(); + range.setEnd(node, offset); + range.setStart(node, offset); + sel.removeAllRanges(); + sel.addRange(range); + } else if (sel.extend) { + sel.extend(node, offset); + } + view.domObserver.setCurSelection(); + var state = view.state; + // If no state update ends up happening, reset the selection. + setTimeout(function () { + if (view.state == state) { selectionToDOM(view); } + }, 50); + } + + // : (EditorState, number) + // Check whether vertical selection motion would involve node + // selections. If so, apply it (if not, the result is left to the + // browser) + function selectVertically(view, dir, mods) { + var sel = view.state.selection; + if (sel instanceof TextSelection && !sel.empty || mods.indexOf("s") > -1) { return false } + if (result.mac && mods.indexOf("m") > -1) { return false } + var $from = sel.$from; + var $to = sel.$to; + + if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? "up" : "down")) { + var next = moveSelectionBlock(view.state, dir); + if (next && (next instanceof NodeSelection)) + { return apply(view, next) } + } + if (!$from.parent.inlineContent) { + var beyond = Selection.findFrom(dir < 0 ? $from : $to, dir); + return beyond ? apply(view, beyond) : true + } + return false + } + + function stopNativeHorizontalDelete(view, dir) { + if (!(view.state.selection instanceof TextSelection)) { return true } + var ref = view.state.selection; + var $head = ref.$head; + var $anchor = ref.$anchor; + var empty = ref.empty; + if (!$head.sameParent($anchor)) { return true } + if (!empty) { return false } + if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) { return true } + var nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter); + if (nextNode && !nextNode.isText) { + var tr = view.state.tr; + if (dir < 0) { tr.delete($head.pos - nextNode.nodeSize, $head.pos); } + else { tr.delete($head.pos, $head.pos + nextNode.nodeSize); } + view.dispatch(tr); + return true + } + return false + } + + function switchEditable(view, node, state) { + view.domObserver.stop(); + node.contentEditable = state; + view.domObserver.start(); + } + + // Issue #867 / #1090 / https://bugs.chromium.org/p/chromium/issues/detail?id=903821 + // In which Safari (and at some point in the past, Chrome) does really + // wrong things when the down arrow is pressed when the cursor is + // directly at the start of a textblock and has an uneditable node + // after it + function safariDownArrowBug(view) { + if (!result.safari || view.state.selection.$head.parentOffset > 0) { return } + var ref = view.root.getSelection(); + var focusNode = ref.focusNode; + var focusOffset = ref.focusOffset; + if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 && + focusNode.firstChild && focusNode.firstChild.contentEditable == "false") { + var child = focusNode.firstChild; + switchEditable(view, child, true); + setTimeout(function () { return switchEditable(view, child, false); }, 20); + } + } + + // A backdrop key mapping used to make sure we always suppress keys + // that have a dangerous default effect, even if the commands they are + // bound to return false, and to make sure that cursor-motion keys + // find a cursor (as opposed to a node selection) when pressed. For + // cursor-motion keys, the code in the handlers also takes care of + // block selections. + + function getMods(event) { + var result = ""; + if (event.ctrlKey) { result += "c"; } + if (event.metaKey) { result += "m"; } + if (event.altKey) { result += "a"; } + if (event.shiftKey) { result += "s"; } + return result + } + + function captureKeyDown(view, event) { + var code = event.keyCode, mods = getMods(event); + if (code == 8 || (result.mac && code == 72 && mods == "c")) { // Backspace, Ctrl-h on Mac + return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodesLeft(view) + } else if (code == 46 || (result.mac && code == 68 && mods == "c")) { // Delete, Ctrl-d on Mac + return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodesRight(view) + } else if (code == 13 || code == 27) { // Enter, Esc + return true + } else if (code == 37) { // Left arrow + return selectHorizontally(view, -1, mods) || skipIgnoredNodesLeft(view) + } else if (code == 39) { // Right arrow + return selectHorizontally(view, 1, mods) || skipIgnoredNodesRight(view) + } else if (code == 38) { // Up arrow + return selectVertically(view, -1, mods) || skipIgnoredNodesLeft(view) + } else if (code == 40) { // Down arrow + return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodesRight(view) + } else if (mods == (result.mac ? "m" : "c") && + (code == 66 || code == 73 || code == 89 || code == 90)) { // Mod-[biyz] + return true + } + return false + } + + // Note that all referencing and parsing is done with the + // start-of-operation selection and document, since that's the one + // that the DOM represents. If any changes came in in the meantime, + // the modification is mapped over those before it is applied, in + // readDOMChange. + + function parseBetween(view, from_, to_) { + var ref = view.docView.parseRange(from_, to_); + var parent = ref.node; + var fromOffset = ref.fromOffset; + var toOffset = ref.toOffset; + var from = ref.from; + var to = ref.to; + + var domSel = view.root.getSelection(), find = null, anchor = domSel.anchorNode; + if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) { + find = [{node: anchor, offset: domSel.anchorOffset}]; + if (!selectionCollapsed(domSel)) + { find.push({node: domSel.focusNode, offset: domSel.focusOffset}); } + } + // Work around issue in Chrome where backspacing sometimes replaces + // the deleted content with a random BR node (issues #799, #831) + if (result.chrome && view.lastKeyCode === 8) { + for (var off = toOffset; off > fromOffset; off--) { + var node = parent.childNodes[off - 1], desc = node.pmViewDesc; + if (node.nodeType == "BR" && !desc) { toOffset = off; break } + if (!desc || desc.size) { break } + } + } + var startDoc = view.state.doc; + var parser = view.someProp("domParser") || DOMParser$1.fromSchema(view.state.schema); + var $from = startDoc.resolve(from); + + var sel = null, doc = parser.parse(parent, { + topNode: $from.parent, + topMatch: $from.parent.contentMatchAt($from.index()), + topOpen: true, + from: fromOffset, + to: toOffset, + preserveWhitespace: $from.parent.type.spec.code ? "full" : true, + editableContent: true, + findPositions: find, + ruleFromNode: ruleFromNode, + context: $from + }); + if (find && find[0].pos != null) { + var anchor$1 = find[0].pos, head = find[1] && find[1].pos; + if (head == null) { head = anchor$1; } + sel = {anchor: anchor$1 + from, head: head + from}; + } + return {doc: doc, sel: sel, from: from, to: to} + } + + function ruleFromNode(dom) { + var desc = dom.pmViewDesc; + if (desc) { + return desc.parseRule() + } else if (dom.nodeName == "BR" && dom.parentNode) { + // Safari replaces the list item or table cell with a BR + // directly in the list node (?!) if you delete the last + // character in a list item or table cell (#708, #862) + if (result.safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) { + var skip = document.createElement("div"); + skip.appendChild(document.createElement("li")); + return {skip: skip} + } else if (dom.parentNode.lastChild == dom || result.safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) { + return {ignore: true} + } + } else if (dom.nodeName == "IMG" && dom.getAttribute("mark-placeholder")) { + return {ignore: true} + } + } + + function readDOMChange(view, from, to, typeOver, addedNodes) { + if (from < 0) { + var origin = view.lastSelectionTime > Date.now() - 50 ? view.lastSelectionOrigin : null; + var newSel = selectionFromDOM(view, origin); + if (newSel && !view.state.selection.eq(newSel)) { + var tr$1 = view.state.tr.setSelection(newSel); + if (origin == "pointer") { tr$1.setMeta("pointer", true); } + else if (origin == "key") { tr$1.scrollIntoView(); } + view.dispatch(tr$1); + } + return + } + + var $before = view.state.doc.resolve(from); + var shared = $before.sharedDepth(to); + from = $before.before(shared + 1); + to = view.state.doc.resolve(to).after(shared + 1); + + var sel = view.state.selection; + var parse = parseBetween(view, from, to); + + var doc = view.state.doc, compare = doc.slice(parse.from, parse.to); + var preferredPos, preferredSide; + // Prefer anchoring to end when Backspace is pressed + if (view.lastKeyCode === 8 && Date.now() - 100 < view.lastKeyCodeTime) { + preferredPos = view.state.selection.to; + preferredSide = "end"; + } else { + preferredPos = view.state.selection.from; + preferredSide = "start"; + } + view.lastKeyCode = null; + + var change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide); + if (!change) { + if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) && + !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) { + change = {start: sel.from, endA: sel.to, endB: sel.to}; + } else { + if (parse.sel) { + var sel$1 = resolveSelection(view, view.state.doc, parse.sel); + if (sel$1 && !sel$1.eq(view.state.selection)) { view.dispatch(view.state.tr.setSelection(sel$1)); } + } + return + } + } + view.domChangeCount++; + // Handle the case where overwriting a selection by typing matches + // the start or end of the selected content, creating a change + // that's smaller than what was actually overwritten. + if (view.state.selection.from < view.state.selection.to && + change.start == change.endB && + view.state.selection instanceof TextSelection) { + if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2) { + change.start = view.state.selection.from; + } else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2) { + change.endB += (view.state.selection.to - change.endA); + change.endA = view.state.selection.to; + } + } + + // IE11 will insert a non-breaking space _ahead_ of the space after + // the cursor space when adding a space before another space. When + // that happened, adjust the change to cover the space instead. + if (result.ie && result.ie_version <= 11 && change.endB == change.start + 1 && + change.endA == change.start && change.start > parse.from && + parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == " \u00a0") { + change.start--; + change.endA--; + change.endB--; + } + + var $from = parse.doc.resolveNoCache(change.start - parse.from); + var $to = parse.doc.resolveNoCache(change.endB - parse.from); + var inlineChange = $from.sameParent($to) && $from.parent.inlineContent; + var nextSel; + // If this looks like the effect of pressing Enter (or was recorded + // as being an iOS enter press), just dispatch an Enter key instead. + if (((result.ios && view.lastIOSEnter > Date.now() - 225 && + (!inlineChange || addedNodes.some(function (n) { return n.nodeName == "DIV" || n.nodeName == "P"; }))) || + (!inlineChange && $from.pos < parse.doc.content.size && + (nextSel = Selection.findFrom(parse.doc.resolve($from.pos + 1), 1, true)) && + nextSel.head == $to.pos)) && + view.someProp("handleKeyDown", function (f) { return f(view, keyEvent(13, "Enter")); })) { + view.lastIOSEnter = 0; + return + } + // Same for backspace + if (view.state.selection.anchor > change.start && + looksLikeJoin(doc, change.start, change.endA, $from, $to) && + view.someProp("handleKeyDown", function (f) { return f(view, keyEvent(8, "Backspace")); })) { + if (result.android && result.chrome) { view.domObserver.suppressSelectionUpdates(); } // #820 + return + } + + // This tries to detect Android virtual keyboard + // enter-and-pick-suggestion action. That sometimes (see issue + // #1059) first fires a DOM mutation, before moving the selection to + // the newly created block. And then, because ProseMirror cleans up + // the DOM selection, it gives up moving the selection entirely, + // leaving the cursor in the wrong place. When that happens, we drop + // the new paragraph from the initial change, and fire a simulated + // enter key afterwards. + if (result.android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth && + parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) { + change.endB -= 2; + $to = parse.doc.resolveNoCache(change.endB - parse.from); + setTimeout(function () { + view.someProp("handleKeyDown", function (f) { return f(view, keyEvent(13, "Enter")); }); + }, 20); + } + + var chFrom = change.start, chTo = change.endA; + + var tr, storedMarks, markChange, $from1; + if (inlineChange) { + if ($from.pos == $to.pos) { // Deletion + // IE11 sometimes weirdly moves the DOM selection around after + // backspacing out the first element in a textblock + if (result.ie && result.ie_version <= 11 && $from.parentOffset == 0) { + view.domObserver.suppressSelectionUpdates(); + setTimeout(function () { return selectionToDOM(view); }, 20); + } + tr = view.state.tr.delete(chFrom, chTo); + storedMarks = doc.resolve(change.start).marksAcross(doc.resolve(change.endA)); + } else if ( // Adding or removing a mark + change.endA == change.endB && ($from1 = doc.resolve(change.start)) && + (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), + $from1.parent.content.cut($from1.parentOffset, change.endA - $from1.start()))) + ) { + tr = view.state.tr; + if (markChange.type == "add") { tr.addMark(chFrom, chTo, markChange.mark); } + else { tr.removeMark(chFrom, chTo, markChange.mark); } + } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) { + // Both positions in the same text node -- simply insert text + var text = $from.parent.textBetween($from.parentOffset, $to.parentOffset); + if (view.someProp("handleTextInput", function (f) { return f(view, chFrom, chTo, text); })) { return } + tr = view.state.tr.insertText(text, chFrom, chTo); + } + } + + if (!tr) + { tr = view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from)); } + if (parse.sel) { + var sel$2 = resolveSelection(view, tr.doc, parse.sel); + // Chrome Android will sometimes, during composition, report the + // selection in the wrong place. If it looks like that is + // happening, don't update the selection. + // Edge just doesn't move the cursor forward when you start typing + // in an empty block or between br nodes. + if (sel$2 && !(result.chrome && result.android && view.composing && sel$2.empty && + (sel$2.head == chFrom || sel$2.head == tr.mapping.map(chTo) - 1) || + result.ie && sel$2.empty && sel$2.head == chFrom)) + { tr.setSelection(sel$2); } + } + if (storedMarks) { tr.ensureMarks(storedMarks); } + view.dispatch(tr.scrollIntoView()); + } + + function resolveSelection(view, doc, parsedSel) { + if (Math.max(parsedSel.anchor, parsedSel.head) > doc.content.size) { return null } + return selectionBetween(view, doc.resolve(parsedSel.anchor), doc.resolve(parsedSel.head)) + } + + // : (Fragment, Fragment) → ?{mark: Mark, type: string} + // Given two same-length, non-empty fragments of inline content, + // determine whether the first could be created from the second by + // removing or adding a single mark type. + function isMarkChange(cur, prev) { + var curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks; + var added = curMarks, removed = prevMarks, type, mark, update; + for (var i = 0; i < prevMarks.length; i++) { added = prevMarks[i].removeFromSet(added); } + for (var i$1 = 0; i$1 < curMarks.length; i$1++) { removed = curMarks[i$1].removeFromSet(removed); } + if (added.length == 1 && removed.length == 0) { + mark = added[0]; + type = "add"; + update = function (node) { return node.mark(mark.addToSet(node.marks)); }; + } else if (added.length == 0 && removed.length == 1) { + mark = removed[0]; + type = "remove"; + update = function (node) { return node.mark(mark.removeFromSet(node.marks)); }; + } else { + return null + } + var updated = []; + for (var i$2 = 0; i$2 < prev.childCount; i$2++) { updated.push(update(prev.child(i$2))); } + if (Fragment.from(updated).eq(cur)) { return {mark: mark, type: type} } + } + + function looksLikeJoin(old, start, end, $newStart, $newEnd) { + if (!$newStart.parent.isTextblock || + // The content must have shrunk + end - start <= $newEnd.pos - $newStart.pos || + // newEnd must point directly at or after the end of the block that newStart points into + skipClosingAndOpening($newStart, true, false) < $newEnd.pos) + { return false } + + var $start = old.resolve(start); + // Start must be at the end of a block + if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock) + { return false } + var $next = old.resolve(skipClosingAndOpening($start, true, true)); + // The next textblock must start before end and end near it + if (!$next.parent.isTextblock || $next.pos > end || + skipClosingAndOpening($next, true, false) < end) + { return false } + + // The fragments after the join point must match + return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content) + } + + function skipClosingAndOpening($pos, fromEnd, mayOpen) { + var depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos; + while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) { + depth--; + end++; + fromEnd = false; + } + if (mayOpen) { + var next = $pos.node(depth).maybeChild($pos.indexAfter(depth)); + while (next && !next.isLeaf) { + next = next.firstChild; + end++; + } + } + return end + } + + function findDiff(a, b, pos, preferredPos, preferredSide) { + var start = a.findDiffStart(b, pos); + if (start == null) { return null } + var ref = a.findDiffEnd(b, pos + a.size, pos + b.size); + var endA = ref.a; + var endB = ref.b; + if (preferredSide == "end") { + var adjust = Math.max(0, start - Math.min(endA, endB)); + preferredPos -= endA + adjust - start; + } + if (endA < start && a.size < b.size) { + var move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0; + start -= move; + endB = start + (endB - endA); + endA = start; + } else if (endB < start) { + var move$1 = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0; + start -= move$1; + endA = start + (endA - endB); + endB = start; + } + return {start: start, endA: endA, endB: endB} + } + + function serializeForClipboard(view, slice) { + var context = []; + var content = slice.content; + var openStart = slice.openStart; + var openEnd = slice.openEnd; + while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) { + openStart--; + openEnd--; + var node = content.firstChild; + context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null); + content = node.content; + } + + var serializer = view.someProp("clipboardSerializer") || DOMSerializer.fromSchema(view.state.schema); + var doc = detachedDoc(), wrap = doc.createElement("div"); + wrap.appendChild(serializer.serializeFragment(content, {document: doc})); + + var firstChild = wrap.firstChild, needsWrap; + while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) { + for (var i = needsWrap.length - 1; i >= 0; i--) { + var wrapper = doc.createElement(needsWrap[i]); + while (wrap.firstChild) { wrapper.appendChild(wrap.firstChild); } + wrap.appendChild(wrapper); + } + firstChild = wrap.firstChild; + } + + if (firstChild && firstChild.nodeType == 1) + { firstChild.setAttribute("data-pm-slice", (openStart + " " + openEnd + " " + (JSON.stringify(context)))); } + + var text = view.someProp("clipboardTextSerializer", function (f) { return f(slice); }) || + slice.content.textBetween(0, slice.content.size, "\n\n"); + + return {dom: wrap, text: text} + } + + // : (EditorView, string, string, ?bool, ResolvedPos) → ?Slice + // Read a slice of content from the clipboard (or drop data). + function parseFromClipboard(view, text, html, plainText, $context) { + var dom, inCode = $context.parent.type.spec.code, slice; + if (!html && !text) { return null } + var asText = text && (plainText || inCode || !html); + if (asText) { + view.someProp("transformPastedText", function (f) { text = f(text, inCode || plainText); }); + if (inCode) { return new Slice(Fragment.from(view.state.schema.text(text)), 0, 0) } + var parsed = view.someProp("clipboardTextParser", function (f) { return f(text, $context, plainText); }); + if (parsed) { + slice = parsed; + } else { + dom = document.createElement("div"); + text.trim().split(/(?:\r\n?|\n)+/).forEach(function (block) { + dom.appendChild(document.createElement("p")).textContent = block; + }); + } + } else { + view.someProp("transformPastedHTML", function (f) { html = f(html); }); + dom = readHTML(html); + } + + var contextNode = dom && dom.querySelector("[data-pm-slice]"); + var sliceData = contextNode && /^(\d+) (\d+) (.*)/.exec(contextNode.getAttribute("data-pm-slice")); + if (!slice) { + var parser = view.someProp("clipboardParser") || view.someProp("domParser") || DOMParser$1.fromSchema(view.state.schema); + slice = parser.parseSlice(dom, {preserveWhitespace: !!(asText || sliceData), context: $context}); + } + if (sliceData) + { slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[3]); } + else // HTML wasn't created by ProseMirror. Make sure top-level siblings are coherent + { slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), false); } + + view.someProp("transformPasted", function (f) { slice = f(slice); }); + return slice + } + + // Takes a slice parsed with parseSlice, which means there hasn't been + // any content-expression checking done on the top nodes, tries to + // find a parent node in the current context that might fit the nodes, + // and if successful, rebuilds the slice so that it fits into that parent. + // + // This addresses the problem that Transform.replace expects a + // coherent slice, and will fail to place a set of siblings that don't + // fit anywhere in the schema. + function normalizeSiblings(fragment, $context) { + if (fragment.childCount < 2) { return fragment } + var loop = function ( d ) { + var parent = $context.node(d); + var match = parent.contentMatchAt($context.index(d)); + var lastWrap = (void 0), result = []; + fragment.forEach(function (node) { + if (!result) { return } + var wrap = match.findWrapping(node.type), inLast; + if (!wrap) { return result = null } + if (inLast = result.length && lastWrap.length && addToSibling(wrap, lastWrap, node, result[result.length - 1], 0)) { + result[result.length - 1] = inLast; + } else { + if (result.length) { result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length); } + var wrapped = withWrappers(node, wrap); + result.push(wrapped); + match = match.matchType(wrapped.type, wrapped.attrs); + lastWrap = wrap; + } + }); + if (result) { return { v: Fragment.from(result) } } + }; + + for (var d = $context.depth; d >= 0; d--) { + var returned = loop( d ); + + if ( returned ) return returned.v; + } + return fragment + } + + function withWrappers(node, wrap, from) { + if ( from === void 0 ) from = 0; + + for (var i = wrap.length - 1; i >= from; i--) + { node = wrap[i].create(null, Fragment.from(node)); } + return node + } + + // Used to group adjacent nodes wrapped in similar parents by + // normalizeSiblings into the same parent node + function addToSibling(wrap, lastWrap, node, sibling, depth) { + if (depth < wrap.length && depth < lastWrap.length && wrap[depth] == lastWrap[depth]) { + var inner = addToSibling(wrap, lastWrap, node, sibling.lastChild, depth + 1); + if (inner) { return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner)) } + var match = sibling.contentMatchAt(sibling.childCount); + if (match.matchType(depth == wrap.length - 1 ? node.type : wrap[depth + 1])) + { return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap, depth + 1)))) } + } + } + + function closeRight(node, depth) { + if (depth == 0) { return node } + var fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1)); + var fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true); + return node.copy(fragment.append(fill)) + } + + function closeRange(fragment, side, from, to, depth, openEnd) { + var node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content; + if (depth < to - 1) { inner = closeRange(inner, side, from, to, depth + 1, openEnd); } + if (depth >= from) + { inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, fragment.childCount > 1 || openEnd <= depth).append(inner) + : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true)); } + return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner)) + } + + function closeSlice(slice, openStart, openEnd) { + if (openStart < slice.openStart) + { slice = new Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd); } + if (openEnd < slice.openEnd) + { slice = new Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd); } + return slice + } + + // Trick from jQuery -- some elements must be wrapped in other + // elements for innerHTML to work. I.e. if you do `div.innerHTML = + // ".."` the table cells are ignored. + var wrapMap = { + thead: ["table"], + tbody: ["table"], + tfoot: ["table"], + caption: ["table"], + colgroup: ["table"], + col: ["table", "colgroup"], + tr: ["table", "tbody"], + td: ["table", "tbody", "tr"], + th: ["table", "tbody", "tr"] + }; + + var _detachedDoc = null; + function detachedDoc() { + return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument("title")) + } + + function readHTML(html) { + var metas = /(\s*]*>)*/.exec(html); + if (metas) { html = html.slice(metas[0].length); } + var elt = detachedDoc().createElement("div"); + var firstTag = /(?:]*>)*<([a-z][^>\s]+)/i.exec(html), wrap, depth = 0; + if (wrap = firstTag && wrapMap[firstTag[1].toLowerCase()]) { + html = wrap.map(function (n) { return "<" + n + ">"; }).join("") + html + wrap.map(function (n) { return ""; }).reverse().join(""); + depth = wrap.length; + } + elt.innerHTML = html; + for (var i = 0; i < depth; i++) { elt = elt.firstChild; } + return elt + } + + function addContext(slice, context) { + if (!slice.size) { return slice } + var schema = slice.content.firstChild.type.schema, array; + try { array = JSON.parse(context); } + catch(e) { return slice } + var content = slice.content; + var openStart = slice.openStart; + var openEnd = slice.openEnd; + for (var i = array.length - 2; i >= 0; i -= 2) { + var type = schema.nodes[array[i]]; + if (!type || type.hasRequiredAttrs()) { break } + content = Fragment.from(type.create(array[i + 1], content)); + openStart++; openEnd++; + } + return new Slice(content, openStart, openEnd) + } + + var observeOptions = { + childList: true, + characterData: true, + characterDataOldValue: true, + attributes: true, + attributeOldValue: true, + subtree: true + }; + // IE11 has very broken mutation observers, so we also listen to DOMCharacterDataModified + var useCharData = result.ie && result.ie_version <= 11; + + var SelectionState = function SelectionState() { + this.anchorNode = this.anchorOffset = this.focusNode = this.focusOffset = null; + }; + + SelectionState.prototype.set = function set (sel) { + this.anchorNode = sel.anchorNode; this.anchorOffset = sel.anchorOffset; + this.focusNode = sel.focusNode; this.focusOffset = sel.focusOffset; + }; + + SelectionState.prototype.eq = function eq (sel) { + return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset && + sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset + }; + + var DOMObserver = function DOMObserver(view, handleDOMChange) { + var this$1 = this; + + this.view = view; + this.handleDOMChange = handleDOMChange; + this.queue = []; + this.flushingSoon = -1; + this.observer = window.MutationObserver && + new window.MutationObserver(function (mutations) { + for (var i = 0; i < mutations.length; i++) { this$1.queue.push(mutations[i]); } + // IE11 will sometimes (on backspacing out a single character + // text node after a BR node) call the observer callback + // before actually updating the DOM, which will cause + // ProseMirror to miss the change (see #930) + if (result.ie && result.ie_version <= 11 && mutations.some( + function (m) { return m.type == "childList" && m.removedNodes.length || + m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length; })) + { this$1.flushSoon(); } + else + { this$1.flush(); } + }); + this.currentSelection = new SelectionState; + if (useCharData) { + this.onCharData = function (e) { + this$1.queue.push({target: e.target, type: "characterData", oldValue: e.prevValue}); + this$1.flushSoon(); + }; + } + this.onSelectionChange = this.onSelectionChange.bind(this); + this.suppressingSelectionUpdates = false; + }; + + DOMObserver.prototype.flushSoon = function flushSoon () { + var this$1 = this; + + if (this.flushingSoon < 0) + { this.flushingSoon = window.setTimeout(function () { this$1.flushingSoon = -1; this$1.flush(); }, 20); } + }; + + DOMObserver.prototype.forceFlush = function forceFlush () { + if (this.flushingSoon > -1) { + window.clearTimeout(this.flushingSoon); + this.flushingSoon = -1; + this.flush(); + } + }; + + DOMObserver.prototype.start = function start () { + if (this.observer) + { this.observer.observe(this.view.dom, observeOptions); } + if (useCharData) + { this.view.dom.addEventListener("DOMCharacterDataModified", this.onCharData); } + this.connectSelection(); + }; + + DOMObserver.prototype.stop = function stop () { + var this$1 = this; + + if (this.observer) { + var take = this.observer.takeRecords(); + if (take.length) { + for (var i = 0; i < take.length; i++) { this.queue.push(take[i]); } + window.setTimeout(function () { return this$1.flush(); }, 20); + } + this.observer.disconnect(); + } + if (useCharData) { this.view.dom.removeEventListener("DOMCharacterDataModified", this.onCharData); } + this.disconnectSelection(); + }; + + DOMObserver.prototype.connectSelection = function connectSelection () { + this.view.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange); + }; + + DOMObserver.prototype.disconnectSelection = function disconnectSelection () { + this.view.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange); + }; + + DOMObserver.prototype.suppressSelectionUpdates = function suppressSelectionUpdates () { + var this$1 = this; + + this.suppressingSelectionUpdates = true; + setTimeout(function () { return this$1.suppressingSelectionUpdates = false; }, 50); + }; + + DOMObserver.prototype.onSelectionChange = function onSelectionChange () { + if (!hasFocusAndSelection(this.view)) { return } + if (this.suppressingSelectionUpdates) { return selectionToDOM(this.view) } + // Deletions on IE11 fire their events in the wrong order, giving + // us a selection change event before the DOM changes are + // reported. + if (result.ie && result.ie_version <= 11 && !this.view.state.selection.empty) { + var sel = this.view.root.getSelection(); + // Selection.isCollapsed isn't reliable on IE + if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) + { return this.flushSoon() } + } + this.flush(); + }; + + DOMObserver.prototype.setCurSelection = function setCurSelection () { + this.currentSelection.set(this.view.root.getSelection()); + }; + + DOMObserver.prototype.ignoreSelectionChange = function ignoreSelectionChange (sel) { + if (sel.rangeCount == 0) { return true } + var container = sel.getRangeAt(0).commonAncestorContainer; + var desc = this.view.docView.nearestDesc(container); + if (desc && desc.ignoreMutation({type: "selection", target: container.nodeType == 3 ? container.parentNode : container})) { + this.setCurSelection(); + return true + } + }; + + DOMObserver.prototype.flush = function flush () { + if (!this.view.docView || this.flushingSoon > -1) { return } + var mutations = this.observer ? this.observer.takeRecords() : []; + if (this.queue.length) { + mutations = this.queue.concat(mutations); + this.queue.length = 0; + } + + var sel = this.view.root.getSelection(); + var newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasSelection(this.view) && !this.ignoreSelectionChange(sel); + + var from = -1, to = -1, typeOver = false, added = []; + if (this.view.editable) { + for (var i = 0; i < mutations.length; i++) { + var result$1 = this.registerMutation(mutations[i], added); + if (result$1) { + from = from < 0 ? result$1.from : Math.min(result$1.from, from); + to = to < 0 ? result$1.to : Math.max(result$1.to, to); + if (result$1.typeOver) { typeOver = true; } + } + } + } + + if (result.gecko && added.length > 1) { + var brs = added.filter(function (n) { return n.nodeName == "BR"; }); + if (brs.length == 2) { + var a = brs[0]; + var b = brs[1]; + if (a.parentNode && a.parentNode.parentNode == b.parentNode) { b.remove(); } + else { a.remove(); } + } + } + + if (from > -1 || newSel) { + if (from > -1) { + this.view.docView.markDirty(from, to); + checkCSS(this.view); + } + this.handleDOMChange(from, to, typeOver, added); + if (this.view.docView.dirty) { this.view.updateState(this.view.state); } + else if (!this.currentSelection.eq(sel)) { selectionToDOM(this.view); } + } + }; + + DOMObserver.prototype.registerMutation = function registerMutation (mut, added) { + // Ignore mutations inside nodes that were already noted as inserted + if (added.indexOf(mut.target) > -1) { return null } + var desc = this.view.docView.nearestDesc(mut.target); + if (mut.type == "attributes" && + (desc == this.view.docView || mut.attributeName == "contenteditable" || + // Firefox sometimes fires spurious events for null/empty styles + (mut.attributeName == "style" && !mut.oldValue && !mut.target.getAttribute("style")))) + { return null } + if (!desc || desc.ignoreMutation(mut)) { return null } + + if (mut.type == "childList") { + var prev = mut.previousSibling, next = mut.nextSibling; + if (result.ie && result.ie_version <= 11 && mut.addedNodes.length) { + // IE11 gives us incorrect next/prev siblings for some + // insertions, so if there are added nodes, recompute those + for (var i = 0; i < mut.addedNodes.length; i++) { + var ref = mut.addedNodes[i]; + var previousSibling = ref.previousSibling; + var nextSibling = ref.nextSibling; + if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0) { prev = previousSibling; } + if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0) { next = nextSibling; } + } + } + var fromOffset = prev && prev.parentNode == mut.target + ? domIndex(prev) + 1 : 0; + var from = desc.localPosFromDOM(mut.target, fromOffset, -1); + var toOffset = next && next.parentNode == mut.target + ? domIndex(next) : mut.target.childNodes.length; + for (var i$1 = 0; i$1 < mut.addedNodes.length; i$1++) { added.push(mut.addedNodes[i$1]); } + var to = desc.localPosFromDOM(mut.target, toOffset, 1); + return {from: from, to: to} + } else if (mut.type == "attributes") { + return {from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border} + } else { // "characterData" + return { + from: desc.posAtStart, + to: desc.posAtEnd, + // An event was generated for a text change that didn't change + // any text. Mark the dom change to fall back to assuming the + // selection was typed over with an identical value if it can't + // find another change. + typeOver: mut.target.nodeValue == mut.oldValue + } + } + }; + + var cssChecked = false; + + function checkCSS(view) { + if (cssChecked) { return } + cssChecked = true; + if (getComputedStyle(view.dom).whiteSpace == "normal") + { console["warn"]("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package."); } + } + + // A collection of DOM events that occur within the editor, and callback functions + // to invoke when the event fires. + var handlers = {}, editHandlers = {}; + + function initInput(view) { + view.shiftKey = false; + view.mouseDown = null; + view.lastKeyCode = null; + view.lastKeyCodeTime = 0; + view.lastClick = {time: 0, x: 0, y: 0, type: ""}; + view.lastSelectionOrigin = null; + view.lastSelectionTime = 0; + + view.lastIOSEnter = 0; + view.lastIOSEnterFallbackTimeout = null; + + view.composing = false; + view.composingTimeout = null; + view.compositionNodes = []; + view.compositionEndedAt = -2e8; + + view.domObserver = new DOMObserver(view, function (from, to, typeOver, added) { return readDOMChange(view, from, to, typeOver, added); }); + view.domObserver.start(); + // Used by hacks like the beforeinput handler to check whether anything happened in the DOM + view.domChangeCount = 0; + + view.eventHandlers = Object.create(null); + var loop = function ( event ) { + var handler = handlers[event]; + view.dom.addEventListener(event, view.eventHandlers[event] = function (event) { + if (eventBelongsToView(view, event) && !runCustomHandler(view, event) && + (view.editable || !(event.type in editHandlers))) + { handler(view, event); } + }); + }; + + for (var event in handlers) loop( event ); + // On Safari, for reasons beyond my understanding, adding an input + // event handler makes an issue where the composition vanishes when + // you press enter go away. + if (result.safari) { view.dom.addEventListener("input", function () { return null; }); } + + ensureListeners(view); + } + + function setSelectionOrigin(view, origin) { + view.lastSelectionOrigin = origin; + view.lastSelectionTime = Date.now(); + } + + function destroyInput(view) { + view.domObserver.stop(); + for (var type in view.eventHandlers) + { view.dom.removeEventListener(type, view.eventHandlers[type]); } + clearTimeout(view.composingTimeout); + clearTimeout(view.lastIOSEnterFallbackTimeout); + } + + function ensureListeners(view) { + view.someProp("handleDOMEvents", function (currentHandlers) { + for (var type in currentHandlers) { if (!view.eventHandlers[type]) + { view.dom.addEventListener(type, view.eventHandlers[type] = function (event) { return runCustomHandler(view, event); }); } } + }); + } + + function runCustomHandler(view, event) { + return view.someProp("handleDOMEvents", function (handlers) { + var handler = handlers[event.type]; + return handler ? handler(view, event) || event.defaultPrevented : false + }) + } + + function eventBelongsToView(view, event) { + if (!event.bubbles) { return true } + if (event.defaultPrevented) { return false } + for (var node = event.target; node != view.dom; node = node.parentNode) + { if (!node || node.nodeType == 11 || + (node.pmViewDesc && node.pmViewDesc.stopEvent(event))) + { return false } } + return true + } + + function dispatchEvent(view, event) { + if (!runCustomHandler(view, event) && handlers[event.type] && + (view.editable || !(event.type in editHandlers))) + { handlers[event.type](view, event); } + } + + editHandlers.keydown = function (view, event) { + view.shiftKey = event.keyCode == 16 || event.shiftKey; + if (inOrNearComposition(view, event)) { return } + view.domObserver.forceFlush(); + view.lastKeyCode = event.keyCode; + view.lastKeyCodeTime = Date.now(); + // On iOS, if we preventDefault enter key presses, the virtual + // keyboard gets confused. So the hack here is to set a flag that + // makes the DOM change code recognize that what just happens should + // be replaced by whatever the Enter key handlers do. + if (result.ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) { + var now = Date.now(); + view.lastIOSEnter = now; + view.lastIOSEnterFallbackTimeout = setTimeout(function () { + if (view.lastIOSEnter == now) { + view.someProp("handleKeyDown", function (f) { return f(view, keyEvent(13, "Enter")); }); + view.lastIOSEnter = 0; + } + }, 200); + } else if (view.someProp("handleKeyDown", function (f) { return f(view, event); }) || captureKeyDown(view, event)) { + event.preventDefault(); + } else { + setSelectionOrigin(view, "key"); + } + }; + + editHandlers.keyup = function (view, e) { + if (e.keyCode == 16) { view.shiftKey = false; } + }; + + editHandlers.keypress = function (view, event) { + if (inOrNearComposition(view, event) || !event.charCode || + event.ctrlKey && !event.altKey || result.mac && event.metaKey) { return } + + if (view.someProp("handleKeyPress", function (f) { return f(view, event); })) { + event.preventDefault(); + return + } + + var sel = view.state.selection; + if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) { + var text = String.fromCharCode(event.charCode); + if (!view.someProp("handleTextInput", function (f) { return f(view, sel.$from.pos, sel.$to.pos, text); })) + { view.dispatch(view.state.tr.insertText(text).scrollIntoView()); } + event.preventDefault(); + } + }; + + function eventCoords(event) { return {left: event.clientX, top: event.clientY} } + + function isNear(event, click) { + var dx = click.x - event.clientX, dy = click.y - event.clientY; + return dx * dx + dy * dy < 100 + } + + function runHandlerOnContext(view, propName, pos, inside, event) { + if (inside == -1) { return false } + var $pos = view.state.doc.resolve(inside); + var loop = function ( i ) { + if (view.someProp(propName, function (f) { return i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true) + : f(view, pos, $pos.node(i), $pos.before(i), event, false); })) + { return { v: true } } + }; + + for (var i = $pos.depth + 1; i > 0; i--) { + var returned = loop( i ); + + if ( returned ) return returned.v; + } + return false + } + + function updateSelection(view, selection, origin) { + if (!view.focused) { view.focus(); } + var tr = view.state.tr.setSelection(selection); + if (origin == "pointer") { tr.setMeta("pointer", true); } + view.dispatch(tr); + } + + function selectClickedLeaf(view, inside) { + if (inside == -1) { return false } + var $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter; + if (node && node.isAtom && NodeSelection.isSelectable(node)) { + updateSelection(view, new NodeSelection($pos), "pointer"); + return true + } + return false + } + + function selectClickedNode(view, inside) { + if (inside == -1) { return false } + var sel = view.state.selection, selectedNode, selectAt; + if (sel instanceof NodeSelection) { selectedNode = sel.node; } + + var $pos = view.state.doc.resolve(inside); + for (var i = $pos.depth + 1; i > 0; i--) { + var node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i); + if (NodeSelection.isSelectable(node)) { + if (selectedNode && sel.$from.depth > 0 && + i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos) + { selectAt = $pos.before(sel.$from.depth); } + else + { selectAt = $pos.before(i); } + break + } + } + + if (selectAt != null) { + updateSelection(view, NodeSelection.create(view.state.doc, selectAt), "pointer"); + return true + } else { + return false + } + } + + function handleSingleClick(view, pos, inside, event, selectNode) { + return runHandlerOnContext(view, "handleClickOn", pos, inside, event) || + view.someProp("handleClick", function (f) { return f(view, pos, event); }) || + (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside)) + } + + function handleDoubleClick(view, pos, inside, event) { + return runHandlerOnContext(view, "handleDoubleClickOn", pos, inside, event) || + view.someProp("handleDoubleClick", function (f) { return f(view, pos, event); }) + } + + function handleTripleClick(view, pos, inside, event) { + return runHandlerOnContext(view, "handleTripleClickOn", pos, inside, event) || + view.someProp("handleTripleClick", function (f) { return f(view, pos, event); }) || + defaultTripleClick(view, inside) + } + + function defaultTripleClick(view, inside) { + var doc = view.state.doc; + if (inside == -1) { + if (doc.inlineContent) { + updateSelection(view, TextSelection.create(doc, 0, doc.content.size), "pointer"); + return true + } + return false + } + + var $pos = doc.resolve(inside); + for (var i = $pos.depth + 1; i > 0; i--) { + var node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i); + var nodePos = $pos.before(i); + if (node.inlineContent) + { updateSelection(view, TextSelection.create(doc, nodePos + 1, nodePos + 1 + node.content.size), "pointer"); } + else if (NodeSelection.isSelectable(node)) + { updateSelection(view, NodeSelection.create(doc, nodePos), "pointer"); } + else + { continue } + return true + } + } + + function forceDOMFlush(view) { + return endComposition(view) + } + + var selectNodeModifier = result.mac ? "metaKey" : "ctrlKey"; + + handlers.mousedown = function (view, event) { + view.shiftKey = event.shiftKey; + var flushed = forceDOMFlush(view); + var now = Date.now(), type = "singleClick"; + if (now - view.lastClick.time < 500 && isNear(event, view.lastClick) && !event[selectNodeModifier]) { + if (view.lastClick.type == "singleClick") { type = "doubleClick"; } + else if (view.lastClick.type == "doubleClick") { type = "tripleClick"; } + } + view.lastClick = {time: now, x: event.clientX, y: event.clientY, type: type}; + + var pos = view.posAtCoords(eventCoords(event)); + if (!pos) { return } + + if (type == "singleClick") + { view.mouseDown = new MouseDown(view, pos, event, flushed); } + else if ((type == "doubleClick" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) + { event.preventDefault(); } + else + { setSelectionOrigin(view, "pointer"); } + }; + + var MouseDown = function MouseDown(view, pos, event, flushed) { + var this$1 = this; + + this.view = view; + this.startDoc = view.state.doc; + this.pos = pos; + this.event = event; + this.flushed = flushed; + this.selectNode = event[selectNodeModifier]; + this.allowDefault = event.shiftKey; + + var targetNode, targetPos; + if (pos.inside > -1) { + targetNode = view.state.doc.nodeAt(pos.inside); + targetPos = pos.inside; + } else { + var $pos = view.state.doc.resolve(pos.pos); + targetNode = $pos.parent; + targetPos = $pos.depth ? $pos.before() : 0; + } + + this.mightDrag = null; + + var target = flushed ? null : event.target; + var targetDesc = target ? view.docView.nearestDesc(target, true) : null; + this.target = targetDesc ? targetDesc.dom : null; + + if (targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false || + view.state.selection instanceof NodeSelection && targetPos == view.state.selection.from) + { this.mightDrag = {node: targetNode, + pos: targetPos, + addAttr: this.target && !this.target.draggable, + setUneditable: this.target && result.gecko && !this.target.hasAttribute("contentEditable")}; } + + if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) { + this.view.domObserver.stop(); + if (this.mightDrag.addAttr) { this.target.draggable = true; } + if (this.mightDrag.setUneditable) + { setTimeout(function () { return this$1.target.setAttribute("contentEditable", "false"); }, 20); } + this.view.domObserver.start(); + } + + view.root.addEventListener("mouseup", this.up = this.up.bind(this)); + view.root.addEventListener("mousemove", this.move = this.move.bind(this)); + setSelectionOrigin(view, "pointer"); + }; + + MouseDown.prototype.done = function done () { + this.view.root.removeEventListener("mouseup", this.up); + this.view.root.removeEventListener("mousemove", this.move); + if (this.mightDrag && this.target) { + this.view.domObserver.stop(); + if (this.mightDrag.addAttr) { this.target.removeAttribute("draggable"); } + if (this.mightDrag.setUneditable) { this.target.removeAttribute("contentEditable"); } + this.view.domObserver.start(); + } + this.view.mouseDown = null; + }; + + MouseDown.prototype.up = function up (event) { + this.done(); + + if (!this.view.dom.contains(event.target.nodeType == 3 ? event.target.parentNode : event.target)) + { return } + + var pos = this.pos; + if (this.view.state.doc != this.startDoc) { pos = this.view.posAtCoords(eventCoords(event)); } + + if (this.allowDefault || !pos) { + setSelectionOrigin(this.view, "pointer"); + } else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) { + event.preventDefault(); + } else if (this.flushed || + // Safari ignores clicks on draggable elements + (result.safari && this.mightDrag && !this.mightDrag.node.isAtom) || + // Chrome will sometimes treat a node selection as a + // cursor, but still report that the node is selected + // when asked through getSelection. You'll then get a + // situation where clicking at the point where that + // (hidden) cursor is doesn't change the selection, and + // thus doesn't get a reaction from ProseMirror. This + // works around that. + (result.chrome && !(this.view.state.selection instanceof TextSelection) && + (pos.pos == this.view.state.selection.from || pos.pos == this.view.state.selection.to))) { + updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)), "pointer"); + event.preventDefault(); + } else { + setSelectionOrigin(this.view, "pointer"); + } + }; + + MouseDown.prototype.move = function move (event) { + if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 || + Math.abs(this.event.y - event.clientY) > 4)) + { this.allowDefault = true; } + setSelectionOrigin(this.view, "pointer"); + }; + + handlers.touchdown = function (view) { + forceDOMFlush(view); + setSelectionOrigin(view, "pointer"); + }; + + handlers.contextmenu = function (view) { return forceDOMFlush(view); }; + + function inOrNearComposition(view, event) { + if (view.composing) { return true } + // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/. + // On Japanese input method editors (IMEs), the Enter key is used to confirm character + // selection. On Safari, when Enter is pressed, compositionend and keydown events are + // emitted. The keydown event triggers newline insertion, which we don't want. + // This method returns true if the keydown event should be ignored. + // We only ignore it once, as pressing Enter a second time *should* insert a newline. + // Furthermore, the keydown event timestamp must be close to the compositionEndedAt timestamp. + // This guards against the case where compositionend is triggered without the keyboard + // (e.g. character confirmation may be done with the mouse), and keydown is triggered + // afterwards- we wouldn't want to ignore the keydown event in this case. + if (result.safari && Math.abs(event.timeStamp - view.compositionEndedAt) < 500) { + view.compositionEndedAt = -2e8; + return true + } + return false + } + + // Drop active composition after 5 seconds of inactivity on Android + var timeoutComposition = result.android ? 5000 : -1; + + editHandlers.compositionstart = editHandlers.compositionupdate = function (view) { + if (!view.composing) { + view.domObserver.flush(); + var state = view.state; + var $pos = state.selection.$from; + if (state.selection.empty && + (state.storedMarks || (!$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some(function (m) { return m.type.spec.inclusive === false; })))) { + // Need to wrap the cursor in mark nodes different from the ones in the DOM context + view.markCursor = view.state.storedMarks || $pos.marks(); + endComposition(view, true); + view.markCursor = null; + } else { + endComposition(view); + // In firefox, if the cursor is after but outside a marked node, + // the inserted text won't inherit the marks. So this moves it + // inside if necessary. + if (result.gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) { + var sel = view.root.getSelection(); + for (var node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0;) { + var before = offset < 0 ? node.lastChild : node.childNodes[offset - 1]; + if (!before) { break } + if (before.nodeType == 3) { + sel.collapse(before, before.nodeValue.length); + break + } else { + node = before; + offset = -1; + } + } + } + } + view.composing = true; + } + scheduleComposeEnd(view, timeoutComposition); + }; + + editHandlers.compositionend = function (view, event) { + if (view.composing) { + view.composing = false; + view.compositionEndedAt = event.timeStamp; + scheduleComposeEnd(view, 20); + } + }; + + function scheduleComposeEnd(view, delay) { + clearTimeout(view.composingTimeout); + if (delay > -1) { view.composingTimeout = setTimeout(function () { return endComposition(view); }, delay); } + } + + function clearComposition(view) { + view.composing = false; + while (view.compositionNodes.length > 0) { view.compositionNodes.pop().markParentsDirty(); } + } + + function endComposition(view, forceUpdate) { + view.domObserver.forceFlush(); + clearComposition(view); + if (forceUpdate || view.docView.dirty) { + var sel = selectionFromDOM(view); + if (sel && !sel.eq(view.state.selection)) { view.dispatch(view.state.tr.setSelection(sel)); } + else { view.updateState(view.state); } + return true + } + return false + } + + function captureCopy(view, dom) { + // The extra wrapper is somehow necessary on IE/Edge to prevent the + // content from being mangled when it is put onto the clipboard + if (!view.dom.parentNode) { return } + var wrap = view.dom.parentNode.appendChild(document.createElement("div")); + wrap.appendChild(dom); + wrap.style.cssText = "position: fixed; left: -10000px; top: 10px"; + var sel = getSelection(), range = document.createRange(); + range.selectNodeContents(dom); + // Done because IE will fire a selectionchange moving the selection + // to its start when removeAllRanges is called and the editor still + // has focus (which will mess up the editor's selection state). + view.dom.blur(); + sel.removeAllRanges(); + sel.addRange(range); + setTimeout(function () { + if (wrap.parentNode) { wrap.parentNode.removeChild(wrap); } + view.focus(); + }, 50); + } + + // This is very crude, but unfortunately both these browsers _pretend_ + // that they have a clipboard API—all the objects and methods are + // there, they just don't work, and they are hard to test. + var brokenClipboardAPI = (result.ie && result.ie_version < 15) || + (result.ios && result.webkit_version < 604); + + handlers.copy = editHandlers.cut = function (view, e) { + var sel = view.state.selection, cut = e.type == "cut"; + if (sel.empty) { return } + + // IE and Edge's clipboard interface is completely broken + var data = brokenClipboardAPI ? null : e.clipboardData; + var slice = sel.content(); + var ref = serializeForClipboard(view, slice); + var dom = ref.dom; + var text = ref.text; + if (data) { + e.preventDefault(); + data.clearData(); + data.setData("text/html", dom.innerHTML); + data.setData("text/plain", text); + } else { + captureCopy(view, dom); + } + if (cut) { view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut")); } + }; + + function sliceSingleNode(slice) { + return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null + } + + function capturePaste(view, e) { + if (!view.dom.parentNode) { return } + var plainText = view.shiftKey || view.state.selection.$from.parent.type.spec.code; + var target = view.dom.parentNode.appendChild(document.createElement(plainText ? "textarea" : "div")); + if (!plainText) { target.contentEditable = "true"; } + target.style.cssText = "position: fixed; left: -10000px; top: 10px"; + target.focus(); + setTimeout(function () { + view.focus(); + if (target.parentNode) { target.parentNode.removeChild(target); } + if (plainText) { doPaste(view, target.value, null, e); } + else { doPaste(view, target.textContent, target.innerHTML, e); } + }, 50); + } + + function doPaste(view, text, html, e) { + var slice = parseFromClipboard(view, text, html, view.shiftKey, view.state.selection.$from); + if (view.someProp("handlePaste", function (f) { return f(view, e, slice || Slice.empty); }) || !slice) { return } + + var singleNode = sliceSingleNode(slice); + var tr = singleNode ? view.state.tr.replaceSelectionWith(singleNode, view.shiftKey) : view.state.tr.replaceSelection(slice); + view.dispatch(tr.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste")); + } + + editHandlers.paste = function (view, e) { + var data = brokenClipboardAPI ? null : e.clipboardData; + var html = data && data.getData("text/html"), text = data && data.getData("text/plain"); + if (data && (html || text || data.files.length)) { + doPaste(view, text, html, e); + e.preventDefault(); + } else { + capturePaste(view, e); + } + }; + + var Dragging = function Dragging(slice, move) { + this.slice = slice; + this.move = move; + }; + + var dragCopyModifier = result.mac ? "altKey" : "ctrlKey"; + + handlers.dragstart = function (view, e) { + var mouseDown = view.mouseDown; + if (mouseDown) { mouseDown.done(); } + if (!e.dataTransfer) { return } + + var sel = view.state.selection; + var pos = sel.empty ? null : view.posAtCoords(eventCoords(e)); + if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1: sel.to)) ; else if (mouseDown && mouseDown.mightDrag) { + view.dispatch(view.state.tr.setSelection(NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos))); + } else if (e.target && e.target.nodeType == 1) { + var desc = view.docView.nearestDesc(e.target, true); + if (!desc || !desc.node.type.spec.draggable || desc == view.docView) { return } + view.dispatch(view.state.tr.setSelection(NodeSelection.create(view.state.doc, desc.posBefore))); + } + var slice = view.state.selection.content(); + var ref = serializeForClipboard(view, slice); + var dom = ref.dom; + var text = ref.text; + e.dataTransfer.clearData(); + e.dataTransfer.setData(brokenClipboardAPI ? "Text" : "text/html", dom.innerHTML); + if (!brokenClipboardAPI) { e.dataTransfer.setData("text/plain", text); } + view.dragging = new Dragging(slice, !e[dragCopyModifier]); + }; + + handlers.dragend = function (view) { + var dragging = view.dragging; + window.setTimeout(function () { + if (view.dragging == dragging) { view.dragging = null; } + }, 50); + }; + + editHandlers.dragover = editHandlers.dragenter = function (_, e) { return e.preventDefault(); }; + + editHandlers.drop = function (view, e) { + var dragging = view.dragging; + view.dragging = null; + + if (!e.dataTransfer) { return } + + var eventPos = view.posAtCoords(eventCoords(e)); + if (!eventPos) { return } + var $mouse = view.state.doc.resolve(eventPos.pos); + if (!$mouse) { return } + var slice = dragging && dragging.slice || + parseFromClipboard(view, e.dataTransfer.getData(brokenClipboardAPI ? "Text" : "text/plain"), + brokenClipboardAPI ? null : e.dataTransfer.getData("text/html"), false, $mouse); + var move = dragging && !e[dragCopyModifier]; + if (view.someProp("handleDrop", function (f) { return f(view, e, slice || Slice.empty, move); })) { + e.preventDefault(); + return + } + if (!slice) { return } + + e.preventDefault(); + var insertPos = slice ? dropPoint(view.state.doc, $mouse.pos, slice) : $mouse.pos; + if (insertPos == null) { insertPos = $mouse.pos; } + + var tr = view.state.tr; + if (move) { tr.deleteSelection(); } + + var pos = tr.mapping.map(insertPos); + var isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1; + var beforeInsert = tr.doc; + if (isNode) + { tr.replaceRangeWith(pos, pos, slice.content.firstChild); } + else + { tr.replaceRange(pos, pos, slice); } + if (tr.doc.eq(beforeInsert)) { return } + + var $pos = tr.doc.resolve(pos); + if (isNode && NodeSelection.isSelectable(slice.content.firstChild) && + $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice.content.firstChild)) { + tr.setSelection(new NodeSelection($pos)); + } else { + var end = tr.mapping.map(insertPos); + tr.mapping.maps[tr.mapping.maps.length - 1].forEach(function (_from, _to, _newFrom, newTo) { return end = newTo; }); + tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(end))); + } + view.focus(); + view.dispatch(tr.setMeta("uiEvent", "drop")); + }; + + handlers.focus = function (view) { + if (!view.focused) { + view.domObserver.stop(); + view.dom.classList.add("ProseMirror-focused"); + view.domObserver.start(); + view.focused = true; + setTimeout(function () { + if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.root.getSelection())) + { selectionToDOM(view); } + }, 20); + } + }; + + handlers.blur = function (view) { + if (view.focused) { + view.domObserver.stop(); + view.dom.classList.remove("ProseMirror-focused"); + view.domObserver.start(); + view.domObserver.currentSelection.set({}); + view.focused = false; + } + }; + + handlers.beforeinput = function (view, event) { + // We should probably do more with beforeinput events, but support + // is so spotty that I'm still waiting to see where they are going. + + // Very specific hack to deal with backspace sometimes failing on + // Chrome Android when after an uneditable node. + if (result.chrome && result.android && event.inputType == "deleteContentBackward") { + var domChangeCount = view.domChangeCount; + setTimeout(function () { + if (view.domChangeCount != domChangeCount) { return } // Event already had some effect + // This bug tends to close the virtual keyboard, so we refocus + view.dom.blur(); + view.focus(); + if (view.someProp("handleKeyDown", function (f) { return f(view, keyEvent(8, "Backspace")); })) { return } + var ref = view.state.selection; + var $cursor = ref.$cursor; + // Crude approximation of backspace behavior when no command handled it + if ($cursor && $cursor.pos > 0) { view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView()); } + }, 50); + } + }; + + // Make sure all handlers get registered + for (var prop in editHandlers) { handlers[prop] = editHandlers[prop]; } + + function compareObjs(a, b) { + if (a == b) { return true } + for (var p in a) { if (a[p] !== b[p]) { return false } } + for (var p$1 in b) { if (!(p$1 in a)) { return false } } + return true + } + + var WidgetType = function WidgetType(toDOM, spec) { + this.spec = spec || noSpec; + this.side = this.spec.side || 0; + this.toDOM = toDOM; + }; + + WidgetType.prototype.map = function map (mapping, span, offset, oldOffset) { + var ref = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1); + var pos = ref.pos; + var deleted = ref.deleted; + return deleted ? null : new Decoration(pos - offset, pos - offset, this) + }; + + WidgetType.prototype.valid = function valid () { return true }; + + WidgetType.prototype.eq = function eq (other) { + return this == other || + (other instanceof WidgetType && + (this.spec.key && this.spec.key == other.spec.key || + this.toDOM == other.toDOM && compareObjs(this.spec, other.spec))) + }; + + var InlineType = function InlineType(attrs, spec) { + this.spec = spec || noSpec; + this.attrs = attrs; + }; + + InlineType.prototype.map = function map (mapping, span, offset, oldOffset) { + var from = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset; + var to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset; + return from >= to ? null : new Decoration(from, to, this) + }; + + InlineType.prototype.valid = function valid (_, span) { return span.from < span.to }; + + InlineType.prototype.eq = function eq (other) { + return this == other || + (other instanceof InlineType && compareObjs(this.attrs, other.attrs) && + compareObjs(this.spec, other.spec)) + }; + + InlineType.is = function is (span) { return span.type instanceof InlineType }; + + var NodeType$1 = function NodeType(attrs, spec) { + this.spec = spec || noSpec; + this.attrs = attrs; + }; + + NodeType$1.prototype.map = function map (mapping, span, offset, oldOffset) { + var from = mapping.mapResult(span.from + oldOffset, 1); + if (from.deleted) { return null } + var to = mapping.mapResult(span.to + oldOffset, -1); + if (to.deleted || to.pos <= from.pos) { return null } + return new Decoration(from.pos - offset, to.pos - offset, this) + }; + + NodeType$1.prototype.valid = function valid (node, span) { + var ref = node.content.findIndex(span.from); + var index = ref.index; + var offset = ref.offset; + return offset == span.from && offset + node.child(index).nodeSize == span.to + }; + + NodeType$1.prototype.eq = function eq (other) { + return this == other || + (other instanceof NodeType$1 && compareObjs(this.attrs, other.attrs) && + compareObjs(this.spec, other.spec)) + }; + + // ::- Decoration objects can be provided to the view through the + // [`decorations` prop](#view.EditorProps.decorations). They come in + // several variants—see the static members of this class for details. + var Decoration = function Decoration(from, to, type) { + // :: number + // The start position of the decoration. + this.from = from; + // :: number + // The end position. Will be the same as `from` for [widget + // decorations](#view.Decoration^widget). + this.to = to; + this.type = type; + }; + + var prototypeAccessors$1$6 = { spec: { configurable: true },inline: { configurable: true } }; + + Decoration.prototype.copy = function copy (from, to) { + return new Decoration(from, to, this.type) + }; + + Decoration.prototype.eq = function eq (other, offset) { + if ( offset === void 0 ) offset = 0; + + return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to + }; + + Decoration.prototype.map = function map (mapping, offset, oldOffset) { + return this.type.map(mapping, this, offset, oldOffset) + }; + + // :: (number, union<(view: EditorView, getPos: () → number) → dom.Node, dom.Node>, ?Object) → Decoration + // Creates a widget decoration, which is a DOM node that's shown in + // the document at the given position. It is recommended that you + // delay rendering the widget by passing a function that will be + // called when the widget is actually drawn in a view, but you can + // also directly pass a DOM node. `getPos` can be used to find the + // widget's current document position. + // + // spec::- These options are supported: + // + // side:: ?number + // Controls which side of the document position this widget is + // associated with. When negative, it is drawn before a cursor + // at its position, and content inserted at that position ends + // up after the widget. When zero (the default) or positive, the + // widget is drawn after the cursor and content inserted there + // ends up before the widget. + // + // When there are multiple widgets at a given position, their + // `side` values determine the order in which they appear. Those + // with lower values appear first. The ordering of widgets with + // the same `side` value is unspecified. + // + // When `marks` is null, `side` also determines the marks that + // the widget is wrapped in—those of the node before when + // negative, those of the node after when positive. + // + // marks:: ?[Mark] + // The precise set of marks to draw around the widget. + // + // stopEvent:: ?(event: dom.Event) → bool + // Can be used to control which DOM events, when they bubble out + // of this widget, the editor view should ignore. + // + // ignoreSelection:: ?bool + // When set (defaults to false), selection changes inside the + // widget are ignored, and don't cause ProseMirror to try and + // re-sync the selection with its selection state. + // + // key:: ?string + // When comparing decorations of this type (in order to decide + // whether it needs to be redrawn), ProseMirror will by default + // compare the widget DOM node by identity. If you pass a key, + // that key will be compared instead, which can be useful when + // you generate decorations on the fly and don't want to store + // and reuse DOM nodes. Make sure that any widgets with the same + // key are interchangeable—if widgets differ in, for example, + // the behavior of some event handler, they should get + // different keys. + Decoration.widget = function widget (pos, toDOM, spec) { + return new Decoration(pos, pos, new WidgetType(toDOM, spec)) + }; + + // :: (number, number, DecorationAttrs, ?Object) → Decoration + // Creates an inline decoration, which adds the given attributes to + // each inline node between `from` and `to`. + // + // spec::- These options are recognized: + // + // inclusiveStart:: ?bool + // Determines how the left side of the decoration is + // [mapped](#transform.Position_Mapping) when content is + // inserted directly at that position. By default, the decoration + // won't include the new content, but you can set this to `true` + // to make it inclusive. + // + // inclusiveEnd:: ?bool + // Determines how the right side of the decoration is mapped. + // See + // [`inclusiveStart`](#view.Decoration^inline^spec.inclusiveStart). + Decoration.inline = function inline (from, to, attrs, spec) { + return new Decoration(from, to, new InlineType(attrs, spec)) + }; + + // :: (number, number, DecorationAttrs, ?Object) → Decoration + // Creates a node decoration. `from` and `to` should point precisely + // before and after a node in the document. That node, and only that + // node, will receive the given attributes. + // + // spec::- + // + // Optional information to store with the decoration. It + // is also used when comparing decorators for equality. + Decoration.node = function node (from, to, attrs, spec) { + return new Decoration(from, to, new NodeType$1(attrs, spec)) + }; + + // :: Object + // The spec provided when creating this decoration. Can be useful + // if you've stored extra information in that object. + prototypeAccessors$1$6.spec.get = function () { return this.type.spec }; + + prototypeAccessors$1$6.inline.get = function () { return this.type instanceof InlineType }; + + Object.defineProperties( Decoration.prototype, prototypeAccessors$1$6 ); + + // DecorationAttrs:: interface + // A set of attributes to add to a decorated node. Most properties + // simply directly correspond to DOM attributes of the same name, + // which will be set to the property's value. These are exceptions: + // + // class:: ?string + // A CSS class name or a space-separated set of class names to be + // _added_ to the classes that the node already had. + // + // style:: ?string + // A string of CSS to be _added_ to the node's existing `style` property. + // + // nodeName:: ?string + // When non-null, the target node is wrapped in a DOM element of + // this type (and the other attributes are applied to this element). + + var none = [], noSpec = {}; + + // ::- A collection of [decorations](#view.Decoration), organized in + // such a way that the drawing algorithm can efficiently use and + // compare them. This is a persistent data structure—it is not + // modified, updates create a new value. + var DecorationSet = function DecorationSet(local, children) { + this.local = local && local.length ? local : none; + this.children = children && children.length ? children : none; + }; + + // :: (Node, [Decoration]) → DecorationSet + // Create a set of decorations, using the structure of the given + // document. + DecorationSet.create = function create (doc, decorations) { + return decorations.length ? buildTree(decorations, doc, 0, noSpec) : empty + }; + + // :: (?number, ?number, ?(spec: Object) → bool) → [Decoration] + // Find all decorations in this set which touch the given range + // (including decorations that start or end directly at the + // boundaries) and match the given predicate on their spec. When + // `start` and `end` are omitted, all decorations in the set are + // considered. When `predicate` isn't given, all decorations are + // assumed to match. + DecorationSet.prototype.find = function find (start, end, predicate) { + var result = []; + this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate); + return result + }; + + DecorationSet.prototype.findInner = function findInner (start, end, result, offset, predicate) { + for (var i = 0; i < this.local.length; i++) { + var span = this.local[i]; + if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec))) + { result.push(span.copy(span.from + offset, span.to + offset)); } + } + for (var i$1 = 0; i$1 < this.children.length; i$1 += 3) { + if (this.children[i$1] < end && this.children[i$1 + 1] > start) { + var childOff = this.children[i$1] + 1; + this.children[i$1 + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate); + } + } + }; + + // :: (Mapping, Node, ?Object) → DecorationSet + // Map the set of decorations in response to a change in the + // document. + // + // options::- An optional set of options. + // + // onRemove:: ?(decorationSpec: Object) + // When given, this function will be called for each decoration + // that gets dropped as a result of the mapping, passing the + // spec of that decoration. + DecorationSet.prototype.map = function map (mapping, doc, options) { + if (this == empty || mapping.maps.length == 0) { return this } + return this.mapInner(mapping, doc, 0, 0, options || noSpec) + }; + + DecorationSet.prototype.mapInner = function mapInner (mapping, node, offset, oldOffset, options) { + var newLocal; + for (var i = 0; i < this.local.length; i++) { + var mapped = this.local[i].map(mapping, offset, oldOffset); + if (mapped && mapped.type.valid(node, mapped)) { (newLocal || (newLocal = [])).push(mapped); } + else if (options.onRemove) { options.onRemove(this.local[i].spec); } + } + + if (this.children.length) + { return mapChildren(this.children, newLocal, mapping, node, offset, oldOffset, options) } + else + { return newLocal ? new DecorationSet(newLocal.sort(byPos)) : empty } + }; + + // :: (Node, [Decoration]) → DecorationSet + // Add the given array of decorations to the ones in the set, + // producing a new set. Needs access to the current document to + // create the appropriate tree structure. + DecorationSet.prototype.add = function add (doc, decorations) { + if (!decorations.length) { return this } + if (this == empty) { return DecorationSet.create(doc, decorations) } + return this.addInner(doc, decorations, 0) + }; + + DecorationSet.prototype.addInner = function addInner (doc, decorations, offset) { + var this$1 = this; + + var children, childIndex = 0; + doc.forEach(function (childNode, childOffset) { + var baseOffset = childOffset + offset, found; + if (!(found = takeSpansForNode(decorations, childNode, baseOffset))) { return } + + if (!children) { children = this$1.children.slice(); } + while (childIndex < children.length && children[childIndex] < childOffset) { childIndex += 3; } + if (children[childIndex] == childOffset) + { children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found, baseOffset + 1); } + else + { children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found, childNode, baseOffset + 1, noSpec)); } + childIndex += 3; + }); + + var local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset); + return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, + children || this.children) + }; + + // :: ([Decoration]) → DecorationSet + // Create a new set that contains the decorations in this set, minus + // the ones in the given array. + DecorationSet.prototype.remove = function remove (decorations) { + if (decorations.length == 0 || this == empty) { return this } + return this.removeInner(decorations, 0) + }; + + DecorationSet.prototype.removeInner = function removeInner (decorations, offset) { + var children = this.children, local = this.local; + for (var i = 0; i < children.length; i += 3) { + var found = (void 0), from = children[i] + offset, to = children[i + 1] + offset; + for (var j = 0, span = (void 0); j < decorations.length; j++) { if (span = decorations[j]) { + if (span.from > from && span.to < to) { + decorations[j] = null + ;(found || (found = [])).push(span); + } + } } + if (!found) { continue } + if (children == this.children) { children = this.children.slice(); } + var removed = children[i + 2].removeInner(found, from + 1); + if (removed != empty) { + children[i + 2] = removed; + } else { + children.splice(i, 3); + i -= 3; + } + } + if (local.length) { for (var i$1 = 0, span$1 = (void 0); i$1 < decorations.length; i$1++) { if (span$1 = decorations[i$1]) { + for (var j$1 = 0; j$1 < local.length; j$1++) { if (local[j$1].eq(span$1, offset)) { + if (local == this.local) { local = this.local.slice(); } + local.splice(j$1--, 1); + } } + } } } + if (children == this.children && local == this.local) { return this } + return local.length || children.length ? new DecorationSet(local, children) : empty + }; + + DecorationSet.prototype.forChild = function forChild (offset, node) { + if (this == empty) { return this } + if (node.isLeaf) { return DecorationSet.empty } + + var child, local; + for (var i = 0; i < this.children.length; i += 3) { if (this.children[i] >= offset) { + if (this.children[i] == offset) { child = this.children[i + 2]; } + break + } } + var start = offset + 1, end = start + node.content.size; + for (var i$1 = 0; i$1 < this.local.length; i$1++) { + var dec = this.local[i$1]; + if (dec.from < end && dec.to > start && (dec.type instanceof InlineType)) { + var from = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start; + if (from < to) { (local || (local = [])).push(dec.copy(from, to)); } + } + } + if (local) { + var localSet = new DecorationSet(local.sort(byPos)); + return child ? new DecorationGroup([localSet, child]) : localSet + } + return child || empty + }; + + DecorationSet.prototype.eq = function eq (other) { + if (this == other) { return true } + if (!(other instanceof DecorationSet) || + this.local.length != other.local.length || + this.children.length != other.children.length) { return false } + for (var i = 0; i < this.local.length; i++) + { if (!this.local[i].eq(other.local[i])) { return false } } + for (var i$1 = 0; i$1 < this.children.length; i$1 += 3) + { if (this.children[i$1] != other.children[i$1] || + this.children[i$1 + 1] != other.children[i$1 + 1] || + !this.children[i$1 + 2].eq(other.children[i$1 + 2])) { return false } } + return true + }; + + DecorationSet.prototype.locals = function locals (node) { + return removeOverlap(this.localsInner(node)) + }; + + DecorationSet.prototype.localsInner = function localsInner (node) { + if (this == empty) { return none } + if (node.inlineContent || !this.local.some(InlineType.is)) { return this.local } + var result = []; + for (var i = 0; i < this.local.length; i++) { + if (!(this.local[i].type instanceof InlineType)) + { result.push(this.local[i]); } + } + return result + }; + + var empty = new DecorationSet(); + + // :: DecorationSet + // The empty set of decorations. + DecorationSet.empty = empty; + + DecorationSet.removeOverlap = removeOverlap; + + // :- An abstraction that allows the code dealing with decorations to + // treat multiple DecorationSet objects as if it were a single object + // with (a subset of) the same interface. + var DecorationGroup = function DecorationGroup(members) { + this.members = members; + }; + + DecorationGroup.prototype.forChild = function forChild (offset, child) { + if (child.isLeaf) { return DecorationSet.empty } + var found = []; + for (var i = 0; i < this.members.length; i++) { + var result = this.members[i].forChild(offset, child); + if (result == empty) { continue } + if (result instanceof DecorationGroup) { found = found.concat(result.members); } + else { found.push(result); } + } + return DecorationGroup.from(found) + }; + + DecorationGroup.prototype.eq = function eq (other) { + if (!(other instanceof DecorationGroup) || + other.members.length != this.members.length) { return false } + for (var i = 0; i < this.members.length; i++) + { if (!this.members[i].eq(other.members[i])) { return false } } + return true + }; + + DecorationGroup.prototype.locals = function locals (node) { + var result, sorted = true; + for (var i = 0; i < this.members.length; i++) { + var locals = this.members[i].localsInner(node); + if (!locals.length) { continue } + if (!result) { + result = locals; + } else { + if (sorted) { + result = result.slice(); + sorted = false; + } + for (var j = 0; j < locals.length; j++) { result.push(locals[j]); } + } + } + return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none + }; + + // : ([DecorationSet]) → union + // Create a group for the given array of decoration sets, or return + // a single set when possible. + DecorationGroup.from = function from (members) { + switch (members.length) { + case 0: return empty + case 1: return members[0] + default: return new DecorationGroup(members) + } + }; + + function mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) { + var children = oldChildren.slice(); + + // Mark the children that are directly touched by changes, and + // move those that are after the changes. + var shift = function (oldStart, oldEnd, newStart, newEnd) { + for (var i = 0; i < children.length; i += 3) { + var end = children[i + 1], dSize = (void 0); + if (end == -1 || oldStart > end + oldOffset) { continue } + if (oldEnd >= children[i] + oldOffset) { + children[i + 1] = -1; + } else if (newStart >= offset && (dSize = (newEnd - newStart) - (oldEnd - oldStart))) { + children[i] += dSize; + children[i + 1] += dSize; + } + } + }; + for (var i = 0; i < mapping.maps.length; i++) { mapping.maps[i].forEach(shift); } + + // Find the child nodes that still correspond to a single node, + // recursively call mapInner on them and update their positions. + var mustRebuild = false; + for (var i$1 = 0; i$1 < children.length; i$1 += 3) { if (children[i$1 + 1] == -1) { // Touched nodes + var from = mapping.map(oldChildren[i$1] + oldOffset), fromLocal = from - offset; + if (fromLocal < 0 || fromLocal >= node.content.size) { + mustRebuild = true; + continue + } + // Must read oldChildren because children was tagged with -1 + var to = mapping.map(oldChildren[i$1 + 1] + oldOffset, -1), toLocal = to - offset; + var ref = node.content.findIndex(fromLocal); + var index = ref.index; + var childOffset = ref.offset; + var childNode = node.maybeChild(index); + if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) { + var mapped = children[i$1 + 2].mapInner(mapping, childNode, from + 1, oldChildren[i$1] + oldOffset + 1, options); + if (mapped != empty) { + children[i$1] = fromLocal; + children[i$1 + 1] = toLocal; + children[i$1 + 2] = mapped; + } else { + children[i$1 + 1] = -2; + mustRebuild = true; + } + } else { + mustRebuild = true; + } + } } + + // Remaining children must be collected and rebuilt into the appropriate structure + if (mustRebuild) { + var decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal || [], mapping, + offset, oldOffset, options); + var built = buildTree(decorations, node, 0, options); + newLocal = built.local; + for (var i$2 = 0; i$2 < children.length; i$2 += 3) { if (children[i$2 + 1] < 0) { + children.splice(i$2, 3); + i$2 -= 3; + } } + for (var i$3 = 0, j = 0; i$3 < built.children.length; i$3 += 3) { + var from$1 = built.children[i$3]; + while (j < children.length && children[j] < from$1) { j += 3; } + children.splice(j, 0, built.children[i$3], built.children[i$3 + 1], built.children[i$3 + 2]); + } + } + + return new DecorationSet(newLocal && newLocal.sort(byPos), children) + } + + function moveSpans(spans, offset) { + if (!offset || !spans.length) { return spans } + var result = []; + for (var i = 0; i < spans.length; i++) { + var span = spans[i]; + result.push(new Decoration(span.from + offset, span.to + offset, span.type)); + } + return result + } + + function mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) { + // Gather all decorations from the remaining marked children + function gather(set, oldOffset) { + for (var i = 0; i < set.local.length; i++) { + var mapped = set.local[i].map(mapping, offset, oldOffset); + if (mapped) { decorations.push(mapped); } + else if (options.onRemove) { options.onRemove(set.local[i].spec); } + } + for (var i$1 = 0; i$1 < set.children.length; i$1 += 3) + { gather(set.children[i$1 + 2], set.children[i$1] + oldOffset + 1); } + } + for (var i = 0; i < children.length; i += 3) { if (children[i + 1] == -1) + { gather(children[i + 2], oldChildren[i] + oldOffset + 1); } } + + return decorations + } + + function takeSpansForNode(spans, node, offset) { + if (node.isLeaf) { return null } + var end = offset + node.nodeSize, found = null; + for (var i = 0, span = (void 0); i < spans.length; i++) { + if ((span = spans[i]) && span.from > offset && span.to < end) { + (found || (found = [])).push(span); + spans[i] = null; + } + } + return found + } + + function withoutNulls(array) { + var result = []; + for (var i = 0; i < array.length; i++) + { if (array[i] != null) { result.push(array[i]); } } + return result + } + + // : ([Decoration], Node, number) → DecorationSet + // Build up a tree that corresponds to a set of decorations. `offset` + // is a base offset that should be subtractet from the `from` and `to` + // positions in the spans (so that we don't have to allocate new spans + // for recursive calls). + function buildTree(spans, node, offset, options) { + var children = [], hasNulls = false; + node.forEach(function (childNode, localStart) { + var found = takeSpansForNode(spans, childNode, localStart + offset); + if (found) { + hasNulls = true; + var subtree = buildTree(found, childNode, offset + localStart + 1, options); + if (subtree != empty) + { children.push(localStart, localStart + childNode.nodeSize, subtree); } + } + }); + var locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos); + for (var i = 0; i < locals.length; i++) { if (!locals[i].type.valid(node, locals[i])) { + if (options.onRemove) { options.onRemove(locals[i].spec); } + locals.splice(i--, 1); + } } + return locals.length || children.length ? new DecorationSet(locals, children) : empty + } + + // : (Decoration, Decoration) → number + // Used to sort decorations so that ones with a low start position + // come first, and within a set with the same start position, those + // with an smaller end position come first. + function byPos(a, b) { + return a.from - b.from || a.to - b.to + } + + // : ([Decoration]) → [Decoration] + // Scan a sorted array of decorations for partially overlapping spans, + // and split those so that only fully overlapping spans are left (to + // make subsequent rendering easier). Will return the input array if + // no partially overlapping spans are found (the common case). + function removeOverlap(spans) { + var working = spans; + for (var i = 0; i < working.length - 1; i++) { + var span = working[i]; + if (span.from != span.to) { for (var j = i + 1; j < working.length; j++) { + var next = working[j]; + if (next.from == span.from) { + if (next.to != span.to) { + if (working == spans) { working = spans.slice(); } + // Followed by a partially overlapping larger span. Split that + // span. + working[j] = next.copy(next.from, span.to); + insertAhead(working, j + 1, next.copy(span.to, next.to)); + } + continue + } else { + if (next.from < span.to) { + if (working == spans) { working = spans.slice(); } + // The end of this one overlaps with a subsequent span. Split + // this one. + working[i] = span.copy(span.from, next.from); + insertAhead(working, j, span.copy(next.from, span.to)); + } + break + } + } } + } + return working + } + + function insertAhead(array, i, deco) { + while (i < array.length && byPos(deco, array[i]) > 0) { i++; } + array.splice(i, 0, deco); + } + + // : (EditorView) → union + // Get the decorations associated with the current props of a view. + function viewDecorations(view) { + var found = []; + view.someProp("decorations", function (f) { + var result = f(view.state); + if (result && result != empty) { found.push(result); } + }); + if (view.cursorWrapper) + { found.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco])); } + return DecorationGroup.from(found) + } + + // ::- An editor view manages the DOM structure that represents an + // editable document. Its state and behavior are determined by its + // [props](#view.DirectEditorProps). + var EditorView = function EditorView(place, props) { + this._props = props; + // :: EditorState + // The view's current [state](#state.EditorState). + this.state = props.state; + + this.dispatch = this.dispatch.bind(this); + + this._root = null; + this.focused = false; + // Kludge used to work around a Chrome bug + this.trackWrites = null; + + // :: dom.Element + // An editable DOM node containing the document. (You probably + // should not directly interfere with its content.) + this.dom = (place && place.mount) || document.createElement("div"); + if (place) { + if (place.appendChild) { place.appendChild(this.dom); } + else if (place.apply) { place(this.dom); } + else if (place.mount) { this.mounted = true; } + } + + // :: bool + // Indicates whether the editor is currently [editable](#view.EditorProps.editable). + this.editable = getEditable(this); + this.markCursor = null; + this.cursorWrapper = null; + updateCursorWrapper(this); + this.nodeViews = buildNodeViews(this); + this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this); + + this.lastSelectedViewDesc = null; + // :: ?{slice: Slice, move: bool} + // When editor content is being dragged, this object contains + // information about the dragged slice and whether it is being + // copied or moved. At any other time, it is null. + this.dragging = null; + + initInput(this); + + this.pluginViews = []; + this.updatePluginViews(); + }; + + var prototypeAccessors$2$1 = { props: { configurable: true },root: { configurable: true } }; + + // composing:: boolean + // Holds `true` when a + // [composition](https://developer.mozilla.org/en-US/docs/Mozilla/IME_handling_guide) + // is active. + + // :: DirectEditorProps + // The view's current [props](#view.EditorProps). + prototypeAccessors$2$1.props.get = function () { + if (this._props.state != this.state) { + var prev = this._props; + this._props = {}; + for (var name in prev) { this._props[name] = prev[name]; } + this._props.state = this.state; + } + return this._props + }; + + // :: (DirectEditorProps) + // Update the view's props. Will immediately cause an update to + // the DOM. + EditorView.prototype.update = function update (props) { + if (props.handleDOMEvents != this._props.handleDOMEvents) { ensureListeners(this); } + this._props = props; + this.updateStateInner(props.state, true); + }; + + // :: (DirectEditorProps) + // Update the view by updating existing props object with the object + // given as argument. Equivalent to `view.update(Object.assign({}, + // view.props, props))`. + EditorView.prototype.setProps = function setProps (props) { + var updated = {}; + for (var name in this._props) { updated[name] = this._props[name]; } + updated.state = this.state; + for (var name$1 in props) { updated[name$1] = props[name$1]; } + this.update(updated); + }; + + // :: (EditorState) + // Update the editor's `state` prop, without touching any of the + // other props. + EditorView.prototype.updateState = function updateState (state) { + this.updateStateInner(state, this.state.plugins != state.plugins); + }; + + EditorView.prototype.updateStateInner = function updateStateInner (state, reconfigured) { + var this$1 = this; + + var prev = this.state, redraw = false, updateSel = false; + // When stored marks are added, stop composition, so that they can + // be displayed. + if (state.storedMarks && this.composing) { + clearComposition(this); + updateSel = true; + } + this.state = state; + if (reconfigured) { + var nodeViews = buildNodeViews(this); + if (changedNodeViews(nodeViews, this.nodeViews)) { + this.nodeViews = nodeViews; + redraw = true; + } + ensureListeners(this); + } + + this.editable = getEditable(this); + updateCursorWrapper(this); + var innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this); + + var scroll = reconfigured ? "reset" + : state.scrollToSelection > prev.scrollToSelection ? "to selection" : "preserve"; + var updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco); + if (updateDoc || !state.selection.eq(prev.selection)) { updateSel = true; } + var oldScrollPos = scroll == "preserve" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this); + + if (updateSel) { + this.domObserver.stop(); + // Work around an issue in Chrome, IE, and Edge where changing + // the DOM around an active selection puts it into a broken + // state where the thing the user sees differs from the + // selection reported by the Selection object (#710, #973, + // #1011, #1013, #1035). + var forceSelUpdate = updateDoc && (result.ie || result.chrome) && !this.composing && + !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection); + if (updateDoc) { + // If the node that the selection points into is written to, + // Chrome sometimes starts misreporting the selection, so this + // tracks that and forces a selection reset when our update + // did write to the node. + var chromeKludge = result.chrome ? (this.trackWrites = this.root.getSelection().focusNode) : null; + if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) { + this.docView.updateOuterDeco([]); + this.docView.destroy(); + this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this); + } + if (chromeKludge && !this.trackWrites) { forceSelUpdate = true; } + } + // Work around for an issue where an update arriving right between + // a DOM selection change and the "selectionchange" event for it + // can cause a spurious DOM selection update, disrupting mouse + // drag selection. + if (forceSelUpdate || + !(this.mouseDown && this.domObserver.currentSelection.eq(this.root.getSelection()) && anchorInRightPlace(this))) { + selectionToDOM(this, forceSelUpdate); + } else { + syncNodeSelection(this, state.selection); + this.domObserver.setCurSelection(); + } + this.domObserver.start(); + } + + this.updatePluginViews(prev); + + if (scroll == "reset") { + this.dom.scrollTop = 0; + } else if (scroll == "to selection") { + var startDOM = this.root.getSelection().focusNode; + if (this.someProp("handleScrollToSelection", function (f) { return f(this$1); })) + ; // Handled + else if (state.selection instanceof NodeSelection) + { scrollRectIntoView(this, this.docView.domAfterPos(state.selection.from).getBoundingClientRect(), startDOM); } + else + { scrollRectIntoView(this, this.coordsAtPos(state.selection.head, 1), startDOM); } + } else if (oldScrollPos) { + resetScrollPos(oldScrollPos); + } + }; + + EditorView.prototype.destroyPluginViews = function destroyPluginViews () { + var view; + while (view = this.pluginViews.pop()) { if (view.destroy) { view.destroy(); } } + }; + + EditorView.prototype.updatePluginViews = function updatePluginViews (prevState) { + if (!prevState || prevState.plugins != this.state.plugins) { + this.destroyPluginViews(); + for (var i = 0; i < this.state.plugins.length; i++) { + var plugin = this.state.plugins[i]; + if (plugin.spec.view) { this.pluginViews.push(plugin.spec.view(this)); } + } + } else { + for (var i$1 = 0; i$1 < this.pluginViews.length; i$1++) { + var pluginView = this.pluginViews[i$1]; + if (pluginView.update) { pluginView.update(this, prevState); } + } + } + }; + + // :: (string, ?(prop: *) → *) → * + // Goes over the values of a prop, first those provided directly, + // then those from plugins (in order), and calls `f` every time a + // non-undefined value is found. When `f` returns a truthy value, + // that is immediately returned. When `f` isn't provided, it is + // treated as the identity function (the prop value is returned + // directly). + EditorView.prototype.someProp = function someProp (propName, f) { + var prop = this._props && this._props[propName], value; + if (prop != null && (value = f ? f(prop) : prop)) { return value } + var plugins = this.state.plugins; + if (plugins) { for (var i = 0; i < plugins.length; i++) { + var prop$1 = plugins[i].props[propName]; + if (prop$1 != null && (value = f ? f(prop$1) : prop$1)) { return value } + } } + }; + + // :: () → bool + // Query whether the view has focus. + EditorView.prototype.hasFocus = function hasFocus () { + return this.root.activeElement == this.dom + }; + + // :: () + // Focus the editor. + EditorView.prototype.focus = function focus () { + this.domObserver.stop(); + if (this.editable) { focusPreventScroll(this.dom); } + selectionToDOM(this); + this.domObserver.start(); + }; + + // :: union + // Get the document root in which the editor exists. This will + // usually be the top-level `document`, but might be a [shadow + // DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM) + // root if the editor is inside one. + prototypeAccessors$2$1.root.get = function () { + var cached = this._root; + if (cached == null) { for (var search = this.dom.parentNode; search; search = search.parentNode) { + if (search.nodeType == 9 || (search.nodeType == 11 && search.host)) { + if (!search.getSelection) { Object.getPrototypeOf(search).getSelection = function () { return document.getSelection(); }; } + return this._root = search + } + } } + return cached || document + }; + + // :: ({left: number, top: number}) → ?{pos: number, inside: number} + // Given a pair of viewport coordinates, return the document + // position that corresponds to them. May return null if the given + // coordinates aren't inside of the editor. When an object is + // returned, its `pos` property is the position nearest to the + // coordinates, and its `inside` property holds the position of the + // inner node that the position falls inside of, or -1 if it is at + // the top level, not in any node. + EditorView.prototype.posAtCoords = function posAtCoords$1 (coords) { + return posAtCoords(this, coords) + }; + + // :: (number, number) → {left: number, right: number, top: number, bottom: number} + // Returns the viewport rectangle at a given document position. + // `left` and `right` will be the same number, as this returns a + // flat cursor-ish rectangle. If the position is between two things + // that aren't directly adjacent, `side` determines which element is + // used. When < 0, the element before the position is used, + // otherwise the element after. + EditorView.prototype.coordsAtPos = function coordsAtPos$1 (pos, side) { + if ( side === void 0 ) side = 1; + + return coordsAtPos(this, pos, side) + }; + + // :: (number) → {node: dom.Node, offset: number} + // Find the DOM position that corresponds to the given document + // position. Note that you should **not** mutate the editor's + // internal DOM, only inspect it (and even that is usually not + // necessary). + EditorView.prototype.domAtPos = function domAtPos (pos) { + return this.docView.domFromPos(pos) + }; + + // :: (number) → ?dom.Node + // Find the DOM node that represents the document node after the + // given position. May return `null` when the position doesn't point + // in front of a node or if the node is inside an opaque node view. + // + // This is intended to be able to call things like + // `getBoundingClientRect` on that DOM node. Do **not** mutate the + // editor DOM directly, or add styling this way, since that will be + // immediately overriden by the editor as it redraws the node. + EditorView.prototype.nodeDOM = function nodeDOM (pos) { + var desc = this.docView.descAt(pos); + return desc ? desc.nodeDOM : null + }; + + // :: (dom.Node, number, ?number) → number + // Find the document position that corresponds to a given DOM + // position. (Whenever possible, it is preferable to inspect the + // document structure directly, rather than poking around in the + // DOM, but sometimes—for example when interpreting an event + // target—you don't have a choice.) + // + // The `bias` parameter can be used to influence which side of a DOM + // node to use when the position is inside a leaf node. + EditorView.prototype.posAtDOM = function posAtDOM (node, offset, bias) { + if ( bias === void 0 ) bias = -1; + + var pos = this.docView.posFromDOM(node, offset, bias); + if (pos == null) { throw new RangeError("DOM position not inside the editor") } + return pos + }; + + // :: (union<"up", "down", "left", "right", "forward", "backward">, ?EditorState) → bool + // Find out whether the selection is at the end of a textblock when + // moving in a given direction. When, for example, given `"left"`, + // it will return true if moving left from the current cursor + // position would leave that position's parent textblock. Will apply + // to the view's current state by default, but it is possible to + // pass a different state. + EditorView.prototype.endOfTextblock = function endOfTextblock$1 (dir, state) { + return endOfTextblock(this, state || this.state, dir) + }; + + // :: () + // Removes the editor from the DOM and destroys all [node + // views](#view.NodeView). + EditorView.prototype.destroy = function destroy () { + if (!this.docView) { return } + destroyInput(this); + this.destroyPluginViews(); + if (this.mounted) { + this.docView.update(this.state.doc, [], viewDecorations(this), this); + this.dom.textContent = ""; + } else if (this.dom.parentNode) { + this.dom.parentNode.removeChild(this.dom); + } + this.docView.destroy(); + this.docView = null; + }; + + // Used for testing. + EditorView.prototype.dispatchEvent = function dispatchEvent$1 (event) { + return dispatchEvent(this, event) + }; + + // :: (Transaction) + // Dispatch a transaction. Will call + // [`dispatchTransaction`](#view.DirectEditorProps.dispatchTransaction) + // when given, and otherwise defaults to applying the transaction to + // the current state and calling + // [`updateState`](#view.EditorView.updateState) with the result. + // This method is bound to the view instance, so that it can be + // easily passed around. + EditorView.prototype.dispatch = function dispatch (tr) { + var dispatchTransaction = this._props.dispatchTransaction; + if (dispatchTransaction) { dispatchTransaction.call(this, tr); } + else { this.updateState(this.state.apply(tr)); } + }; + + Object.defineProperties( EditorView.prototype, prototypeAccessors$2$1 ); + + function computeDocDeco(view) { + var attrs = Object.create(null); + attrs.class = "ProseMirror"; + attrs.contenteditable = String(view.editable); + + view.someProp("attributes", function (value) { + if (typeof value == "function") { value = value(view.state); } + if (value) { for (var attr in value) { + if (attr == "class") + { attrs.class += " " + value[attr]; } + else if (!attrs[attr] && attr != "contenteditable" && attr != "nodeName") + { attrs[attr] = String(value[attr]); } + } } + }); + + return [Decoration.node(0, view.state.doc.content.size, attrs)] + } + + function updateCursorWrapper(view) { + if (view.markCursor) { + var dom = document.createElement("img"); + dom.setAttribute("mark-placeholder", "true"); + view.cursorWrapper = {dom: dom, deco: Decoration.widget(view.state.selection.head, dom, {raw: true, marks: view.markCursor})}; + } else { + view.cursorWrapper = null; + } + } + + function getEditable(view) { + return !view.someProp("editable", function (value) { return value(view.state) === false; }) + } + + function selectionContextChanged(sel1, sel2) { + var depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head)); + return sel1.$anchor.start(depth) != sel2.$anchor.start(depth) + } + + function buildNodeViews(view) { + var result = {}; + view.someProp("nodeViews", function (obj) { + for (var prop in obj) { if (!Object.prototype.hasOwnProperty.call(result, prop)) + { result[prop] = obj[prop]; } } + }); + return result + } + + function changedNodeViews(a, b) { + var nA = 0, nB = 0; + for (var prop in a) { + if (a[prop] != b[prop]) { return true } + nA++; + } + for (var _ in b) { nB++; } + return nA != nB + } + + /** + * Efficient diffs. + * + * @module diff + */ + + /** + * A SimpleDiff describes a change on a String. + * + * ```js + * console.log(a) // the old value + * console.log(b) // the updated value + * // Apply changes of diff (pseudocode) + * a.remove(diff.index, diff.remove) // Remove `diff.remove` characters + * a.insert(diff.index, diff.insert) // Insert `diff.insert` + * a === b // values match + * ``` + * + * @typedef {Object} SimpleDiff + * @property {Number} index The index where changes were applied + * @property {Number} remove The number of characters to delete starting + * at `index`. + * @property {T} insert The new text to insert at `index` after applying + * `delete` + * + * @template T + */ + + /** + * Create a diff between two strings. This diff implementation is highly + * efficient, but not very sophisticated. + * + * @function + * + * @param {string} a The old version of the string + * @param {string} b The updated version of the string + * @return {SimpleDiff} The diff description. + */ + const simpleDiffString = (a, b) => { + let left = 0; // number of same characters counting from left + let right = 0; // number of same characters counting from right + while (left < a.length && left < b.length && a[left] === b[left]) { + left++; + } + if (left !== a.length || left !== b.length) { + // Only check right if a !== b + while (right + left < a.length && right + left < b.length && a[a.length - right - 1] === b[b.length - right - 1]) { + right++; + } + } + return { + index: left, + remove: a.length - left - right, + insert: b.slice(left, b.length - right) + } + }; + + /** + * @todo Remove in favor of simpleDiffString + * @deprecated + */ + const simpleDiff = simpleDiffString; + + /** + * The unique prosemirror plugin key for syncPlugin + * + * @public + */ + const ySyncPluginKey = new PluginKey('y-sync'); + + /** + * The unique prosemirror plugin key for undoPlugin + * + * @public + */ + const yUndoPluginKey = new PluginKey('y-undo'); + + /** + * The unique prosemirror plugin key for cursorPlugin + * + * @public + */ + const yCursorPluginKey = new PluginKey('yjs-cursor'); + + /** + * @module bindings/prosemirror + */ + + /** + * @param {Y.Item} item + * @param {Y.Snapshot} [snapshot] + */ + const isVisible$1 = (item, snapshot) => snapshot === undefined ? !item.deleted : (snapshot.sv.has(item.id.client) && /** @type {number} */ (snapshot.sv.get(item.id.client)) > item.id.clock && !isDeleted(snapshot.ds, item.id)); + + /** + * Either a node if type is YXmlElement or an Array of text nodes if YXmlText + * @typedef {Map>} ProsemirrorMapping + */ + + /** + * @typedef {Object} ColorDef + * @property {string} ColorDef.light + * @property {string} ColorDef.dark + */ + + /** + * @typedef {Object} YSyncOpts + * @property {Array} [YSyncOpts.colors] + * @property {Map} [YSyncOpts.colorMapping] + * @property {Y.PermanentUserData|null} [YSyncOpts.permanentUserData] + * @property {JSON|null} [YSyncOpts.initialContent] + */ + + /** + * @type {Array} + */ + const defaultColors = [{ light: '#ecd44433', dark: '#ecd444' }]; + + /** + * @param {Map} colorMapping + * @param {Array} colors + * @param {string} user + * @return {ColorDef} + */ + const getUserColor = (colorMapping, colors, user) => { + if (!colorMapping.has(user)) { + colorMapping.set(user, colors[colorMapping.size % colors.length]); + } + return /** @type {ColorDef} */ (colorMapping.get(user)); + }; + + /** + * This plugin listens to changes in prosemirror view and keeps yXmlState and view in sync. + * + * This plugin also keeps references to the type and the shared document so other plugins can access it. + * @param {Y.XmlFragment} yXmlFragment + * @param {YSyncOpts} opts + * @return {any} Returns a prosemirror plugin that binds to this type + */ + const ySyncPlugin = (yXmlFragment, { colors = defaultColors, colorMapping = new Map(), permanentUserData = null, initialContent = null } = {}) => { + let changedInitialContent = false; + const plugin = new Plugin({ + props: { + editable: (state) => { + const syncState = ySyncPluginKey.getState(state); + return syncState.snapshot == null && syncState.prevSnapshot == null + } + }, + key: ySyncPluginKey, + state: { + init: (initargs, state) => { + return { + type: yXmlFragment, + doc: yXmlFragment.doc, + binding: null, + snapshot: null, + prevSnapshot: null, + isChangeOrigin: false, + colors, + colorMapping, + permanentUserData + } + }, + apply: (tr, pluginState) => { + const change = tr.getMeta(ySyncPluginKey); + if (change !== undefined) { + pluginState = Object.assign({}, pluginState); + for (const key in change) { + pluginState[key] = change[key]; + } + } + // always set isChangeOrigin. If undefined, this is not change origin. + pluginState.isChangeOrigin = change !== undefined && !!change.isChangeOrigin; + if (pluginState.binding !== null) { + if (change !== undefined && (change.snapshot != null || change.prevSnapshot != null)) { + // snapshot changed, rerender next + setTimeout(() => { + if (change.restore == null) { + pluginState.binding._renderSnapshot(change.snapshot, change.prevSnapshot, pluginState); + } else { + pluginState.binding._renderSnapshot(change.snapshot, change.snapshot, pluginState); + // reset to current prosemirror state + delete pluginState.restore; + delete pluginState.snapshot; + delete pluginState.prevSnapshot; + pluginState.binding._prosemirrorChanged(pluginState.binding.prosemirrorView.state.doc); + } + }, 0); + } + } + return pluginState + } + }, + view: view => { + const binding = new ProsemirrorBinding(yXmlFragment, view); + binding._forceRerender(); + return { + update: () => { + const pluginState = plugin.getState(view.state); + if (pluginState.snapshot == null && pluginState.prevSnapshot == null) { + changedInitialContent = changedInitialContent || initialContent + ? view.state.doc.content.findDiffStart(view.state.schema.nodeFromJSON(initialContent)) !== null + : view.state.doc.content.findDiffStart(view.state.doc.type.createAndFill().content) !== null; + if (changedInitialContent) { + changedInitialContent = true; + binding._prosemirrorChanged(view.state.doc); + } + } + }, + destroy: () => { + binding.destroy(); + } + } + } + }); + return plugin + }; + + /** + * @param {any} tr + * @param {any} relSel + * @param {ProsemirrorBinding} binding + */ + const restoreRelativeSelection = (tr, relSel, binding) => { + if (relSel !== null && relSel.anchor !== null && relSel.head !== null) { + const anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping); + const head = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.head, binding.mapping); + if (anchor !== null && head !== null) { + tr = tr.setSelection(TextSelection.create(tr.doc, anchor, head)); + } + } + }; + + const getRelativeSelection = (pmbinding, state) => ({ + anchor: absolutePositionToRelativePosition(state.selection.anchor, pmbinding.type, pmbinding.mapping), + head: absolutePositionToRelativePosition(state.selection.head, pmbinding.type, pmbinding.mapping) + }); + + /** + * Binding for prosemirror. + * + * @protected + */ + class ProsemirrorBinding { + /** + * @param {Y.XmlFragment} yXmlFragment The bind source + * @param {any} prosemirrorView The target binding + */ + constructor (yXmlFragment, prosemirrorView) { + this.type = yXmlFragment; + this.prosemirrorView = prosemirrorView; + this.mux = createMutex(); + /** + * @type {ProsemirrorMapping} + */ + this.mapping = new Map(); + this._observeFunction = this._typeChanged.bind(this); + /** + * @type {Y.Doc} + */ + // @ts-ignore + this.doc = yXmlFragment.doc; + /** + * current selection as relative positions in the Yjs model + */ + this.beforeTransactionSelection = null; + this.beforeAllTransactions = () => { + if (this.beforeTransactionSelection === null) { + this.beforeTransactionSelection = getRelativeSelection(this, prosemirrorView.state); + } + }; + this.afterAllTransactions = () => { + this.beforeTransactionSelection = null; + }; + + this.doc.on('beforeAllTransactions', this.beforeAllTransactions); + this.doc.on('afterAllTransactions', this.afterAllTransactions); + yXmlFragment.observeDeep(this._observeFunction); + + this._domSelectionInView = null; + } + + _isLocalCursorInView () { + if (!this.prosemirrorView.hasFocus()) return false + if (isBrowser && this._domSelectionInView === null) { + // Calculate the domSelectionInView and clear by next tick after all events are finished + setTimeout(() => { + this._domSelectionInView = null; + }, 0); + this._domSelectionInView = this._isDomSelectionInView(); + } + return this._domSelectionInView + } + + _isDomSelectionInView () { + const selection = this.prosemirrorView._root.getSelection(); + + const range = this.prosemirrorView._root.createRange(); + range.setStart(selection.anchorNode, selection.anchorOffset); + range.setEnd(selection.focusNode, selection.focusOffset); + + // This is a workaround for an edgecase where getBoundingClientRect will + // return zero values if the selection is collapsed at the start of a newline + // see reference here: https://stackoverflow.com/a/59780954 + const rects = range.getClientRects(); + if (rects.length === 0) { + // probably buggy newline behavior, explicitly select the node contents + if (range.startContainer && range.collapsed) { + range.selectNodeContents(range.startContainer); + } + } + + const bounding = range.getBoundingClientRect(); + const documentElement = doc.documentElement; + + return bounding.bottom >= 0 && bounding.right >= 0 && + bounding.left <= (window.innerWidth || documentElement.clientWidth || 0) && + bounding.top <= (window.innerHeight || documentElement.clientHeight || 0) + } + + renderSnapshot (snapshot, prevSnapshot) { + if (!prevSnapshot) { + prevSnapshot = createSnapshot(createDeleteSet(), new Map()); + } + this.prosemirrorView.dispatch(this.prosemirrorView.state.tr.setMeta(ySyncPluginKey, { snapshot, prevSnapshot })); + } + + unrenderSnapshot () { + this.mapping = new Map(); + this.mux(() => { + const fragmentContent = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null); + // @ts-ignore + const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new Slice(new Fragment(fragmentContent), 0, 0)); + tr.setMeta(ySyncPluginKey, { snapshot: null, prevSnapshot: null }); + this.prosemirrorView.dispatch(tr); + }); + } + + _forceRerender () { + this.mapping = new Map(); + this.mux(() => { + // const fragmentContent = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null) + // @ts-ignore + // const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new PModel.Slice(new PModel.Fragment(fragmentContent), 0, 0)) const tr = this.prosemirrorView.state.tr + const tr = this.prosemirrorView.state.tr; + tr.setMeta(ySyncPluginKey, { binding: this }); + this.prosemirrorView.dispatch(tr); + }); + } + + /** + * @param {Y.Snapshot} snapshot + * @param {Y.Snapshot} prevSnapshot + * @param {Object} pluginState + */ + _renderSnapshot (snapshot$1, prevSnapshot, pluginState) { + if (!snapshot$1) { + snapshot$1 = snapshot(this.doc); + } + // clear mapping because we are going to rerender + this.mapping = new Map(); + this.mux(() => { + this.doc.transact(transaction => { + // before rendering, we are going to sanitize ops and split deleted ops + // if they were deleted by seperate users. + const pud = pluginState.permanentUserData; + if (pud) { + pud.dss.forEach(ds => { + iterateDeletedStructs(transaction, ds, item => {}); + }); + } + const computeYChange = (type, id) => { + const user = type === 'added' ? pud.getUserByClientId(id.client) : pud.getUserByDeletedId(id); + return { + user, + type, + color: getUserColor(pluginState.colorMapping, pluginState.colors, user) + } + }; + // Create document fragment and render + const fragmentContent = typeListToArraySnapshot(this.type, new Snapshot(prevSnapshot.ds, snapshot$1.sv)).map(t => { + if (!t._item.deleted || isVisible$1(t._item, snapshot$1) || isVisible$1(t._item, prevSnapshot)) { + return createNodeFromYElement(t, this.prosemirrorView.state.schema, new Map(), snapshot$1, prevSnapshot, computeYChange) + } else { + // No need to render elements that are not visible by either snapshot. + // If a client adds and deletes content in the same snapshot the element is not visible by either snapshot. + return null + } + }).filter(n => n !== null); + // @ts-ignore + const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new Slice(new Fragment(fragmentContent), 0, 0)); + this.prosemirrorView.dispatch(tr); + }, ySyncPluginKey); + }); + } + + /** + * @param {Array} events + * @param {Y.Transaction} transaction + */ + _typeChanged (events, transaction) { + const syncState = ySyncPluginKey.getState(this.prosemirrorView.state); + if (events.length === 0 || syncState.snapshot != null || syncState.prevSnapshot != null) { + // drop out if snapshot is active + this.renderSnapshot(syncState.snapshot, syncState.prevSnapshot); + return + } + this.mux(() => { + /** + * @param {any} _ + * @param {Y.AbstractType} type + */ + const delType = (_, type) => this.mapping.delete(type); + iterateDeletedStructs(transaction, transaction.deleteSet, struct => struct.constructor === Item && this.mapping.delete(/** @type {Y.ContentType} */ (/** @type {Y.Item} */ (struct).content).type)); + transaction.changed.forEach(delType); + transaction.changedParentTypes.forEach(delType); + const fragmentContent = this.type.toArray().map(t => createNodeIfNotExists(/** @type {Y.XmlElement | Y.XmlHook} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null); + // @ts-ignore + let tr = this.prosemirrorView.state.tr.replaceWith(0, this.prosemirrorView.state.doc.content.size, new Fragment(fragmentContent)); + restoreRelativeSelection(tr, this.beforeTransactionSelection, this); + tr = tr.setMeta(ySyncPluginKey, { isChangeOrigin: true }); + if (this.beforeTransactionSelection !== null && this._isLocalCursorInView()) { + tr.scrollIntoView(); + } + this.prosemirrorView.dispatch(tr); + }); + } + + _prosemirrorChanged (doc) { + this.mux(() => { + this.doc.transact(() => { + updateYFragment(this.doc, this.type, doc, this.mapping); + this.beforeTransactionSelection = getRelativeSelection(this, this.prosemirrorView.state); + }, ySyncPluginKey); + }); + } + + destroy () { + this.type.unobserveDeep(this._observeFunction); + this.doc.off('beforeAllTransactions', this.beforeAllTransactions); + this.doc.off('afterAllTransactions', this.afterAllTransactions); + } + } + + /** + * @private + * @param {Y.XmlElement | Y.XmlHook} el + * @param {PMSchema} schema + * @param {ProsemirrorMapping} mapping + * @param {Y.Snapshot} [snapshot] + * @param {Y.Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', Y.ID):any} [computeYChange] + * @return {PMNode | null} + */ + const createNodeIfNotExists = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => { + const node = /** @type {PMNode} */ (mapping.get(el)); + if (node === undefined) { + if (el instanceof YXmlElement) { + return createNodeFromYElement(el, schema, mapping, snapshot, prevSnapshot, computeYChange) + } else { + throw methodUnimplemented() // we are currently not handling hooks + } + } + return node + }; + + /** + * @private + * @param {Y.XmlElement} el + * @param {any} schema + * @param {ProsemirrorMapping} mapping + * @param {Y.Snapshot} [snapshot] + * @param {Y.Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', Y.ID):any} [computeYChange] + * @return {PMNode | null} Returns node if node could be created. Otherwise it deletes the yjs type and returns null + */ + const createNodeFromYElement = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => { + const children = []; + const createChildren = type => { + if (type.constructor === YXmlElement) { + const n = createNodeIfNotExists(type, schema, mapping, snapshot, prevSnapshot, computeYChange); + if (n !== null) { + children.push(n); + } + } else { + const ns = createTextNodesFromYText(type, schema, mapping, snapshot, prevSnapshot, computeYChange); + if (ns !== null) { + ns.forEach(textchild => { + if (textchild !== null) { + children.push(textchild); + } + }); + } + } + }; + if (snapshot === undefined || prevSnapshot === undefined) { + el.toArray().forEach(createChildren); + } else { + typeListToArraySnapshot(el, new Snapshot(prevSnapshot.ds, snapshot.sv)).forEach(createChildren); + } + try { + const attrs = el.getAttributes(snapshot); + if (snapshot !== undefined) { + if (!isVisible$1(/** @type {Y.Item} */ (el._item), snapshot)) { + attrs.ychange = computeYChange ? computeYChange('removed', /** @type {Y.Item} */ (el._item).id) : { type: 'removed' }; + } else if (!isVisible$1(/** @type {Y.Item} */ (el._item), prevSnapshot)) { + attrs.ychange = computeYChange ? computeYChange('added', /** @type {Y.Item} */ (el._item).id) : { type: 'added' }; + } + } + const node = schema.node(el.nodeName, attrs, children); + mapping.set(el, node); + return node + } catch (e) { + // an error occured while creating the node. This is probably a result of a concurrent action. + /** @type {Y.Doc} */ (el.doc).transact(transaction => { + /** @type {Y.Item} */ (el._item).delete(transaction); + }, ySyncPluginKey); + mapping.delete(el); + return null + } + }; + + /** + * @private + * @param {Y.XmlText} text + * @param {any} schema + * @param {ProsemirrorMapping} mapping + * @param {Y.Snapshot} [snapshot] + * @param {Y.Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', Y.ID):any} [computeYChange] + * @return {Array|null} + */ + const createTextNodesFromYText = (text, schema, mapping, snapshot, prevSnapshot, computeYChange) => { + const nodes = []; + const deltas = text.toDelta(snapshot, prevSnapshot, computeYChange); + try { + for (let i = 0; i < deltas.length; i++) { + const delta = deltas[i]; + const marks = []; + for (const markName in delta.attributes) { + marks.push(schema.mark(markName, delta.attributes[markName])); + } + nodes.push(schema.text(delta.insert, marks)); + } + } catch (e) { + // an error occured while creating the node. This is probably a result of a concurrent action. + /** @type {Y.Doc} */ (text.doc).transact(transaction => { + /** @type {Y.Item} */ (text._item).delete(transaction); + }, ySyncPluginKey); + return null + } + // @ts-ignore + return nodes + }; + + /** + * @private + * @param {Array} nodes prosemirror node + * @param {ProsemirrorMapping} mapping + * @return {Y.XmlText} + */ + const createTypeFromTextNodes = (nodes, mapping) => { + const type = new YXmlText(); + const delta = nodes.map(node => ({ + // @ts-ignore + insert: node.text, + attributes: marksToAttributes(node.marks) + })); + type.applyDelta(delta); + mapping.set(type, nodes); + return type + }; + + /** + * @private + * @param {any} node prosemirror node + * @param {ProsemirrorMapping} mapping + * @return {Y.XmlElement} + */ + const createTypeFromElementNode = (node, mapping) => { + const type = new YXmlElement(node.type.name); + for (const key in node.attrs) { + const val = node.attrs[key]; + if (val !== null && key !== 'ychange') { + type.setAttribute(key, val); + } + } + type.insert(0, normalizePNodeContent(node).map(n => createTypeFromTextOrElementNode(n, mapping))); + mapping.set(type, node); + return type + }; + + /** + * @private + * @param {PMNode|Array} node prosemirror text node + * @param {ProsemirrorMapping} mapping + * @return {Y.XmlElement|Y.XmlText} + */ + const createTypeFromTextOrElementNode = (node, mapping) => node instanceof Array ? createTypeFromTextNodes(node, mapping) : createTypeFromElementNode(node, mapping); + + const equalAttrs$1 = (pattrs, yattrs) => { + const keys = Object.keys(pattrs).filter(key => pattrs[key] !== null); + let eq = keys.length === Object.keys(yattrs).filter(key => yattrs[key] !== null).length; + for (let i = 0; i < keys.length && eq; i++) { + const key = keys[i]; + const l = pattrs[key]; + const r = yattrs[key]; + eq = key === 'ychange' || l === r || (typeof l === 'object' && typeof r === 'object' && equalAttrs$1(l, r)); + } + return eq + }; + + /** + * @typedef {Array|PMNode>} NormalizedPNodeContent + */ + + /** + * @param {any} pnode + * @return {NormalizedPNodeContent} + */ + const normalizePNodeContent = pnode => { + const c = pnode.content.content; + const res = []; + for (let i = 0; i < c.length; i++) { + const n = c[i]; + if (n.isText) { + const textNodes = []; + for (let tnode = c[i]; i < c.length && tnode.isText; tnode = c[++i]) { + textNodes.push(tnode); + } + i--; + res.push(textNodes); + } else { + res.push(n); + } + } + return res + }; + + /** + * @param {Y.XmlText} ytext + * @param {Array} ptexts + */ + const equalYTextPText = (ytext, ptexts) => { + const delta = ytext.toDelta(); + return delta.length === ptexts.length && delta.every((d, i) => d.insert === /** @type {any} */ (ptexts[i]).text && keys(d.attributes || {}).length === ptexts[i].marks.length && ptexts[i].marks.every(mark => equalAttrs$1(d.attributes[mark.type.name] || {}, mark.attrs))) + }; + + /** + * @param {Y.XmlElement|Y.XmlText|Y.XmlHook} ytype + * @param {any|Array} pnode + */ + const equalYTypePNode = (ytype, pnode) => { + if (ytype instanceof YXmlElement && !(pnode instanceof Array) && matchNodeName(ytype, pnode)) { + const normalizedContent = normalizePNodeContent(pnode); + return ytype._length === normalizedContent.length && equalAttrs$1(ytype.getAttributes(), pnode.attrs) && ytype.toArray().every((ychild, i) => equalYTypePNode(ychild, normalizedContent[i])) + } + return ytype instanceof YXmlText && pnode instanceof Array && equalYTextPText(ytype, pnode) + }; + + /** + * @param {PMNode | Array | undefined} mapped + * @param {PMNode | Array} pcontent + */ + const mappedIdentity = (mapped, pcontent) => mapped === pcontent || (mapped instanceof Array && pcontent instanceof Array && mapped.length === pcontent.length && mapped.every((a, i) => pcontent[i] === a)); + + /** + * @param {Y.XmlElement} ytype + * @param {PMNode} pnode + * @param {ProsemirrorMapping} mapping + * @return {{ foundMappedChild: boolean, equalityFactor: number }} + */ + const computeChildEqualityFactor = (ytype, pnode, mapping) => { + const yChildren = ytype.toArray(); + const pChildren = normalizePNodeContent(pnode); + const pChildCnt = pChildren.length; + const yChildCnt = yChildren.length; + const minCnt = min(yChildCnt, pChildCnt); + let left = 0; + let right = 0; + let foundMappedChild = false; + for (; left < minCnt; left++) { + const leftY = yChildren[left]; + const leftP = pChildren[left]; + if (mappedIdentity(mapping.get(leftY), leftP)) { + foundMappedChild = true;// definite (good) match! + } else if (!equalYTypePNode(leftY, leftP)) { + break + } + } + for (; left + right < minCnt; right++) { + const rightY = yChildren[yChildCnt - right - 1]; + const rightP = pChildren[pChildCnt - right - 1]; + if (mappedIdentity(mapping.get(rightY), rightP)) { + foundMappedChild = true; + } else if (!equalYTypePNode(rightY, rightP)) { + break + } + } + return { + equalityFactor: left + right, + foundMappedChild + } + }; + + const ytextTrans = ytext => { + let str = ''; + /** + * @type {Y.Item|null} + */ + let n = ytext._start; + const nAttrs = {}; + while (n !== null) { + if (!n.deleted) { + if (n.countable && n.content instanceof ContentString) { + str += n.content.str; + } else if (n.content instanceof ContentFormat) { + nAttrs[n.content.key] = null; + } + } + n = n.right; + } + return { + str, + nAttrs + } + }; + + /** + * @todo test this more + * + * @param {Y.Text} ytext + * @param {Array} ptexts + * @param {ProsemirrorMapping} mapping + */ + const updateYText = (ytext, ptexts, mapping) => { + mapping.set(ytext, ptexts); + const { nAttrs, str } = ytextTrans(ytext); + const content = ptexts.map(p => ({ insert: /** @type {any} */ (p).text, attributes: Object.assign({}, nAttrs, marksToAttributes(p.marks)) })); + const { insert, remove, index } = simpleDiff(str, content.map(c => c.insert).join('')); + ytext.delete(index, remove); + ytext.insert(index, insert); + ytext.applyDelta(content.map(c => ({ retain: c.insert.length, attributes: c.attributes }))); + }; + + const marksToAttributes = marks => { + const pattrs = {}; + marks.forEach(mark => { + if (mark.type.name !== 'ychange') { + pattrs[mark.type.name] = mark.attrs; + } + }); + return pattrs + }; + + /** + * @private + * @param {Y.Doc} y + * @param {Y.XmlFragment} yDomFragment + * @param {any} pNode + * @param {ProsemirrorMapping} mapping + */ + const updateYFragment = (y, yDomFragment, pNode, mapping) => { + if (yDomFragment instanceof YXmlElement && yDomFragment.nodeName !== pNode.type.name) { + throw new Error('node name mismatch!') + } + mapping.set(yDomFragment, pNode); + // update attributes + if (yDomFragment instanceof YXmlElement) { + const yDomAttrs = yDomFragment.getAttributes(); + const pAttrs = pNode.attrs; + for (const key in pAttrs) { + if (pAttrs[key] !== null) { + if (yDomAttrs[key] !== pAttrs[key] && key !== 'ychange') { + yDomFragment.setAttribute(key, pAttrs[key]); + } + } else { + yDomFragment.removeAttribute(key); + } + } + // remove all keys that are no longer in pAttrs + for (const key in yDomAttrs) { + if (pAttrs[key] === undefined) { + yDomFragment.removeAttribute(key); + } + } + } + // update children + const pChildren = normalizePNodeContent(pNode); + const pChildCnt = pChildren.length; + const yChildren = yDomFragment.toArray(); + const yChildCnt = yChildren.length; + const minCnt = min(pChildCnt, yChildCnt); + let left = 0; + let right = 0; + // find number of matching elements from left + for (;left < minCnt; left++) { + const leftY = yChildren[left]; + const leftP = pChildren[left]; + if (!mappedIdentity(mapping.get(leftY), leftP)) { + if (equalYTypePNode(leftY, leftP)) { + // update mapping + mapping.set(leftY, leftP); + } else { + break + } + } + } + // find number of matching elements from right + for (;right + left + 1 < minCnt; right++) { + const rightY = yChildren[yChildCnt - right - 1]; + const rightP = pChildren[pChildCnt - right - 1]; + if (!mappedIdentity(mapping.get(rightY), rightP)) { + if (equalYTypePNode(rightY, rightP)) { + // update mapping + mapping.set(rightY, rightP); + } else { + break + } + } + } + y.transact(() => { + // try to compare and update + while (yChildCnt - left - right > 0 && pChildCnt - left - right > 0) { + const leftY = yChildren[left]; + const leftP = pChildren[left]; + const rightY = yChildren[yChildCnt - right - 1]; + const rightP = pChildren[pChildCnt - right - 1]; + if (leftY instanceof YXmlText && leftP instanceof Array) { + if (!equalYTextPText(leftY, leftP)) { + updateYText(leftY, leftP, mapping); + } + left += 1; + } else { + let updateLeft = leftY instanceof YXmlElement && matchNodeName(leftY, leftP); + let updateRight = rightY instanceof YXmlElement && matchNodeName(rightY, rightP); + if (updateLeft && updateRight) { + // decide which which element to update + const equalityLeft = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (leftY), /** @type {PMNode} */ (leftP), mapping); + const equalityRight = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (rightY), /** @type {PMNode} */ (rightP), mapping); + if (equalityLeft.foundMappedChild && !equalityRight.foundMappedChild) { + updateRight = false; + } else if (!equalityLeft.foundMappedChild && equalityRight.foundMappedChild) { + updateLeft = false; + } else if (equalityLeft.equalityFactor < equalityRight.equalityFactor) { + updateLeft = false; + } else { + updateRight = false; + } + } + if (updateLeft) { + updateYFragment(y, /** @type {Y.XmlFragment} */ (leftY), /** @type {PMNode} */ (leftP), mapping); + left += 1; + } else if (updateRight) { + updateYFragment(y, /** @type {Y.XmlFragment} */ (rightY), /** @type {PMNode} */ (rightP), mapping); + right += 1; + } else { + yDomFragment.delete(left, 1); + yDomFragment.insert(left, [createTypeFromTextOrElementNode(leftP, mapping)]); + left += 1; + } + } + } + const yDelLen = yChildCnt - left - right; + if (yDelLen > 0) { + yDomFragment.delete(left, yDelLen); + } + if (left + right < pChildCnt) { + const ins = []; + for (let i = left; i < pChildCnt - right; i++) { + ins.push(createTypeFromTextOrElementNode(pChildren[i], mapping)); + } + yDomFragment.insert(left, ins); + } + }, ySyncPluginKey); + }; + + /** + * @function + * @param {Y.XmlElement} yElement + * @param {any} pNode Prosemirror Node + */ + const matchNodeName = (yElement, pNode) => !(pNode instanceof Array) && yElement.nodeName === pNode.type.name; + + /** + * Either a node if type is YXmlElement or an Array of text nodes if YXmlText + * @typedef {Map>} ProsemirrorMapping + */ + + /** + * Is null if no timeout is in progress. + * Is defined if a timeout is in progress. + * Maps from view + * @type {Map>|null} + */ + let viewsToUpdate = null; + + const updateMetas = () => { + const ups = /** @type {Map>} */ (viewsToUpdate); + viewsToUpdate = null; + ups.forEach((metas, view) => { + const tr = view.state.tr; + metas.forEach((val, key) => { + tr.setMeta(key, val); + }); + view.dispatch(tr); + }); + }; + + const setMeta = (view, key, value) => { + if (!viewsToUpdate) { + viewsToUpdate = new Map(); + timeout(0, updateMetas); + } + setIfUndefined(viewsToUpdate, view, create).set(key, value); + }; + + /** + * Transforms a Prosemirror based absolute position to a Yjs Cursor (relative position in the Yjs model). + * + * @param {number} pos + * @param {Y.XmlFragment} type + * @param {ProsemirrorMapping} mapping + * @return {any} relative position + */ + const absolutePositionToRelativePosition = (pos, type, mapping) => { + if (pos === 0) { + return createRelativePositionFromTypeIndex(type, 0) + } + let n = type._first === null ? null : /** @type {Y.ContentType} */ (type._first.content).type; + while (n !== null && type !== n) { + if (n.constructor === YXmlText) { + if (n._length >= pos) { + return createRelativePositionFromTypeIndex(n, pos) + } else { + pos -= n._length; + } + if (n._item !== null && n._item.next !== null) { + n = /** @type {Y.ContentType} */ (n._item.next.content).type; + } else { + do { + n = n._item === null ? null : n._item.parent; + pos--; + } while (n !== type && n !== null && n._item !== null && n._item.next === null) + if (n !== null && n !== type) { + // @ts-gnore we know that n.next !== null because of above loop conditition + n = n._item === null ? null : /** @type {Y.ContentType} */ (/** @type Y.Item */ (n._item.next).content).type; + } + } + } else { + const pNodeSize = /** @type {any} */ (mapping.get(n) || { nodeSize: 0 }).nodeSize; + if (n._first !== null && pos < pNodeSize) { + n = /** @type {Y.ContentType} */ (n._first.content).type; + pos--; + } else { + if (pos === 1 && n._length === 0 && pNodeSize > 1) { + // edge case, should end in this paragraph + return new RelativePosition(n._item === null ? null : n._item.id, n._item === null ? findRootTypeKey(n) : null, null) + } + pos -= pNodeSize; + if (n._item !== null && n._item.next !== null) { + n = /** @type {Y.ContentType} */ (n._item.next.content).type; + } else { + if (pos === 0) { + // set to end of n.parent + n = n._item === null ? n : n._item.parent; + return new RelativePosition(n._item === null ? null : n._item.id, n._item === null ? findRootTypeKey(n) : null, null) + } + do { + n = /** @type {Y.Item} */ (n._item).parent; + pos--; + } while (n !== type && /** @type {Y.Item} */ (n._item).next === null) + // if n is null at this point, we have an unexpected case + if (n !== type) { + // We know that n._item.next is defined because of above loop condition + n = /** @type {Y.ContentType} */ (/** @type {Y.Item} */ (/** @type {Y.Item} */ (n._item).next).content).type; + } + } + } + } + if (n === null) { + throw unexpectedCase() + } + if (pos === 0 && n.constructor !== YXmlText && n !== type) { // TODO: set to <= 0 + return createRelativePosition$1(n._item.parent, n._item) + } + } + return createRelativePositionFromTypeIndex(type, type._length) + }; + + const createRelativePosition$1 = (type, item) => { + let typeid = null; + let tname = null; + if (type._item === null) { + tname = findRootTypeKey(type); + } else { + typeid = createID(type._item.id.client, type._item.id.clock); + } + return new RelativePosition(typeid, tname, item.id) + }; + + /** + * @param {Y.Doc} y + * @param {Y.XmlFragment} documentType Top level type that is bound to pView + * @param {any} relPos Encoded Yjs based relative position + * @param {ProsemirrorMapping} mapping + * @return {null|number} + */ + const relativePositionToAbsolutePosition = (y, documentType, relPos, mapping) => { + const decodedPos = createAbsolutePositionFromRelativePosition(relPos, y); + if (decodedPos === null || (decodedPos.type !== documentType && !isParentOf(documentType, decodedPos.type._item))) { + return null + } + let type = decodedPos.type; + let pos = 0; + if (type.constructor === YXmlText) { + pos = decodedPos.index; + } else if (type._item === null || !type._item.deleted) { + let n = type._first; + let i = 0; + while (i < type._length && i < decodedPos.index && n !== null) { + if (!n.deleted) { + const t = /** @type {Y.ContentType} */ (n.content).type; + i++; + if (t.constructor === YXmlText) { + pos += t._length; + } else { + pos += /** @type {any} */ (mapping.get(t)).nodeSize; + } + } + n = /** @type {Y.Item} */ (n.right); + } + pos += 1; // increase because we go out of n + } + while (type !== documentType && type._item !== null) { + // @ts-ignore + const parent = type._item.parent; + // @ts-ignore + if (parent._item === null || !parent._item.deleted) { + pos += 1; // the start tag + let n = parent._first; + // now iterate until we found type + while (n !== null) { + const contentType = /** @type {Y.ContentType} */ (n.content).type; + if (contentType === type) { + break + } + if (!n.deleted) { + if (contentType.constructor === YXmlText) { + pos += contentType._length; + } else { + pos += /** @type {any} */ (mapping.get(contentType)).nodeSize; + } + } + n = n.right; + } + } + type = parent; + } + return pos - 1 // we don't count the most outer tag, because it is a fragment + }; + + /** + * Default generator for a cursor element + * + * @param {any} user user data + * @return HTMLElement + */ + const defaultCursorBuilder = user => { + const cursor = document.createElement('span'); + cursor.classList.add('ProseMirror-yjs-cursor'); + cursor.setAttribute('style', `border-color: ${user.color}`); + const userDiv = document.createElement('div'); + userDiv.setAttribute('style', `background-color: ${user.color}`); + userDiv.insertBefore(document.createTextNode(user.name), null); + cursor.insertBefore(userDiv, null); + return cursor + }; + + /** + * @param {any} state + * @param {Awareness} awareness + * @return {any} DecorationSet + */ + const createDecorations = (state, awareness, createCursor) => { + const ystate = ySyncPluginKey.getState(state); + const y = ystate.doc; + const decorations = []; + if (ystate.snapshot != null || ystate.prevSnapshot != null || ystate.binding === null) { + // do not render cursors while snapshot is active + return DecorationSet.create(state.doc, []) + } + awareness.getStates().forEach((aw, clientId) => { + if (clientId === y.clientID) { + return + } + if (aw.cursor != null) { + const user = aw.user || {}; + if (user.color == null) { + user.color = '#ffa500'; + } + if (user.name == null) { + user.name = `User: ${clientId}`; + } + let anchor = relativePositionToAbsolutePosition(y, ystate.type, createRelativePositionFromJSON(aw.cursor.anchor), ystate.binding.mapping); + let head = relativePositionToAbsolutePosition(y, ystate.type, createRelativePositionFromJSON(aw.cursor.head), ystate.binding.mapping); + if (anchor !== null && head !== null) { + const maxsize = max(state.doc.content.size - 1, 0); + anchor = min(anchor, maxsize); + head = min(head, maxsize); + decorations.push(Decoration.widget(head, () => createCursor(user), { key: clientId + '', side: 10 })); + const from = min(anchor, head); + const to = max(anchor, head); + decorations.push(Decoration.inline(from, to, { style: `background-color: ${user.color}70` }, { inclusiveEnd: true, inclusiveStart: false })); + } + } + }); + return DecorationSet.create(state.doc, decorations) + }; + + /** + * A prosemirror plugin that listens to awareness information on Yjs. + * This requires that a `prosemirrorPlugin` is also bound to the prosemirror. + * + * @public + * @param {Awareness} awareness + * @param {object} [opts] + * @param {function(any):HTMLElement} [opts.cursorBuilder] + * @param {function(any):any} [opts.getSelection] + * @param {string} [opts.cursorStateField] By default all editor bindings use the awareness 'cursor' field to propagate cursor information. + * @return {any} + */ + const yCursorPlugin = (awareness, { cursorBuilder = defaultCursorBuilder, getSelection = state => state.selection } = {}, cursorStateField = 'cursor') => new Plugin({ + key: yCursorPluginKey, + state: { + init (_, state) { + return createDecorations(state, awareness, cursorBuilder) + }, + apply (tr, prevState, oldState, newState) { + const ystate = ySyncPluginKey.getState(newState); + const yCursorState = tr.getMeta(yCursorPluginKey); + if ((ystate && ystate.isChangeOrigin) || (yCursorState && yCursorState.awarenessUpdated)) { + return createDecorations(newState, awareness, cursorBuilder) + } + return prevState.map(tr.mapping, tr.doc) + } + }, + props: { + decorations: state => { + return yCursorPluginKey.getState(state) + } + }, + view: view => { + const awarenessListener = () => { + // @ts-ignore + if (view.docView) { + setMeta(view, yCursorPluginKey, { awarenessUpdated: true }); + } + }; + const updateCursorInfo = () => { + const ystate = ySyncPluginKey.getState(view.state); + // @note We make implicit checks when checking for the cursor property + const current = awareness.getLocalState() || {}; + if (view.hasFocus() && ystate.binding !== null) { + const selection = getSelection(view.state); + /** + * @type {Y.RelativePosition} + */ + const anchor = absolutePositionToRelativePosition(selection.anchor, ystate.type, ystate.binding.mapping); + /** + * @type {Y.RelativePosition} + */ + const head = absolutePositionToRelativePosition(selection.head, ystate.type, ystate.binding.mapping); + if (current.cursor == null || !compareRelativePositions(createRelativePositionFromJSON(current.cursor.anchor), anchor) || !compareRelativePositions(createRelativePositionFromJSON(current.cursor.head), head)) { + awareness.setLocalStateField(cursorStateField, { + anchor, head + }); + } + } else if (current.cursor != null && relativePositionToAbsolutePosition(ystate.doc, ystate.type, createRelativePositionFromJSON(current.cursor.anchor), ystate.binding.mapping) !== null) { + // delete cursor information if current cursor information is owned by this editor binding + awareness.setLocalStateField(cursorStateField, null); + } + }; + awareness.on('change', awarenessListener); + view.dom.addEventListener('focusin', updateCursorInfo); + view.dom.addEventListener('focusout', updateCursorInfo); + return { + update: updateCursorInfo, + destroy: () => { + view.dom.removeEventListener('focusin', updateCursorInfo); + view.dom.removeEventListener('focusout', updateCursorInfo); + awareness.off('change', awarenessListener); + awareness.setLocalStateField(cursorStateField, null); + } + } + } + }); + + const undo = state => { + const undoManager = yUndoPluginKey.getState(state).undoManager; + if (undoManager != null) { + undoManager.undo(); + return true + } + }; + + const redo = state => { + const undoManager = yUndoPluginKey.getState(state).undoManager; + if (undoManager != null) { + undoManager.redo(); + return true + } + }; + + const yUndoPlugin = ({ protectedNodes = new Set(['paragraph']), trackedOrigins = [] } = {}) => new Plugin({ + key: yUndoPluginKey, + state: { + init: (initargs, state) => { + // TODO: check if plugin order matches and fix + const ystate = ySyncPluginKey.getState(state); + const undoManager = new UndoManager(ystate.type, { + trackedOrigins: new Set([ySyncPluginKey].concat(trackedOrigins)), + deleteFilter: item => !(item instanceof Item) || + !(item.content instanceof ContentType) || + !(item.content.type instanceof YText || + (item.content.type instanceof YXmlElement && protectedNodes.has(item.content.type.nodeName))) || + item.content.type._length === 0 + }); + return { + undoManager, + prevSel: null, + hasUndoOps: undoManager.undoStack.length > 0, + hasRedoOps: undoManager.redoStack.length > 0 + } + }, + apply: (tr, val, oldState, state) => { + const binding = ySyncPluginKey.getState(state).binding; + const undoManager = val.undoManager; + const hasUndoOps = undoManager.undoStack.length > 0; + const hasRedoOps = undoManager.redoStack.length > 0; + if (binding) { + return { + undoManager, + prevSel: getRelativeSelection(binding, oldState), + hasUndoOps, + hasRedoOps + } + } else { + if (hasUndoOps !== val.hasUndoOps || hasRedoOps !== val.hasRedoOps) { + return Object.assign({}, val, { + hasUndoOps: undoManager.undoStack.length > 0, + hasRedoOps: undoManager.redoStack.length > 0 + }) + } else { // nothing changed + return val + } + } + } + }, + view: view => { + const ystate = ySyncPluginKey.getState(view.state); + const undoManager = yUndoPluginKey.getState(view.state).undoManager; + undoManager.on('stack-item-added', ({ stackItem }) => { + const binding = ystate.binding; + if (binding) { + stackItem.meta.set(binding, yUndoPluginKey.getState(view.state).prevSel); + } + }); + undoManager.on('stack-item-popped', ({ stackItem }) => { + const binding = ystate.binding; + if (binding) { + binding.beforeTransactionSelection = stackItem.meta.get(binding) || binding.beforeTransactionSelection; + } + }); + return { + destroy: () => { + undoManager.destroy(); + } + } + } + }); + + const brDOM = ['br']; + + const calcYchangeDomAttrs = (attrs, domAttrs = {}) => { + domAttrs = Object.assign({}, domAttrs); + if (attrs.ychange !== null) { + domAttrs.ychange_user = attrs.ychange.user; + domAttrs.ychange_state = attrs.ychange.state; + } + return domAttrs + }; + + // :: Object + // [Specs](#model.NodeSpec) for the nodes defined in this schema. + const nodes = { + // :: NodeSpec The top level document node. + doc: { + content: 'block+' + }, + + // :: NodeSpec A plain paragraph textblock. Represented in the DOM + // as a `

` element. + paragraph: { + attrs: { ychange: { default: null } }, + content: 'inline*', + group: 'block', + parseDOM: [{ tag: 'p' }], + toDOM (node) { return ['p', calcYchangeDomAttrs(node.attrs), 0] } + }, + + // :: NodeSpec A blockquote (`

`) wrapping one or more blocks. + blockquote: { + attrs: { ychange: { default: null } }, + content: 'block+', + group: 'block', + defining: true, + parseDOM: [{ tag: 'blockquote' }], + toDOM (node) { return ['blockquote', calcYchangeDomAttrs(node.attrs), 0] } + }, + + // :: NodeSpec A horizontal rule (`
`). + horizontal_rule: { + attrs: { ychange: { default: null } }, + group: 'block', + parseDOM: [{ tag: 'hr' }], + toDOM (node) { + return ['hr', calcYchangeDomAttrs(node.attrs)] + } + }, + + // :: NodeSpec A heading textblock, with a `level` attribute that + // should hold the number 1 to 6. Parsed and serialized as `

` to + // `

` elements. + heading: { + attrs: { + level: { default: 1 }, + ychange: { default: null } + }, + content: 'inline*', + group: 'block', + defining: true, + parseDOM: [{ tag: 'h1', attrs: { level: 1 } }, + { tag: 'h2', attrs: { level: 2 } }, + { tag: 'h3', attrs: { level: 3 } }, + { tag: 'h4', attrs: { level: 4 } }, + { tag: 'h5', attrs: { level: 5 } }, + { tag: 'h6', attrs: { level: 6 } }], + toDOM (node) { return ['h' + node.attrs.level, calcYchangeDomAttrs(node.attrs), 0] } + }, + + // :: NodeSpec A code listing. Disallows marks or non-text inline + // nodes by default. Represented as a `
` element with a
+    // `` element inside of it.
+    code_block: {
+      attrs: { ychange: { default: null } },
+      content: 'text*',
+      marks: '',
+      group: 'block',
+      code: true,
+      defining: true,
+      parseDOM: [{ tag: 'pre', preserveWhitespace: 'full' }],
+      toDOM (node) { return ['pre', calcYchangeDomAttrs(node.attrs), ['code', 0]] }
+    },
+
+    // :: NodeSpec The text node.
+    text: {
+      group: 'inline'
+    },
+
+    // :: NodeSpec An inline image (``) node. Supports `src`,
+    // `alt`, and `href` attributes. The latter two default to the empty
+    // string.
+    image: {
+      inline: true,
+      attrs: {
+        ychange: { default: null },
+        src: {},
+        alt: { default: null },
+        title: { default: null }
+      },
+      group: 'inline',
+      draggable: true,
+      parseDOM: [{
+        tag: 'img[src]',
+        getAttrs (dom) {
+          return {
+            src: dom.getAttribute('src'),
+            title: dom.getAttribute('title'),
+            alt: dom.getAttribute('alt')
+          }
+        }
+      }],
+      toDOM (node) {
+        const domAttrs = {
+          src: node.attrs.src,
+          title: node.attrs.title,
+          alt: node.attrs.alt
+        };
+        return ['img', calcYchangeDomAttrs(node.attrs, domAttrs)]
+      }
+    },
+
+    // :: NodeSpec A hard line break, represented in the DOM as `
`. + hard_break: { + inline: true, + group: 'inline', + selectable: false, + parseDOM: [{ tag: 'br' }], + toDOM () { return brDOM } + } + }; + + const emDOM = ['em', 0]; const strongDOM = ['strong', 0]; const codeDOM = ['code', 0]; + + // :: Object [Specs](#model.MarkSpec) for the marks in the schema. + const marks = { + // :: MarkSpec A link. Has `href` and `title` attributes. `title` + // defaults to the empty string. Rendered and parsed as an `` + // element. + link: { + attrs: { + href: {}, + title: { default: null } + }, + inclusive: false, + parseDOM: [{ + tag: 'a[href]', + getAttrs (dom) { + return { href: dom.getAttribute('href'), title: dom.getAttribute('title') } + } + }], + toDOM (node) { return ['a', node.attrs, 0] } + }, + + // :: MarkSpec An emphasis mark. Rendered as an `` element. + // Has parse rules that also match `` and `font-style: italic`. + em: { + parseDOM: [{ tag: 'i' }, { tag: 'em' }, { style: 'font-style=italic' }], + toDOM () { return emDOM } + }, + + // :: MarkSpec A strong mark. Rendered as ``, parse rules + // also match `` and `font-weight: bold`. + strong: { + parseDOM: [{ tag: 'strong' }, + // This works around a Google Docs misbehavior where + // pasted content will be inexplicably wrapped in `` + // tags with a font-weight normal. + { tag: 'b', getAttrs: node => node.style.fontWeight !== 'normal' && null }, + { style: 'font-weight', getAttrs: value => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null }], + toDOM () { return strongDOM } + }, + + // :: MarkSpec Code font mark. Represented as a `` element. + code: { + parseDOM: [{ tag: 'code' }], + toDOM () { return codeDOM } + }, + ychange: { + attrs: { + user: { default: null }, + state: { default: null } + }, + inclusive: false, + parseDOM: [{ tag: 'ychange' }], + toDOM (node) { + return ['ychange', { ychange_user: node.attrs.user, ychange_state: node.attrs.state }, 0] + } + } + }; + + // :: Schema + // This schema rougly corresponds to the document schema used by + // [CommonMark](http://commonmark.org/), minus the list elements, + // which are defined in the [`prosemirror-schema-list`](#schema-list) + // module. + // + // To reuse elements from this schema, extend or read from its + // `spec.nodes` and `spec.marks` [properties](#model.Schema.spec). + const schema = new Schema({ nodes, marks }); + + var base = { + 8: "Backspace", + 9: "Tab", + 10: "Enter", + 12: "NumLock", + 13: "Enter", + 16: "Shift", + 17: "Control", + 18: "Alt", + 20: "CapsLock", + 27: "Escape", + 32: " ", + 33: "PageUp", + 34: "PageDown", + 35: "End", + 36: "Home", + 37: "ArrowLeft", + 38: "ArrowUp", + 39: "ArrowRight", + 40: "ArrowDown", + 44: "PrintScreen", + 45: "Insert", + 46: "Delete", + 59: ";", + 61: "=", + 91: "Meta", + 92: "Meta", + 106: "*", + 107: "+", + 108: ",", + 109: "-", + 110: ".", + 111: "/", + 144: "NumLock", + 145: "ScrollLock", + 160: "Shift", + 161: "Shift", + 162: "Control", + 163: "Control", + 164: "Alt", + 165: "Alt", + 173: "-", + 186: ";", + 187: "=", + 188: ",", + 189: "-", + 190: ".", + 191: "/", + 192: "`", + 219: "[", + 220: "\\", + 221: "]", + 222: "'", + 229: "q" + }; + + var shift = { + 48: ")", + 49: "!", + 50: "@", + 51: "#", + 52: "$", + 53: "%", + 54: "^", + 55: "&", + 56: "*", + 57: "(", + 59: ":", + 61: "+", + 173: "_", + 186: ":", + 187: "+", + 188: "<", + 189: "_", + 190: ">", + 191: "?", + 192: "~", + 219: "{", + 220: "|", + 221: "}", + 222: "\"", + 229: "Q" + }; + + var chrome$1 = typeof navigator != "undefined" && /Chrome\/(\d+)/.exec(navigator.userAgent); + var safari = typeof navigator != "undefined" && /Apple Computer/.test(navigator.vendor); + var gecko = typeof navigator != "undefined" && /Gecko\/\d+/.test(navigator.userAgent); + var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform); + var ie$1 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); + var brokenModifierNames = chrome$1 && (mac || +chrome$1[1] < 57) || gecko && mac; + + // Fill in the digit keys + for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i); + + // The function keys + for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i; + + // And the alphabetic keys + for (var i = 65; i <= 90; i++) { + base[i] = String.fromCharCode(i + 32); + shift[i] = String.fromCharCode(i); + } + + // For each code that doesn't have a shift-equivalent, copy the base name + for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]; + + function keyName(event) { + // Don't trust event.key in Chrome when there are modifiers until + // they fix https://bugs.chromium.org/p/chromium/issues/detail?id=633838 + var ignoreKey = brokenModifierNames && (event.ctrlKey || event.altKey || event.metaKey) || + (safari || ie$1) && event.shiftKey && event.key && event.key.length == 1; + var name = (!ignoreKey && event.key) || + (event.shiftKey ? shift : base)[event.keyCode] || + event.key || "Unidentified"; + // Edge sometimes produces wrong names (Issue #3) + if (name == "Esc") name = "Escape"; + if (name == "Del") name = "Delete"; + // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/ + if (name == "Left") name = "ArrowLeft"; + if (name == "Up") name = "ArrowUp"; + if (name == "Right") name = "ArrowRight"; + if (name == "Down") name = "ArrowDown"; + return name + } + + // declare global: navigator + + var mac$1 = typeof navigator != "undefined" ? /Mac/.test(navigator.platform) : false; + + function normalizeKeyName(name) { + var parts = name.split(/-(?!$)/), result = parts[parts.length - 1]; + if (result == "Space") { result = " "; } + var alt, ctrl, shift, meta; + for (var i = 0; i < parts.length - 1; i++) { + var mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) { meta = true; } + else if (/^a(lt)?$/i.test(mod)) { alt = true; } + else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; } + else if (/^s(hift)?$/i.test(mod)) { shift = true; } + else if (/^mod$/i.test(mod)) { if (mac$1) { meta = true; } else { ctrl = true; } } + else { throw new Error("Unrecognized modifier name: " + mod) } + } + if (alt) { result = "Alt-" + result; } + if (ctrl) { result = "Ctrl-" + result; } + if (meta) { result = "Meta-" + result; } + if (shift) { result = "Shift-" + result; } + return result + } + + function normalize(map) { + var copy = Object.create(null); + for (var prop in map) { copy[normalizeKeyName(prop)] = map[prop]; } + return copy + } + + function modifiers(name, event, shift) { + if (event.altKey) { name = "Alt-" + name; } + if (event.ctrlKey) { name = "Ctrl-" + name; } + if (event.metaKey) { name = "Meta-" + name; } + if (shift !== false && event.shiftKey) { name = "Shift-" + name; } + return name + } + + // :: (Object) → Plugin + // Create a keymap plugin for the given set of bindings. + // + // Bindings should map key names to [command](#commands)-style + // functions, which will be called with `(EditorState, dispatch, + // EditorView)` arguments, and should return true when they've handled + // the key. Note that the view argument isn't part of the command + // protocol, but can be used as an escape hatch if a binding needs to + // directly interact with the UI. + // + // Key names may be strings like `"Shift-Ctrl-Enter"`—a key + // identifier prefixed with zero or more modifiers. Key identifiers + // are based on the strings that can appear in + // [`KeyEvent.key`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key). + // Use lowercase letters to refer to letter keys (or uppercase letters + // if you want shift to be held). You may use `"Space"` as an alias + // for the `" "` name. + // + // Modifiers can be given in any order. `Shift-` (or `s-`), `Alt-` (or + // `a-`), `Ctrl-` (or `c-` or `Control-`) and `Cmd-` (or `m-` or + // `Meta-`) are recognized. For characters that are created by holding + // shift, the `Shift-` prefix is implied, and should not be added + // explicitly. + // + // You can use `Mod-` as a shorthand for `Cmd-` on Mac and `Ctrl-` on + // other platforms. + // + // You can add multiple keymap plugins to an editor. The order in + // which they appear determines their precedence (the ones early in + // the array get to dispatch first). + function keymap(bindings) { + return new Plugin({props: {handleKeyDown: keydownHandler(bindings)}}) + } + + // :: (Object) → (view: EditorView, event: dom.Event) → bool + // Given a set of bindings (using the same format as + // [`keymap`](#keymap.keymap), return a [keydown + // handler](#view.EditorProps.handleKeyDown) that handles them. + function keydownHandler(bindings) { + var map = normalize(bindings); + return function(view, event) { + var name = keyName(event), isChar = name.length == 1 && name != " ", baseName; + var direct = map[modifiers(name, event, !isChar)]; + if (direct && direct(view.state, view.dispatch, view)) { return true } + if (isChar && (event.shiftKey || event.altKey || event.metaKey || name.charCodeAt(0) > 127) && + (baseName = base[event.keyCode]) && baseName != name) { + // Try falling back to the keyCode when there's a modifier + // active or the character produced isn't ASCII, and our table + // produces a different name from the the keyCode. See #668, + // #1060 + var fromCode = map[modifiers(baseName, event, true)]; + if (fromCode && fromCode(view.state, view.dispatch, view)) { return true } + } else if (isChar && event.shiftKey) { + // Otherwise, if shift is active, also try the binding with the + // Shift- prefix enabled. See #997 + var withShift = map[modifiers(name, event, true)]; + if (withShift && withShift(view.state, view.dispatch, view)) { return true } + } + return false + } + } + + var GOOD_LEAF_SIZE = 200; + + // :: class A rope sequence is a persistent sequence data structure + // that supports appending, prepending, and slicing without doing a + // full copy. It is represented as a mostly-balanced tree. + var RopeSequence = function RopeSequence () {}; + + RopeSequence.prototype.append = function append (other) { + if (!other.length) { return this } + other = RopeSequence.from(other); + + return (!this.length && other) || + (other.length < GOOD_LEAF_SIZE && this.leafAppend(other)) || + (this.length < GOOD_LEAF_SIZE && other.leafPrepend(this)) || + this.appendInner(other) + }; + + // :: (union<[T], RopeSequence>) → RopeSequence + // Prepend an array or other rope to this one, returning a new rope. + RopeSequence.prototype.prepend = function prepend (other) { + if (!other.length) { return this } + return RopeSequence.from(other).append(this) + }; + + RopeSequence.prototype.appendInner = function appendInner (other) { + return new Append(this, other) + }; + + // :: (?number, ?number) → RopeSequence + // Create a rope repesenting a sub-sequence of this rope. + RopeSequence.prototype.slice = function slice (from, to) { + if ( from === void 0 ) from = 0; + if ( to === void 0 ) to = this.length; + + if (from >= to) { return RopeSequence.empty } + return this.sliceInner(Math.max(0, from), Math.min(this.length, to)) + }; + + // :: (number) → T + // Retrieve the element at the given position from this rope. + RopeSequence.prototype.get = function get (i) { + if (i < 0 || i >= this.length) { return undefined } + return this.getInner(i) + }; + + // :: ((element: T, index: number) → ?bool, ?number, ?number) + // Call the given function for each element between the given + // indices. This tends to be more efficient than looping over the + // indices and calling `get`, because it doesn't have to descend the + // tree for every element. + RopeSequence.prototype.forEach = function forEach (f, from, to) { + if ( from === void 0 ) from = 0; + if ( to === void 0 ) to = this.length; + + if (from <= to) + { this.forEachInner(f, from, to, 0); } + else + { this.forEachInvertedInner(f, from, to, 0); } + }; + + // :: ((element: T, index: number) → U, ?number, ?number) → [U] + // Map the given functions over the elements of the rope, producing + // a flat array. + RopeSequence.prototype.map = function map (f, from, to) { + if ( from === void 0 ) from = 0; + if ( to === void 0 ) to = this.length; + + var result = []; + this.forEach(function (elt, i) { return result.push(f(elt, i)); }, from, to); + return result + }; + + // :: (?union<[T], RopeSequence>) → RopeSequence + // Create a rope representing the given array, or return the rope + // itself if a rope was given. + RopeSequence.from = function from (values) { + if (values instanceof RopeSequence) { return values } + return values && values.length ? new Leaf(values) : RopeSequence.empty + }; + + var Leaf = /*@__PURE__*/(function (RopeSequence) { + function Leaf(values) { + RopeSequence.call(this); + this.values = values; + } + + if ( RopeSequence ) Leaf.__proto__ = RopeSequence; + Leaf.prototype = Object.create( RopeSequence && RopeSequence.prototype ); + Leaf.prototype.constructor = Leaf; + + var prototypeAccessors = { length: { configurable: true },depth: { configurable: true } }; + + Leaf.prototype.flatten = function flatten () { + return this.values + }; + + Leaf.prototype.sliceInner = function sliceInner (from, to) { + if (from == 0 && to == this.length) { return this } + return new Leaf(this.values.slice(from, to)) + }; + + Leaf.prototype.getInner = function getInner (i) { + return this.values[i] + }; + + Leaf.prototype.forEachInner = function forEachInner (f, from, to, start) { + for (var i = from; i < to; i++) + { if (f(this.values[i], start + i) === false) { return false } } + }; + + Leaf.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) { + for (var i = from - 1; i >= to; i--) + { if (f(this.values[i], start + i) === false) { return false } } + }; + + Leaf.prototype.leafAppend = function leafAppend (other) { + if (this.length + other.length <= GOOD_LEAF_SIZE) + { return new Leaf(this.values.concat(other.flatten())) } + }; + + Leaf.prototype.leafPrepend = function leafPrepend (other) { + if (this.length + other.length <= GOOD_LEAF_SIZE) + { return new Leaf(other.flatten().concat(this.values)) } + }; + + prototypeAccessors.length.get = function () { return this.values.length }; + + prototypeAccessors.depth.get = function () { return 0 }; + + Object.defineProperties( Leaf.prototype, prototypeAccessors ); + + return Leaf; + }(RopeSequence)); + + // :: RopeSequence + // The empty rope sequence. + RopeSequence.empty = new Leaf([]); + + var Append = /*@__PURE__*/(function (RopeSequence) { + function Append(left, right) { + RopeSequence.call(this); + this.left = left; + this.right = right; + this.length = left.length + right.length; + this.depth = Math.max(left.depth, right.depth) + 1; + } + + if ( RopeSequence ) Append.__proto__ = RopeSequence; + Append.prototype = Object.create( RopeSequence && RopeSequence.prototype ); + Append.prototype.constructor = Append; + + Append.prototype.flatten = function flatten () { + return this.left.flatten().concat(this.right.flatten()) + }; + + Append.prototype.getInner = function getInner (i) { + return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length) + }; + + Append.prototype.forEachInner = function forEachInner (f, from, to, start) { + var leftLen = this.left.length; + if (from < leftLen && + this.left.forEachInner(f, from, Math.min(to, leftLen), start) === false) + { return false } + if (to > leftLen && + this.right.forEachInner(f, Math.max(from - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false) + { return false } + }; + + Append.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) { + var leftLen = this.left.length; + if (from > leftLen && + this.right.forEachInvertedInner(f, from - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false) + { return false } + if (to < leftLen && + this.left.forEachInvertedInner(f, Math.min(from, leftLen), to, start) === false) + { return false } + }; + + Append.prototype.sliceInner = function sliceInner (from, to) { + if (from == 0 && to == this.length) { return this } + var leftLen = this.left.length; + if (to <= leftLen) { return this.left.slice(from, to) } + if (from >= leftLen) { return this.right.slice(from - leftLen, to - leftLen) } + return this.left.slice(from, leftLen).append(this.right.slice(0, to - leftLen)) + }; + + Append.prototype.leafAppend = function leafAppend (other) { + var inner = this.right.leafAppend(other); + if (inner) { return new Append(this.left, inner) } + }; + + Append.prototype.leafPrepend = function leafPrepend (other) { + var inner = this.left.leafPrepend(other); + if (inner) { return new Append(inner, this.right) } + }; + + Append.prototype.appendInner = function appendInner (other) { + if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1) + { return new Append(this.left, new Append(this.right, other)) } + return new Append(this, other) + }; + + return Append; + }(RopeSequence)); + + var ropeSequence = RopeSequence; + + // ProseMirror's history isn't simply a way to roll back to a previous + // state, because ProseMirror supports applying changes without adding + // them to the history (for example during collaboration). + // + // To this end, each 'Branch' (one for the undo history and one for + // the redo history) keeps an array of 'Items', which can optionally + // hold a step (an actual undoable change), and always hold a position + // map (which is needed to move changes below them to apply to the + // current document). + // + // An item that has both a step and a selection bookmark is the start + // of an 'event' — a group of changes that will be undone or redone at + // once. (It stores only the bookmark, since that way we don't have to + // provide a document until the selection is actually applied, which + // is useful when compressing.) + + // Used to schedule history compression + var max_empty_items = 500; + + var Branch = function Branch(items, eventCount) { + this.items = items; + this.eventCount = eventCount; + }; + + // : (EditorState, bool) → ?{transform: Transform, selection: ?SelectionBookmark, remaining: Branch} + // Pop the latest event off the branch's history and apply it + // to a document transform. + Branch.prototype.popEvent = function popEvent (state, preserveItems) { + var this$1 = this; + + if (this.eventCount == 0) { return null } + + var end = this.items.length; + for (;; end--) { + var next = this.items.get(end - 1); + if (next.selection) { --end; break } + } + + var remap, mapFrom; + if (preserveItems) { + remap = this.remapping(end, this.items.length); + mapFrom = remap.maps.length; + } + var transform = state.tr; + var selection, remaining; + var addAfter = [], addBefore = []; + + this.items.forEach(function (item, i) { + if (!item.step) { + if (!remap) { + remap = this$1.remapping(end, i + 1); + mapFrom = remap.maps.length; + } + mapFrom--; + addBefore.push(item); + return + } + + if (remap) { + addBefore.push(new Item$1(item.map)); + var step = item.step.map(remap.slice(mapFrom)), map; + + if (step && transform.maybeStep(step).doc) { + map = transform.mapping.maps[transform.mapping.maps.length - 1]; + addAfter.push(new Item$1(map, null, null, addAfter.length + addBefore.length)); + } + mapFrom--; + if (map) { remap.appendMap(map, mapFrom); } + } else { + transform.maybeStep(item.step); + } + + if (item.selection) { + selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection; + remaining = new Branch(this$1.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this$1.eventCount - 1); + return false + } + }, this.items.length, 0); + + return {remaining: remaining, transform: transform, selection: selection} + }; + + // : (Transform, ?SelectionBookmark, Object) → Branch + // Create a new branch with the given transform added. + Branch.prototype.addTransform = function addTransform (transform, selection, histOptions, preserveItems) { + var newItems = [], eventCount = this.eventCount; + var oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null; + + for (var i = 0; i < transform.steps.length; i++) { + var step = transform.steps[i].invert(transform.docs[i]); + var item = new Item$1(transform.mapping.maps[i], step, selection), merged = (void 0); + if (merged = lastItem && lastItem.merge(item)) { + item = merged; + if (i) { newItems.pop(); } + else { oldItems = oldItems.slice(0, oldItems.length - 1); } + } + newItems.push(item); + if (selection) { + eventCount++; + selection = null; + } + if (!preserveItems) { lastItem = item; } + } + var overflow = eventCount - histOptions.depth; + if (overflow > DEPTH_OVERFLOW) { + oldItems = cutOffEvents(oldItems, overflow); + eventCount -= overflow; + } + return new Branch(oldItems.append(newItems), eventCount) + }; + + Branch.prototype.remapping = function remapping (from, to) { + var maps = new Mapping; + this.items.forEach(function (item, i) { + var mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from + ? maps.maps.length - item.mirrorOffset : null; + maps.appendMap(item.map, mirrorPos); + }, from, to); + return maps + }; + + Branch.prototype.addMaps = function addMaps (array) { + if (this.eventCount == 0) { return this } + return new Branch(this.items.append(array.map(function (map) { return new Item$1(map); })), this.eventCount) + }; + + // : (Transform, number) + // When the collab module receives remote changes, the history has + // to know about those, so that it can adjust the steps that were + // rebased on top of the remote changes, and include the position + // maps for the remote changes in its array of items. + Branch.prototype.rebased = function rebased (rebasedTransform, rebasedCount) { + if (!this.eventCount) { return this } + + var rebasedItems = [], start = Math.max(0, this.items.length - rebasedCount); + + var mapping = rebasedTransform.mapping; + var newUntil = rebasedTransform.steps.length; + var eventCount = this.eventCount; + this.items.forEach(function (item) { if (item.selection) { eventCount--; } }, start); + + var iRebased = rebasedCount; + this.items.forEach(function (item) { + var pos = mapping.getMirror(--iRebased); + if (pos == null) { return } + newUntil = Math.min(newUntil, pos); + var map = mapping.maps[pos]; + if (item.step) { + var step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]); + var selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos)); + if (selection) { eventCount++; } + rebasedItems.push(new Item$1(map, step, selection)); + } else { + rebasedItems.push(new Item$1(map)); + } + }, start); + + var newMaps = []; + for (var i = rebasedCount; i < newUntil; i++) + { newMaps.push(new Item$1(mapping.maps[i])); } + var items = this.items.slice(0, start).append(newMaps).append(rebasedItems); + var branch = new Branch(items, eventCount); + + if (branch.emptyItemCount() > max_empty_items) + { branch = branch.compress(this.items.length - rebasedItems.length); } + return branch + }; + + Branch.prototype.emptyItemCount = function emptyItemCount () { + var count = 0; + this.items.forEach(function (item) { if (!item.step) { count++; } }); + return count + }; + + // Compressing a branch means rewriting it to push the air (map-only + // items) out. During collaboration, these naturally accumulate + // because each remote change adds one. The `upto` argument is used + // to ensure that only the items below a given level are compressed, + // because `rebased` relies on a clean, untouched set of items in + // order to associate old items with rebased steps. + Branch.prototype.compress = function compress (upto) { + if ( upto === void 0 ) upto = this.items.length; + + var remap = this.remapping(0, upto), mapFrom = remap.maps.length; + var items = [], events = 0; + this.items.forEach(function (item, i) { + if (i >= upto) { + items.push(item); + if (item.selection) { events++; } + } else if (item.step) { + var step = item.step.map(remap.slice(mapFrom)), map = step && step.getMap(); + mapFrom--; + if (map) { remap.appendMap(map, mapFrom); } + if (step) { + var selection = item.selection && item.selection.map(remap.slice(mapFrom)); + if (selection) { events++; } + var newItem = new Item$1(map.invert(), step, selection), merged, last = items.length - 1; + if (merged = items.length && items[last].merge(newItem)) + { items[last] = merged; } + else + { items.push(newItem); } + } + } else if (item.map) { + mapFrom--; + } + }, this.items.length, 0); + return new Branch(ropeSequence.from(items.reverse()), events) + }; + + Branch.empty = new Branch(ropeSequence.empty, 0); + + function cutOffEvents(items, n) { + var cutPoint; + items.forEach(function (item, i) { + if (item.selection && (n-- == 0)) { + cutPoint = i; + return false + } + }); + return items.slice(cutPoint) + } + + var Item$1 = function Item(map, step, selection, mirrorOffset) { + // The (forward) step map for this item. + this.map = map; + // The inverted step + this.step = step; + // If this is non-null, this item is the start of a group, and + // this selection is the starting selection for the group (the one + // that was active before the first step was applied) + this.selection = selection; + // If this item is the inverse of a previous mapping on the stack, + // this points at the inverse's offset + this.mirrorOffset = mirrorOffset; + }; + + Item$1.prototype.merge = function merge (other) { + if (this.step && other.step && !other.selection) { + var step = other.step.merge(this.step); + if (step) { return new Item$1(step.getMap().invert(), step, this.selection) } + } + }; + + // The value of the state field that tracks undo/redo history for that + // state. Will be stored in the plugin state when the history plugin + // is active. + var HistoryState = function HistoryState(done, undone, prevRanges, prevTime) { + this.done = done; + this.undone = undone; + this.prevRanges = prevRanges; + this.prevTime = prevTime; + }; + + var DEPTH_OVERFLOW = 20; + + // : (HistoryState, EditorState, Transaction, Object) + // Record a transformation in undo history. + function applyTransaction(history, state, tr, options) { + var historyTr = tr.getMeta(historyKey), rebased; + if (historyTr) { return historyTr.historyState } + + if (tr.getMeta(closeHistoryKey)) { history = new HistoryState(history.done, history.undone, null, 0); } + + var appended = tr.getMeta("appendedTransaction"); + + if (tr.steps.length == 0) { + return history + } else if (appended && appended.getMeta(historyKey)) { + if (appended.getMeta(historyKey).redo) + { return new HistoryState(history.done.addTransform(tr, null, options, mustPreserveItems(state)), + history.undone, rangesFor(tr.mapping.maps[tr.steps.length - 1]), history.prevTime) } + else + { return new HistoryState(history.done, history.undone.addTransform(tr, null, options, mustPreserveItems(state)), + null, history.prevTime) } + } else if (tr.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) { + // Group transforms that occur in quick succession into one event. + var newGroup = history.prevTime == 0 || !appended && (history.prevTime < (tr.time || 0) - options.newGroupDelay || + !isAdjacentTo(tr, history.prevRanges)); + var prevRanges = appended ? mapRanges(history.prevRanges, tr.mapping) : rangesFor(tr.mapping.maps[tr.steps.length - 1]); + return new HistoryState(history.done.addTransform(tr, newGroup ? state.selection.getBookmark() : null, + options, mustPreserveItems(state)), + Branch.empty, prevRanges, tr.time) + } else if (rebased = tr.getMeta("rebased")) { + // Used by the collab module to tell the history that some of its + // content has been rebased. + return new HistoryState(history.done.rebased(tr, rebased), + history.undone.rebased(tr, rebased), + mapRanges(history.prevRanges, tr.mapping), history.prevTime) + } else { + return new HistoryState(history.done.addMaps(tr.mapping.maps), + history.undone.addMaps(tr.mapping.maps), + mapRanges(history.prevRanges, tr.mapping), history.prevTime) + } + } + + function isAdjacentTo(transform, prevRanges) { + if (!prevRanges) { return false } + if (!transform.docChanged) { return true } + var adjacent = false; + transform.mapping.maps[0].forEach(function (start, end) { + for (var i = 0; i < prevRanges.length; i += 2) + { if (start <= prevRanges[i + 1] && end >= prevRanges[i]) + { adjacent = true; } } + }); + return adjacent + } + + function rangesFor(map) { + var result = []; + map.forEach(function (_from, _to, from, to) { return result.push(from, to); }); + return result + } + + function mapRanges(ranges, mapping) { + if (!ranges) { return null } + var result = []; + for (var i = 0; i < ranges.length; i += 2) { + var from = mapping.map(ranges[i], 1), to = mapping.map(ranges[i + 1], -1); + if (from <= to) { result.push(from, to); } + } + return result + } + + // : (HistoryState, EditorState, (tr: Transaction), bool) + // Apply the latest event from one branch to the document and shift the event + // onto the other branch. + function histTransaction(history, state, dispatch, redo) { + var preserveItems = mustPreserveItems(state), histOptions = historyKey.get(state).spec.config; + var pop = (redo ? history.undone : history.done).popEvent(state, preserveItems); + if (!pop) { return } + + var selection = pop.selection.resolve(pop.transform.doc); + var added = (redo ? history.done : history.undone).addTransform(pop.transform, state.selection.getBookmark(), + histOptions, preserveItems); + + var newHist = new HistoryState(redo ? added : pop.remaining, redo ? pop.remaining : added, null, 0); + dispatch(pop.transform.setSelection(selection).setMeta(historyKey, {redo: redo, historyState: newHist}).scrollIntoView()); + } + + var cachedPreserveItems = false, cachedPreserveItemsPlugins = null; + // Check whether any plugin in the given state has a + // `historyPreserveItems` property in its spec, in which case we must + // preserve steps exactly as they came in, so that they can be + // rebased. + function mustPreserveItems(state) { + var plugins = state.plugins; + if (cachedPreserveItemsPlugins != plugins) { + cachedPreserveItems = false; + cachedPreserveItemsPlugins = plugins; + for (var i = 0; i < plugins.length; i++) { if (plugins[i].spec.historyPreserveItems) { + cachedPreserveItems = true; + break + } } + } + return cachedPreserveItems + } + + var historyKey = new PluginKey("history"); + var closeHistoryKey = new PluginKey("closeHistory"); + + // :: (?Object) → Plugin + // Returns a plugin that enables the undo history for an editor. The + // plugin will track undo and redo stacks, which can be used with the + // [`undo`](#history.undo) and [`redo`](#history.redo) commands. + // + // You can set an `"addToHistory"` [metadata + // property](#state.Transaction.setMeta) of `false` on a transaction + // to prevent it from being rolled back by undo. + // + // config::- + // Supports the following configuration options: + // + // depth:: ?number + // The amount of history events that are collected before the + // oldest events are discarded. Defaults to 100. + // + // newGroupDelay:: ?number + // The delay between changes after which a new group should be + // started. Defaults to 500 (milliseconds). Note that when changes + // aren't adjacent, a new group is always started. + function history(config) { + config = {depth: config && config.depth || 100, + newGroupDelay: config && config.newGroupDelay || 500}; + return new Plugin({ + key: historyKey, + + state: { + init: function init() { + return new HistoryState(Branch.empty, Branch.empty, null, 0) + }, + apply: function apply(tr, hist, state) { + return applyTransaction(hist, state, tr, config) + } + }, + + config: config + }) + } + + // :: (EditorState, ?(tr: Transaction)) → bool + // A command function that undoes the last change, if any. + function undo$1(state, dispatch) { + var hist = historyKey.getState(state); + if (!hist || hist.done.eventCount == 0) { return false } + if (dispatch) { histTransaction(hist, state, dispatch, false); } + return true + } + + // :: (EditorState, ?(tr: Transaction)) → bool + // A command function that redoes the last undone change, if any. + function redo$1(state, dispatch) { + var hist = historyKey.getState(state); + if (!hist || hist.undone.eventCount == 0) { return false } + if (dispatch) { histTransaction(hist, state, dispatch, true); } + return true + } + + // :: (EditorState, ?(tr: Transaction)) → bool + // Delete the selection, if there is one. + function deleteSelection(state, dispatch) { + if (state.selection.empty) { return false } + if (dispatch) { dispatch(state.tr.deleteSelection().scrollIntoView()); } + return true + } + + // :: (EditorState, ?(tr: Transaction), ?EditorView) → bool + // If the selection is empty and at the start of a textblock, try to + // reduce the distance between that block and the one before it—if + // there's a block directly before it that can be joined, join them. + // If not, try to move the selected block closer to the next one in + // the document structure by lifting it out of its parent or moving it + // into a parent of the previous block. Will use the view for accurate + // (bidi-aware) start-of-textblock detection if given. + function joinBackward(state, dispatch, view) { + var ref = state.selection; + var $cursor = ref.$cursor; + if (!$cursor || (view ? !view.endOfTextblock("backward", state) + : $cursor.parentOffset > 0)) + { return false } + + var $cut = findCutBefore($cursor); + + // If there is no node before this, try to lift + if (!$cut) { + var range = $cursor.blockRange(), target = range && liftTarget(range); + if (target == null) { return false } + if (dispatch) { dispatch(state.tr.lift(range, target).scrollIntoView()); } + return true + } + + var before = $cut.nodeBefore; + // Apply the joining algorithm + if (!before.type.spec.isolating && deleteBarrier(state, $cut, dispatch)) + { return true } + + // If the node below has no content and the node above is + // selectable, delete the node below and select the one above. + if ($cursor.parent.content.size == 0 && + (textblockAt(before, "end") || NodeSelection.isSelectable(before))) { + if (dispatch) { + var tr = state.tr.deleteRange($cursor.before(), $cursor.after()); + tr.setSelection(textblockAt(before, "end") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1) + : NodeSelection.create(tr.doc, $cut.pos - before.nodeSize)); + dispatch(tr.scrollIntoView()); + } + return true + } + + // If the node before is an atom, delete it + if (before.isAtom && $cut.depth == $cursor.depth - 1) { + if (dispatch) { dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView()); } + return true + } + + return false + } + + function textblockAt(node, side) { + for (; node; node = (side == "start" ? node.firstChild : node.lastChild)) + { if (node.isTextblock) { return true } } + return false + } + + // :: (EditorState, ?(tr: Transaction), ?EditorView) → bool + // When the selection is empty and at the start of a textblock, select + // the node before that textblock, if possible. This is intended to be + // bound to keys like backspace, after + // [`joinBackward`](#commands.joinBackward) or other deleting + // commands, as a fall-back behavior when the schema doesn't allow + // deletion at the selected point. + function selectNodeBackward(state, dispatch, view) { + var ref = state.selection; + var $head = ref.$head; + var empty = ref.empty; + var $cut = $head; + if (!empty) { return false } + + if ($head.parent.isTextblock) { + if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0) { return false } + $cut = findCutBefore($head); + } + var node = $cut && $cut.nodeBefore; + if (!node || !NodeSelection.isSelectable(node)) { return false } + if (dispatch) + { dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView()); } + return true + } + + function findCutBefore($pos) { + if (!$pos.parent.type.spec.isolating) { for (var i = $pos.depth - 1; i >= 0; i--) { + if ($pos.index(i) > 0) { return $pos.doc.resolve($pos.before(i + 1)) } + if ($pos.node(i).type.spec.isolating) { break } + } } + return null + } + + // :: (EditorState, ?(tr: Transaction), ?EditorView) → bool + // If the selection is empty and the cursor is at the end of a + // textblock, try to reduce or remove the boundary between that block + // and the one after it, either by joining them or by moving the other + // block closer to this one in the tree structure. Will use the view + // for accurate start-of-textblock detection if given. + function joinForward(state, dispatch, view) { + var ref = state.selection; + var $cursor = ref.$cursor; + if (!$cursor || (view ? !view.endOfTextblock("forward", state) + : $cursor.parentOffset < $cursor.parent.content.size)) + { return false } + + var $cut = findCutAfter($cursor); + + // If there is no node after this, there's nothing to do + if (!$cut) { return false } + + var after = $cut.nodeAfter; + // Try the joining algorithm + if (deleteBarrier(state, $cut, dispatch)) { return true } + + // If the node above has no content and the node below is + // selectable, delete the node above and select the one below. + if ($cursor.parent.content.size == 0 && + (textblockAt(after, "start") || NodeSelection.isSelectable(after))) { + if (dispatch) { + var tr = state.tr.deleteRange($cursor.before(), $cursor.after()); + tr.setSelection(textblockAt(after, "start") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1) + : NodeSelection.create(tr.doc, tr.mapping.map($cut.pos))); + dispatch(tr.scrollIntoView()); + } + return true + } + + // If the next node is an atom, delete it + if (after.isAtom && $cut.depth == $cursor.depth - 1) { + if (dispatch) { dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView()); } + return true + } + + return false + } + + // :: (EditorState, ?(tr: Transaction), ?EditorView) → bool + // When the selection is empty and at the end of a textblock, select + // the node coming after that textblock, if possible. This is intended + // to be bound to keys like delete, after + // [`joinForward`](#commands.joinForward) and similar deleting + // commands, to provide a fall-back behavior when the schema doesn't + // allow deletion at the selected point. + function selectNodeForward(state, dispatch, view) { + var ref = state.selection; + var $head = ref.$head; + var empty = ref.empty; + var $cut = $head; + if (!empty) { return false } + if ($head.parent.isTextblock) { + if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size) + { return false } + $cut = findCutAfter($head); + } + var node = $cut && $cut.nodeAfter; + if (!node || !NodeSelection.isSelectable(node)) { return false } + if (dispatch) + { dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView()); } + return true + } + + function findCutAfter($pos) { + if (!$pos.parent.type.spec.isolating) { for (var i = $pos.depth - 1; i >= 0; i--) { + var parent = $pos.node(i); + if ($pos.index(i) + 1 < parent.childCount) { return $pos.doc.resolve($pos.after(i + 1)) } + if (parent.type.spec.isolating) { break } + } } + return null + } + + // :: (EditorState, ?(tr: Transaction)) → bool + // Join the selected block or, if there is a text selection, the + // closest ancestor block of the selection that can be joined, with + // the sibling above it. + function joinUp(state, dispatch) { + var sel = state.selection, nodeSel = sel instanceof NodeSelection, point; + if (nodeSel) { + if (sel.node.isTextblock || !canJoin(state.doc, sel.from)) { return false } + point = sel.from; + } else { + point = joinPoint(state.doc, sel.from, -1); + if (point == null) { return false } + } + if (dispatch) { + var tr = state.tr.join(point); + if (nodeSel) { tr.setSelection(NodeSelection.create(tr.doc, point - state.doc.resolve(point).nodeBefore.nodeSize)); } + dispatch(tr.scrollIntoView()); + } + return true + } + + // :: (EditorState, ?(tr: Transaction)) → bool + // Join the selected block, or the closest ancestor of the selection + // that can be joined, with the sibling after it. + function joinDown(state, dispatch) { + var sel = state.selection, point; + if (sel instanceof NodeSelection) { + if (sel.node.isTextblock || !canJoin(state.doc, sel.to)) { return false } + point = sel.to; + } else { + point = joinPoint(state.doc, sel.to, 1); + if (point == null) { return false } + } + if (dispatch) + { dispatch(state.tr.join(point).scrollIntoView()); } + return true + } + + // :: (EditorState, ?(tr: Transaction)) → bool + // Lift the selected block, or the closest ancestor block of the + // selection that can be lifted, out of its parent node. + function lift(state, dispatch) { + var ref = state.selection; + var $from = ref.$from; + var $to = ref.$to; + var range = $from.blockRange($to), target = range && liftTarget(range); + if (target == null) { return false } + if (dispatch) { dispatch(state.tr.lift(range, target).scrollIntoView()); } + return true + } + + // :: (EditorState, ?(tr: Transaction)) → bool + // If the selection is in a node whose type has a truthy + // [`code`](#model.NodeSpec.code) property in its spec, replace the + // selection with a newline character. + function newlineInCode(state, dispatch) { + var ref = state.selection; + var $head = ref.$head; + var $anchor = ref.$anchor; + if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) { return false } + if (dispatch) { dispatch(state.tr.insertText("\n").scrollIntoView()); } + return true + } + + function defaultBlockAt(match) { + for (var i = 0; i < match.edgeCount; i++) { + var ref = match.edge(i); + var type = ref.type; + if (type.isTextblock && !type.hasRequiredAttrs()) { return type } + } + return null + } + + // :: (EditorState, ?(tr: Transaction)) → bool + // When the selection is in a node with a truthy + // [`code`](#model.NodeSpec.code) property in its spec, create a + // default block after the code block, and move the cursor there. + function exitCode(state, dispatch) { + var ref = state.selection; + var $head = ref.$head; + var $anchor = ref.$anchor; + if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) { return false } + var above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after)); + if (!above.canReplaceWith(after, after, type)) { return false } + if (dispatch) { + var pos = $head.after(), tr = state.tr.replaceWith(pos, pos, type.createAndFill()); + tr.setSelection(Selection.near(tr.doc.resolve(pos), 1)); + dispatch(tr.scrollIntoView()); + } + return true + } + + // :: (EditorState, ?(tr: Transaction)) → bool + // If a block node is selected, create an empty paragraph before (if + // it is its parent's first child) or after it. + function createParagraphNear(state, dispatch) { + var ref = state.selection; + var $from = ref.$from; + var $to = ref.$to; + if ($from.parent.inlineContent || $to.parent.inlineContent) { return false } + var type = defaultBlockAt($from.parent.contentMatchAt($to.indexAfter())); + if (!type || !type.isTextblock) { return false } + if (dispatch) { + var side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos; + var tr = state.tr.insert(side, type.createAndFill()); + tr.setSelection(TextSelection.create(tr.doc, side + 1)); + dispatch(tr.scrollIntoView()); + } + return true + } + + // :: (EditorState, ?(tr: Transaction)) → bool + // If the cursor is in an empty textblock that can be lifted, lift the + // block. + function liftEmptyBlock(state, dispatch) { + var ref = state.selection; + var $cursor = ref.$cursor; + if (!$cursor || $cursor.parent.content.size) { return false } + if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) { + var before = $cursor.before(); + if (canSplit(state.doc, before)) { + if (dispatch) { dispatch(state.tr.split(before).scrollIntoView()); } + return true + } + } + var range = $cursor.blockRange(), target = range && liftTarget(range); + if (target == null) { return false } + if (dispatch) { dispatch(state.tr.lift(range, target).scrollIntoView()); } + return true + } + + // :: (EditorState, ?(tr: Transaction)) → bool + // Split the parent block of the selection. If the selection is a text + // selection, also delete its content. + function splitBlock(state, dispatch) { + var ref = state.selection; + var $from = ref.$from; + var $to = ref.$to; + if (state.selection instanceof NodeSelection && state.selection.node.isBlock) { + if (!$from.parentOffset || !canSplit(state.doc, $from.pos)) { return false } + if (dispatch) { dispatch(state.tr.split($from.pos).scrollIntoView()); } + return true + } + + if (!$from.parent.isBlock) { return false } + + if (dispatch) { + var atEnd = $to.parentOffset == $to.parent.content.size; + var tr = state.tr; + if (state.selection instanceof TextSelection) { tr.deleteSelection(); } + var deflt = $from.depth == 0 ? null : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1))); + var types = atEnd && deflt ? [{type: deflt}] : null; + var can = canSplit(tr.doc, tr.mapping.map($from.pos), 1, types); + if (!types && !can && canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt && [{type: deflt}])) { + types = [{type: deflt}]; + can = true; + } + if (can) { + tr.split(tr.mapping.map($from.pos), 1, types); + if (!atEnd && !$from.parentOffset && $from.parent.type != deflt && + $from.node(-1).canReplace($from.index(-1), $from.indexAfter(-1), Fragment.from(deflt.create(), $from.parent))) + { tr.setNodeMarkup(tr.mapping.map($from.before()), deflt); } + } + dispatch(tr.scrollIntoView()); + } + return true + } + + // :: (EditorState, ?(tr: Transaction)) → bool + // Move the selection to the node wrapping the current selection, if + // any. (Will not select the document node.) + function selectParentNode(state, dispatch) { + var ref = state.selection; + var $from = ref.$from; + var to = ref.to; + var pos; + var same = $from.sharedDepth(to); + if (same == 0) { return false } + pos = $from.before(same); + if (dispatch) { dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos))); } + return true + } + + // :: (EditorState, ?(tr: Transaction)) → bool + // Select the whole document. + function selectAll(state, dispatch) { + if (dispatch) { dispatch(state.tr.setSelection(new AllSelection(state.doc))); } + return true + } + + function joinMaybeClear(state, $pos, dispatch) { + var before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index(); + if (!before || !after || !before.type.compatibleContent(after.type)) { return false } + if (!before.content.size && $pos.parent.canReplace(index - 1, index)) { + if (dispatch) { dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView()); } + return true + } + if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos))) + { return false } + if (dispatch) + { dispatch(state.tr + .clearIncompatible($pos.pos, before.type, before.contentMatchAt(before.childCount)) + .join($pos.pos) + .scrollIntoView()); } + return true + } + + function deleteBarrier(state, $cut, dispatch) { + var before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match; + if (before.type.spec.isolating || after.type.spec.isolating) { return false } + if (joinMaybeClear(state, $cut, dispatch)) { return true } + + if ($cut.parent.canReplace($cut.index(), $cut.index() + 1) && + (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) && + match.matchType(conn[0] || after.type).validEnd) { + if (dispatch) { + var end = $cut.pos + after.nodeSize, wrap = Fragment.empty; + for (var i = conn.length - 1; i >= 0; i--) + { wrap = Fragment.from(conn[i].create(null, wrap)); } + wrap = Fragment.from(before.copy(wrap)); + var tr = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap, 1, 0), conn.length, true)); + var joinAt = end + 2 * conn.length; + if (canJoin(tr.doc, joinAt)) { tr.join(joinAt); } + dispatch(tr.scrollIntoView()); + } + return true + } + + var selAfter = Selection.findFrom($cut, 1); + var range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range); + if (target != null && target >= $cut.depth) { + if (dispatch) { dispatch(state.tr.lift(range, target).scrollIntoView()); } + return true + } + + return false + } + + // Parameterized commands + + // :: (NodeType, ?Object) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool + // Wrap the selection in a node of the given type with the given + // attributes. + function wrapIn(nodeType, attrs) { + return function(state, dispatch) { + var ref = state.selection; + var $from = ref.$from; + var $to = ref.$to; + var range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs); + if (!wrapping) { return false } + if (dispatch) { dispatch(state.tr.wrap(range, wrapping).scrollIntoView()); } + return true + } + } + + // :: (NodeType, ?Object) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool + // Returns a command that tries to set the selected textblocks to the + // given node type with the given attributes. + function setBlockType(nodeType, attrs) { + return function(state, dispatch) { + var ref = state.selection; + var from = ref.from; + var to = ref.to; + var applicable = false; + state.doc.nodesBetween(from, to, function (node, pos) { + if (applicable) { return false } + if (!node.isTextblock || node.hasMarkup(nodeType, attrs)) { return } + if (node.type == nodeType) { + applicable = true; + } else { + var $pos = state.doc.resolve(pos), index = $pos.index(); + applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType); + } + }); + if (!applicable) { return false } + if (dispatch) { dispatch(state.tr.setBlockType(from, to, nodeType, attrs).scrollIntoView()); } + return true + } + } + + function markApplies(doc, ranges, type) { + var loop = function ( i ) { + var ref = ranges[i]; + var $from = ref.$from; + var $to = ref.$to; + var can = $from.depth == 0 ? doc.type.allowsMarkType(type) : false; + doc.nodesBetween($from.pos, $to.pos, function (node) { + if (can) { return false } + can = node.inlineContent && node.type.allowsMarkType(type); + }); + if (can) { return { v: true } } + }; + + for (var i = 0; i < ranges.length; i++) { + var returned = loop( i ); + + if ( returned ) return returned.v; + } + return false + } + + // :: (MarkType, ?Object) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool + // Create a command function that toggles the given mark with the + // given attributes. Will return `false` when the current selection + // doesn't support that mark. This will remove the mark if any marks + // of that type exist in the selection, or add it otherwise. If the + // selection is empty, this applies to the [stored + // marks](#state.EditorState.storedMarks) instead of a range of the + // document. + function toggleMark(markType, attrs) { + return function(state, dispatch) { + var ref = state.selection; + var empty = ref.empty; + var $cursor = ref.$cursor; + var ranges = ref.ranges; + if ((empty && !$cursor) || !markApplies(state.doc, ranges, markType)) { return false } + if (dispatch) { + if ($cursor) { + if (markType.isInSet(state.storedMarks || $cursor.marks())) + { dispatch(state.tr.removeStoredMark(markType)); } + else + { dispatch(state.tr.addStoredMark(markType.create(attrs))); } + } else { + var has = false, tr = state.tr; + for (var i = 0; !has && i < ranges.length; i++) { + var ref$1 = ranges[i]; + var $from = ref$1.$from; + var $to = ref$1.$to; + has = state.doc.rangeHasMark($from.pos, $to.pos, markType); + } + for (var i$1 = 0; i$1 < ranges.length; i$1++) { + var ref$2 = ranges[i$1]; + var $from$1 = ref$2.$from; + var $to$1 = ref$2.$to; + if (has) { tr.removeMark($from$1.pos, $to$1.pos, markType); } + else { tr.addMark($from$1.pos, $to$1.pos, markType.create(attrs)); } + } + dispatch(tr.scrollIntoView()); + } + } + return true + } + } + + // :: (...[(EditorState, ?(tr: Transaction), ?EditorView) → bool]) → (EditorState, ?(tr: Transaction), ?EditorView) → bool + // Combine a number of command functions into a single function (which + // calls them one by one until one returns true). + function chainCommands() { + var commands = [], len = arguments.length; + while ( len-- ) commands[ len ] = arguments[ len ]; + + return function(state, dispatch, view) { + for (var i = 0; i < commands.length; i++) + { if (commands[i](state, dispatch, view)) { return true } } + return false + } + } + + var backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward); + var del = chainCommands(deleteSelection, joinForward, selectNodeForward); + + // :: Object + // A basic keymap containing bindings not specific to any schema. + // Binds the following keys (when multiple commands are listed, they + // are chained with [`chainCommands`](#commands.chainCommands)): + // + // * **Enter** to `newlineInCode`, `createParagraphNear`, `liftEmptyBlock`, `splitBlock` + // * **Mod-Enter** to `exitCode` + // * **Backspace** and **Mod-Backspace** to `deleteSelection`, `joinBackward`, `selectNodeBackward` + // * **Delete** and **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward` + // * **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward` + // * **Mod-a** to `selectAll` + var pcBaseKeymap = { + "Enter": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock), + "Mod-Enter": exitCode, + "Backspace": backspace, + "Mod-Backspace": backspace, + "Delete": del, + "Mod-Delete": del, + "Mod-a": selectAll + }; + + // :: Object + // A copy of `pcBaseKeymap` that also binds **Ctrl-h** like Backspace, + // **Ctrl-d** like Delete, **Alt-Backspace** like Ctrl-Backspace, and + // **Ctrl-Alt-Backspace**, **Alt-Delete**, and **Alt-d** like + // Ctrl-Delete. + var macBaseKeymap = { + "Ctrl-h": pcBaseKeymap["Backspace"], + "Alt-Backspace": pcBaseKeymap["Mod-Backspace"], + "Ctrl-d": pcBaseKeymap["Delete"], + "Ctrl-Alt-Backspace": pcBaseKeymap["Mod-Delete"], + "Alt-Delete": pcBaseKeymap["Mod-Delete"], + "Alt-d": pcBaseKeymap["Mod-Delete"] + }; + for (var key in pcBaseKeymap) { macBaseKeymap[key] = pcBaseKeymap[key]; } + + // declare global: os, navigator + var mac$2 = typeof navigator != "undefined" ? /Mac/.test(navigator.platform) + : typeof os != "undefined" ? os.platform() == "darwin" : false; + + // :: Object + // Depending on the detected platform, this will hold + // [`pcBasekeymap`](#commands.pcBaseKeymap) or + // [`macBaseKeymap`](#commands.macBaseKeymap). + var baseKeymap = mac$2 ? macBaseKeymap : pcBaseKeymap; + + // :: (options: ?Object) → Plugin + // Create a plugin that, when added to a ProseMirror instance, + // causes a decoration to show up at the drop position when something + // is dragged over the editor. + // + // options::- These options are supported: + // + // color:: ?string + // The color of the cursor. Defaults to `black`. + // + // width:: ?number + // The precise width of the cursor in pixels. Defaults to 1. + // + // class:: ?string + // A CSS class name to add to the cursor element. + function dropCursor(options) { + if ( options === void 0 ) options = {}; + + return new Plugin({ + view: function view(editorView) { return new DropCursorView(editorView, options) } + }) + } + + var DropCursorView = function DropCursorView(editorView, options) { + var this$1 = this; + + this.editorView = editorView; + this.width = options.width || 1; + this.color = options.color || "black"; + this.class = options.class; + this.cursorPos = null; + this.element = null; + this.timeout = null; + + this.handlers = ["dragover", "dragend", "drop", "dragleave"].map(function (name) { + var handler = function (e) { return this$1[name](e); }; + editorView.dom.addEventListener(name, handler); + return {name: name, handler: handler} + }); + }; + + DropCursorView.prototype.destroy = function destroy () { + var this$1 = this; + + this.handlers.forEach(function (ref) { + var name = ref.name; + var handler = ref.handler; + + return this$1.editorView.dom.removeEventListener(name, handler); + }); + }; + + DropCursorView.prototype.update = function update (editorView, prevState) { + if (this.cursorPos != null && prevState.doc != editorView.state.doc) { this.updateOverlay(); } + }; + + DropCursorView.prototype.setCursor = function setCursor (pos) { + if (pos == this.cursorPos) { return } + this.cursorPos = pos; + if (pos == null) { + this.element.parentNode.removeChild(this.element); + this.element = null; + } else { + this.updateOverlay(); + } + }; + + DropCursorView.prototype.updateOverlay = function updateOverlay () { + var $pos = this.editorView.state.doc.resolve(this.cursorPos), rect; + if (!$pos.parent.inlineContent) { + var before = $pos.nodeBefore, after = $pos.nodeAfter; + if (before || after) { + var nodeRect = this.editorView.nodeDOM(this.cursorPos - (before ?before.nodeSize : 0)).getBoundingClientRect(); + var top = before ? nodeRect.bottom : nodeRect.top; + if (before && after) + { top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2; } + rect = {left: nodeRect.left, right: nodeRect.right, top: top - this.width / 2, bottom: top + this.width / 2}; + } + } + if (!rect) { + var coords = this.editorView.coordsAtPos(this.cursorPos); + rect = {left: coords.left - this.width / 2, right: coords.left + this.width / 2, top: coords.top, bottom: coords.bottom}; + } + + var parent = this.editorView.dom.offsetParent; + if (!this.element) { + this.element = parent.appendChild(document.createElement("div")); + if (this.class) { this.element.className = this.class; } + this.element.style.cssText = "position: absolute; z-index: 50; pointer-events: none; background-color: " + this.color; + } + var parentRect = !parent || parent == document.body && getComputedStyle(parent).position == "static" + ? {left: -pageXOffset, top: -pageYOffset} : parent.getBoundingClientRect(); + this.element.style.left = (rect.left - parentRect.left) + "px"; + this.element.style.top = (rect.top - parentRect.top) + "px"; + this.element.style.width = (rect.right - rect.left) + "px"; + this.element.style.height = (rect.bottom - rect.top) + "px"; + }; + + DropCursorView.prototype.scheduleRemoval = function scheduleRemoval (timeout) { + var this$1 = this; + + clearTimeout(this.timeout); + this.timeout = setTimeout(function () { return this$1.setCursor(null); }, timeout); + }; + + DropCursorView.prototype.dragover = function dragover (event) { + if (!this.editorView.editable) { return } + var pos = this.editorView.posAtCoords({left: event.clientX, top: event.clientY}); + if (pos) { + var target = pos.pos; + if (this.editorView.dragging && this.editorView.dragging.slice) { + target = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice); + if (target == null) { target = pos.pos; } + } + this.setCursor(target); + this.scheduleRemoval(5000); + } + }; + + DropCursorView.prototype.dragend = function dragend () { + this.scheduleRemoval(20); + }; + + DropCursorView.prototype.drop = function drop () { + this.scheduleRemoval(20); + }; + + DropCursorView.prototype.dragleave = function dragleave (event) { + if (event.target == this.editorView.dom || !this.editorView.dom.contains(event.relatedTarget)) + { this.setCursor(null); } + }; + + // ::- Gap cursor selections are represented using this class. Its + // `$anchor` and `$head` properties both point at the cursor position. + var GapCursor = /*@__PURE__*/(function (Selection) { + function GapCursor($pos) { + Selection.call(this, $pos, $pos); + } + + if ( Selection ) GapCursor.__proto__ = Selection; + GapCursor.prototype = Object.create( Selection && Selection.prototype ); + GapCursor.prototype.constructor = GapCursor; + + GapCursor.prototype.map = function map (doc, mapping) { + var $pos = doc.resolve(mapping.map(this.head)); + return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos) + }; + + GapCursor.prototype.content = function content () { return Slice.empty }; + + GapCursor.prototype.eq = function eq (other) { + return other instanceof GapCursor && other.head == this.head + }; + + GapCursor.prototype.toJSON = function toJSON () { + return {type: "gapcursor", pos: this.head} + }; + + GapCursor.fromJSON = function fromJSON (doc, json) { + if (typeof json.pos != "number") { throw new RangeError("Invalid input for GapCursor.fromJSON") } + return new GapCursor(doc.resolve(json.pos)) + }; + + GapCursor.prototype.getBookmark = function getBookmark () { return new GapBookmark(this.anchor) }; + + GapCursor.valid = function valid ($pos) { + var parent = $pos.parent; + if (parent.isTextblock || !closedBefore($pos) || !closedAfter($pos)) { return false } + var override = parent.type.spec.allowGapCursor; + if (override != null) { return override } + var deflt = parent.contentMatchAt($pos.index()).defaultType; + return deflt && deflt.isTextblock + }; + + GapCursor.findFrom = function findFrom ($pos, dir, mustMove) { + search: for (;;) { + if (!mustMove && GapCursor.valid($pos)) { return $pos } + var pos = $pos.pos, next = null; + // Scan up from this position + for (var d = $pos.depth;; d--) { + var parent = $pos.node(d); + if (dir > 0 ? $pos.indexAfter(d) < parent.childCount : $pos.index(d) > 0) { + next = parent.child(dir > 0 ? $pos.indexAfter(d) : $pos.index(d) - 1); + break + } else if (d == 0) { + return null + } + pos += dir; + var $cur = $pos.doc.resolve(pos); + if (GapCursor.valid($cur)) { return $cur } + } + + // And then down into the next node + for (;;) { + var inside = dir > 0 ? next.firstChild : next.lastChild; + if (!inside) { + if (next.isAtom && !next.isText && !NodeSelection.isSelectable(next)) { + $pos = $pos.doc.resolve(pos + next.nodeSize * dir); + mustMove = false; + continue search + } + break + } + next = inside; + pos += dir; + var $cur$1 = $pos.doc.resolve(pos); + if (GapCursor.valid($cur$1)) { return $cur$1 } + } + + return null + } + }; + + return GapCursor; + }(Selection)); + + GapCursor.prototype.visible = false; + + Selection.jsonID("gapcursor", GapCursor); + + var GapBookmark = function GapBookmark(pos) { + this.pos = pos; + }; + GapBookmark.prototype.map = function map (mapping) { + return new GapBookmark(mapping.map(this.pos)) + }; + GapBookmark.prototype.resolve = function resolve (doc) { + var $pos = doc.resolve(this.pos); + return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos) + }; + + function closedBefore($pos) { + for (var d = $pos.depth; d >= 0; d--) { + var index = $pos.index(d); + // At the start of this parent, look at next one + if (index == 0) { continue } + // See if the node before (or its first ancestor) is closed + for (var before = $pos.node(d).child(index - 1);; before = before.lastChild) { + if ((before.childCount == 0 && !before.inlineContent) || before.isAtom || before.type.spec.isolating) { return true } + if (before.inlineContent) { return false } + } + } + // Hit start of document + return true + } + + function closedAfter($pos) { + for (var d = $pos.depth; d >= 0; d--) { + var index = $pos.indexAfter(d), parent = $pos.node(d); + if (index == parent.childCount) { continue } + for (var after = parent.child(index);; after = after.firstChild) { + if ((after.childCount == 0 && !after.inlineContent) || after.isAtom || after.type.spec.isolating) { return true } + if (after.inlineContent) { return false } + } + } + return true + } + + // :: () → Plugin + // Create a gap cursor plugin. When enabled, this will capture clicks + // near and arrow-key-motion past places that don't have a normally + // selectable position nearby, and create a gap cursor selection for + // them. The cursor is drawn as an element with class + // `ProseMirror-gapcursor`. You can either include + // `style/gapcursor.css` from the package's directory or add your own + // styles to make it visible. + var gapCursor = function() { + return new Plugin({ + props: { + decorations: drawGapCursor, + + createSelectionBetween: function createSelectionBetween(_view, $anchor, $head) { + if ($anchor.pos == $head.pos && GapCursor.valid($head)) { return new GapCursor($head) } + }, + + handleClick: handleClick, + handleKeyDown: handleKeyDown + } + }) + }; + + var handleKeyDown = keydownHandler({ + "ArrowLeft": arrow("horiz", -1), + "ArrowRight": arrow("horiz", 1), + "ArrowUp": arrow("vert", -1), + "ArrowDown": arrow("vert", 1) + }); + + function arrow(axis, dir) { + var dirStr = axis == "vert" ? (dir > 0 ? "down" : "up") : (dir > 0 ? "right" : "left"); + return function(state, dispatch, view) { + var sel = state.selection; + var $start = dir > 0 ? sel.$to : sel.$from, mustMove = sel.empty; + if (sel instanceof TextSelection) { + if (!view.endOfTextblock(dirStr) || $start.depth == 0) { return false } + mustMove = false; + $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before()); + } + var $found = GapCursor.findFrom($start, dir, mustMove); + if (!$found) { return false } + if (dispatch) { dispatch(state.tr.setSelection(new GapCursor($found))); } + return true + } + } + + function handleClick(view, pos, event) { + if (!view.editable) { return false } + var $pos = view.state.doc.resolve(pos); + if (!GapCursor.valid($pos)) { return false } + var ref = view.posAtCoords({left: event.clientX, top: event.clientY}); + var inside = ref.inside; + if (inside > -1 && NodeSelection.isSelectable(view.state.doc.nodeAt(inside))) { return false } + view.dispatch(view.state.tr.setSelection(new GapCursor($pos))); + return true + } + + function drawGapCursor(state) { + if (!(state.selection instanceof GapCursor)) { return null } + var node = document.createElement("div"); + node.className = "ProseMirror-gapcursor"; + return DecorationSet.create(state.doc, [Decoration.widget(state.selection.head, node, {key: "gapcursor"})]) + } + + function crelt() { + var elt = arguments[0]; + if (typeof elt == "string") elt = document.createElement(elt); + var i = 1, next = arguments[1]; + if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) { + for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) { + var value = next[name]; + if (typeof value == "string") elt.setAttribute(name, value); + else if (value != null) elt[name] = value; + } + i++; + } + for (; i < arguments.length; i++) add(elt, arguments[i]); + return elt + } + + function add(elt, child) { + if (typeof child == "string") { + elt.appendChild(document.createTextNode(child)); + } else if (child == null) ; else if (child.nodeType != null) { + elt.appendChild(child); + } else if (Array.isArray(child)) { + for (var i = 0; i < child.length; i++) add(elt, child[i]); + } else { + throw new RangeError("Unsupported child node: " + child) + } + } + + var SVG = "http://www.w3.org/2000/svg"; + var XLINK = "http://www.w3.org/1999/xlink"; + + var prefix = "ProseMirror-icon"; + + function hashPath(path) { + var hash = 0; + for (var i = 0; i < path.length; i++) + { hash = (((hash << 5) - hash) + path.charCodeAt(i)) | 0; } + return hash + } + + function getIcon(icon) { + var node = document.createElement("div"); + node.className = prefix; + if (icon.path) { + var name = "pm-icon-" + hashPath(icon.path).toString(16); + if (!document.getElementById(name)) { buildSVG(name, icon); } + var svg = node.appendChild(document.createElementNS(SVG, "svg")); + svg.style.width = (icon.width / icon.height) + "em"; + var use = svg.appendChild(document.createElementNS(SVG, "use")); + use.setAttributeNS(XLINK, "href", /([^#]*)/.exec(document.location)[1] + "#" + name); + } else if (icon.dom) { + node.appendChild(icon.dom.cloneNode(true)); + } else { + node.appendChild(document.createElement("span")).textContent = icon.text || ''; + if (icon.css) { node.firstChild.style.cssText = icon.css; } + } + return node + } + + function buildSVG(name, data) { + var collection = document.getElementById(prefix + "-collection"); + if (!collection) { + collection = document.createElementNS(SVG, "svg"); + collection.id = prefix + "-collection"; + collection.style.display = "none"; + document.body.insertBefore(collection, document.body.firstChild); + } + var sym = document.createElementNS(SVG, "symbol"); + sym.id = name; + sym.setAttribute("viewBox", "0 0 " + data.width + " " + data.height); + var path = sym.appendChild(document.createElementNS(SVG, "path")); + path.setAttribute("d", data.path); + collection.appendChild(sym); + } + + var prefix$1 = "ProseMirror-menu"; + + // ::- An icon or label that, when clicked, executes a command. + var MenuItem = function MenuItem(spec) { + // :: MenuItemSpec + // The spec used to create the menu item. + this.spec = spec; + }; + + // :: (EditorView) → {dom: dom.Node, update: (EditorState) → bool} + // Renders the icon according to its [display + // spec](#menu.MenuItemSpec.display), and adds an event handler which + // executes the command when the representation is clicked. + MenuItem.prototype.render = function render (view) { + var spec = this.spec; + var dom = spec.render ? spec.render(view) + : spec.icon ? getIcon(spec.icon) + : spec.label ? crelt("div", null, translate(view, spec.label)) + : null; + if (!dom) { throw new RangeError("MenuItem without icon or label property") } + if (spec.title) { + var title = (typeof spec.title === "function" ? spec.title(view.state) : spec.title); + dom.setAttribute("title", translate(view, title)); + } + if (spec.class) { dom.classList.add(spec.class); } + if (spec.css) { dom.style.cssText += spec.css; } + + dom.addEventListener("mousedown", function (e) { + e.preventDefault(); + if (!dom.classList.contains(prefix$1 + "-disabled")) + { spec.run(view.state, view.dispatch, view, e); } + }); + + function update(state) { + if (spec.select) { + var selected = spec.select(state); + dom.style.display = selected ? "" : "none"; + if (!selected) { return false } + } + var enabled = true; + if (spec.enable) { + enabled = spec.enable(state) || false; + setClass(dom, prefix$1 + "-disabled", !enabled); + } + if (spec.active) { + var active = enabled && spec.active(state) || false; + setClass(dom, prefix$1 + "-active", active); + } + return true + } + + return {dom: dom, update: update} + }; + + function translate(view, text) { + return view._props.translate ? view._props.translate(text) : text + } + + // MenuItemSpec:: interface + // The configuration object passed to the `MenuItem` constructor. + // + // run:: (EditorState, (Transaction), EditorView, dom.Event) + // The function to execute when the menu item is activated. + // + // select:: ?(EditorState) → bool + // Optional function that is used to determine whether the item is + // appropriate at the moment. Deselected items will be hidden. + // + // enable:: ?(EditorState) → bool + // Function that is used to determine if the item is enabled. If + // given and returning false, the item will be given a disabled + // styling. + // + // active:: ?(EditorState) → bool + // A predicate function to determine whether the item is 'active' (for + // example, the item for toggling the strong mark might be active then + // the cursor is in strong text). + // + // render:: ?(EditorView) → dom.Node + // A function that renders the item. You must provide either this, + // [`icon`](#menu.MenuItemSpec.icon), or [`label`](#MenuItemSpec.label). + // + // icon:: ?Object + // Describes an icon to show for this item. The object may specify + // an SVG icon, in which case its `path` property should be an [SVG + // path + // spec](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/d), + // and `width` and `height` should provide the viewbox in which that + // path exists. Alternatively, it may have a `text` property + // specifying a string of text that makes up the icon, with an + // optional `css` property giving additional CSS styling for the + // text. _Or_ it may contain `dom` property containing a DOM node. + // + // label:: ?string + // Makes the item show up as a text label. Mostly useful for items + // wrapped in a [drop-down](#menu.Dropdown) or similar menu. The object + // should have a `label` property providing the text to display. + // + // title:: ?union + // Defines DOM title (mouseover) text for the item. + // + // class:: ?string + // Optionally adds a CSS class to the item's DOM representation. + // + // css:: ?string + // Optionally adds a string of inline CSS to the item's DOM + // representation. + + var lastMenuEvent = {time: 0, node: null}; + function markMenuEvent(e) { + lastMenuEvent.time = Date.now(); + lastMenuEvent.node = e.target; + } + function isMenuEvent(wrapper) { + return Date.now() - 100 < lastMenuEvent.time && + lastMenuEvent.node && wrapper.contains(lastMenuEvent.node) + } + + // ::- A drop-down menu, displayed as a label with a downwards-pointing + // triangle to the right of it. + var Dropdown = function Dropdown(content, options) { + this.options = options || {}; + this.content = Array.isArray(content) ? content : [content]; + }; + + // :: (EditorView) → {dom: dom.Node, update: (EditorState)} + // Render the dropdown menu and sub-items. + Dropdown.prototype.render = function render (view) { + var this$1 = this; + + var content = renderDropdownItems(this.content, view); + + var label = crelt("div", {class: prefix$1 + "-dropdown " + (this.options.class || ""), + style: this.options.css}, + translate(view, this.options.label)); + if (this.options.title) { label.setAttribute("title", translate(view, this.options.title)); } + var wrap = crelt("div", {class: prefix$1 + "-dropdown-wrap"}, label); + var open = null, listeningOnClose = null; + var close = function () { + if (open && open.close()) { + open = null; + window.removeEventListener("mousedown", listeningOnClose); + } + }; + label.addEventListener("mousedown", function (e) { + e.preventDefault(); + markMenuEvent(e); + if (open) { + close(); + } else { + open = this$1.expand(wrap, content.dom); + window.addEventListener("mousedown", listeningOnClose = function () { + if (!isMenuEvent(wrap)) { close(); } + }); + } + }); + + function update(state) { + var inner = content.update(state); + wrap.style.display = inner ? "" : "none"; + return inner + } + + return {dom: wrap, update: update} + }; + + Dropdown.prototype.expand = function expand (dom, items) { + var menuDOM = crelt("div", {class: prefix$1 + "-dropdown-menu " + (this.options.class || "")}, items); + + var done = false; + function close() { + if (done) { return } + done = true; + dom.removeChild(menuDOM); + return true + } + dom.appendChild(menuDOM); + return {close: close, node: menuDOM} + }; + + function renderDropdownItems(items, view) { + var rendered = [], updates = []; + for (var i = 0; i < items.length; i++) { + var ref = items[i].render(view); + var dom = ref.dom; + var update = ref.update; + rendered.push(crelt("div", {class: prefix$1 + "-dropdown-item"}, dom)); + updates.push(update); + } + return {dom: rendered, update: combineUpdates(updates, rendered)} + } + + function combineUpdates(updates, nodes) { + return function (state) { + var something = false; + for (var i = 0; i < updates.length; i++) { + var up = updates[i](state); + nodes[i].style.display = up ? "" : "none"; + if (up) { something = true; } + } + return something + } + } + + // ::- Represents a submenu wrapping a group of elements that start + // hidden and expand to the right when hovered over or tapped. + var DropdownSubmenu = function DropdownSubmenu(content, options) { + this.options = options || {}; + this.content = Array.isArray(content) ? content : [content]; + }; + + // :: (EditorView) → {dom: dom.Node, update: (EditorState) → bool} + // Renders the submenu. + DropdownSubmenu.prototype.render = function render (view) { + var items = renderDropdownItems(this.content, view); + + var label = crelt("div", {class: prefix$1 + "-submenu-label"}, translate(view, this.options.label)); + var wrap = crelt("div", {class: prefix$1 + "-submenu-wrap"}, label, + crelt("div", {class: prefix$1 + "-submenu"}, items.dom)); + var listeningOnClose = null; + label.addEventListener("mousedown", function (e) { + e.preventDefault(); + markMenuEvent(e); + setClass(wrap, prefix$1 + "-submenu-wrap-active"); + if (!listeningOnClose) + { window.addEventListener("mousedown", listeningOnClose = function () { + if (!isMenuEvent(wrap)) { + wrap.classList.remove(prefix$1 + "-submenu-wrap-active"); + window.removeEventListener("mousedown", listeningOnClose); + listeningOnClose = null; + } + }); } + }); + + function update(state) { + var inner = items.update(state); + wrap.style.display = inner ? "" : "none"; + return inner + } + return {dom: wrap, update: update} + }; + + // :: (EditorView, [union]) → {dom: ?dom.DocumentFragment, update: (EditorState) → bool} + // Render the given, possibly nested, array of menu elements into a + // document fragment, placing separators between them (and ensuring no + // superfluous separators appear when some of the groups turn out to + // be empty). + function renderGrouped(view, content) { + var result = document.createDocumentFragment(); + var updates = [], separators = []; + for (var i = 0; i < content.length; i++) { + var items = content[i], localUpdates = [], localNodes = []; + for (var j = 0; j < items.length; j++) { + var ref = items[j].render(view); + var dom = ref.dom; + var update$1 = ref.update; + var span = crelt("span", {class: prefix$1 + "item"}, dom); + result.appendChild(span); + localNodes.push(span); + localUpdates.push(update$1); + } + if (localUpdates.length) { + updates.push(combineUpdates(localUpdates, localNodes)); + if (i < content.length - 1) + { separators.push(result.appendChild(separator())); } + } + } + + function update(state) { + var something = false, needSep = false; + for (var i = 0; i < updates.length; i++) { + var hasContent = updates[i](state); + if (i) { separators[i - 1].style.display = needSep && hasContent ? "" : "none"; } + needSep = hasContent; + if (hasContent) { something = true; } + } + return something + } + return {dom: result, update: update} + } + + function separator() { + return crelt("span", {class: prefix$1 + "separator"}) + } + + // :: Object + // A set of basic editor-related icons. Contains the properties + // `join`, `lift`, `selectParentNode`, `undo`, `redo`, `strong`, `em`, + // `code`, `link`, `bulletList`, `orderedList`, and `blockquote`, each + // holding an object that can be used as the `icon` option to + // `MenuItem`. + var icons = { + join: { + width: 800, height: 900, + path: "M0 75h800v125h-800z M0 825h800v-125h-800z M250 400h100v-100h100v100h100v100h-100v100h-100v-100h-100z" + }, + lift: { + width: 1024, height: 1024, + path: "M219 310v329q0 7-5 12t-12 5q-8 0-13-5l-164-164q-5-5-5-13t5-13l164-164q5-5 13-5 7 0 12 5t5 12zM1024 749v109q0 7-5 12t-12 5h-987q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h987q7 0 12 5t5 12zM1024 530v109q0 7-5 12t-12 5h-621q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h621q7 0 12 5t5 12zM1024 310v109q0 7-5 12t-12 5h-621q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h621q7 0 12 5t5 12zM1024 91v109q0 7-5 12t-12 5h-987q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h987q7 0 12 5t5 12z" + }, + selectParentNode: {text: "\u2b1a", css: "font-weight: bold"}, + undo: { + width: 1024, height: 1024, + path: "M761 1024c113-206 132-520-313-509v253l-384-384 384-384v248c534-13 594 472 313 775z" + }, + redo: { + width: 1024, height: 1024, + path: "M576 248v-248l384 384-384 384v-253c-446-10-427 303-313 509-280-303-221-789 313-775z" + }, + strong: { + width: 805, height: 1024, + path: "M317 869q42 18 80 18 214 0 214-191 0-65-23-102-15-25-35-42t-38-26-46-14-48-6-54-1q-41 0-57 5 0 30-0 90t-0 90q0 4-0 38t-0 55 2 47 6 38zM309 442q24 4 62 4 46 0 81-7t62-25 42-51 14-81q0-40-16-70t-45-46-61-24-70-8q-28 0-74 7 0 28 2 86t2 86q0 15-0 45t-0 45q0 26 0 39zM0 950l1-53q8-2 48-9t60-15q4-6 7-15t4-19 3-18 1-21 0-19v-37q0-561-12-585-2-4-12-8t-25-6-28-4-27-2-17-1l-2-47q56-1 194-6t213-5q13 0 39 0t38 0q40 0 78 7t73 24 61 40 42 59 16 78q0 29-9 54t-22 41-36 32-41 25-48 22q88 20 146 76t58 141q0 57-20 102t-53 74-78 48-93 27-100 8q-25 0-75-1t-75-1q-60 0-175 6t-132 6z" + }, + em: { + width: 585, height: 1024, + path: "M0 949l9-48q3-1 46-12t63-21q16-20 23-57 0-4 35-165t65-310 29-169v-14q-13-7-31-10t-39-4-33-3l10-58q18 1 68 3t85 4 68 1q27 0 56-1t69-4 56-3q-2 22-10 50-17 5-58 16t-62 19q-4 10-8 24t-5 22-4 26-3 24q-15 84-50 239t-44 203q-1 5-7 33t-11 51-9 47-3 32l0 10q9 2 105 17-1 25-9 56-6 0-18 0t-18 0q-16 0-49-5t-49-5q-78-1-117-1-29 0-81 5t-69 6z" + }, + code: { + width: 896, height: 1024, + path: "M608 192l-96 96 224 224-224 224 96 96 288-320-288-320zM288 192l-288 320 288 320 96-96-224-224 224-224-96-96z" + }, + link: { + width: 951, height: 1024, + path: "M832 694q0-22-16-38l-118-118q-16-16-38-16-24 0-41 18 1 1 10 10t12 12 8 10 7 14 2 15q0 22-16 38t-38 16q-8 0-15-2t-14-7-10-8-12-12-10-10q-18 17-18 41 0 22 16 38l117 118q15 15 38 15 22 0 38-14l84-83q16-16 16-38zM430 292q0-22-16-38l-117-118q-16-16-38-16-22 0-38 15l-84 83q-16 16-16 38 0 22 16 38l118 118q15 15 38 15 24 0 41-17-1-1-10-10t-12-12-8-10-7-14-2-15q0-22 16-38t38-16q8 0 15 2t14 7 10 8 12 12 10 10q18-17 18-41zM941 694q0 68-48 116l-84 83q-47 47-116 47-69 0-116-48l-117-118q-47-47-47-116 0-70 50-119l-50-50q-49 50-118 50-68 0-116-48l-118-118q-48-48-48-116t48-116l84-83q47-47 116-47 69 0 116 48l117 118q47 47 47 116 0 70-50 119l50 50q49-50 118-50 68 0 116 48l118 118q48 48 48 116z" + }, + bulletList: { + width: 768, height: 896, + path: "M0 512h128v-128h-128v128zM0 256h128v-128h-128v128zM0 768h128v-128h-128v128zM256 512h512v-128h-512v128zM256 256h512v-128h-512v128zM256 768h512v-128h-512v128z" + }, + orderedList: { + width: 768, height: 896, + path: "M320 512h448v-128h-448v128zM320 768h448v-128h-448v128zM320 128v128h448v-128h-448zM79 384h78v-256h-36l-85 23v50l43-2v185zM189 590c0-36-12-78-96-78-33 0-64 6-83 16l1 66c21-10 42-15 67-15s32 11 32 28c0 26-30 58-110 112v50h192v-67l-91 2c49-30 87-66 87-113l1-1z" + }, + blockquote: { + width: 640, height: 896, + path: "M0 448v256h256v-256h-128c0 0 0-128 128-128v-128c0 0-256 0-256 256zM640 320v-128c0 0-256 0-256 256v256h256v-256h-128c0 0 0-128 128-128z" + } + }; + + // :: MenuItem + // Menu item for the `joinUp` command. + var joinUpItem = new MenuItem({ + title: "Join with above block", + run: joinUp, + select: function (state) { return joinUp(state); }, + icon: icons.join + }); + + // :: MenuItem + // Menu item for the `lift` command. + var liftItem = new MenuItem({ + title: "Lift out of enclosing block", + run: lift, + select: function (state) { return lift(state); }, + icon: icons.lift + }); + + // :: MenuItem + // Menu item for the `selectParentNode` command. + var selectParentNodeItem = new MenuItem({ + title: "Select parent node", + run: selectParentNode, + select: function (state) { return selectParentNode(state); }, + icon: icons.selectParentNode + }); + + // :: MenuItem + // Menu item for the `undo` command. + var undoItem = new MenuItem({ + title: "Undo last change", + run: undo$1, + enable: function (state) { return undo$1(state); }, + icon: icons.undo + }); + + // :: MenuItem + // Menu item for the `redo` command. + var redoItem$1 = new MenuItem({ + title: "Redo last undone change", + run: redo$1, + enable: function (state) { return redo$1(state); }, + icon: icons.redo + }); + + // :: (NodeType, Object) → MenuItem + // Build a menu item for wrapping the selection in a given node type. + // Adds `run` and `select` properties to the ones present in + // `options`. `options.attrs` may be an object or a function. + function wrapItem(nodeType, options) { + var passedOptions = { + run: function run(state, dispatch) { + // FIXME if (options.attrs instanceof Function) options.attrs(state, attrs => wrapIn(nodeType, attrs)(state)) + return wrapIn(nodeType, options.attrs)(state, dispatch) + }, + select: function select(state) { + return wrapIn(nodeType, options.attrs instanceof Function ? null : options.attrs)(state) + } + }; + for (var prop in options) { passedOptions[prop] = options[prop]; } + return new MenuItem(passedOptions) + } + + // :: (NodeType, Object) → MenuItem + // Build a menu item for changing the type of the textblock around the + // selection to the given type. Provides `run`, `active`, and `select` + // properties. Others must be given in `options`. `options.attrs` may + // be an object to provide the attributes for the textblock node. + function blockTypeItem(nodeType, options) { + var command = setBlockType(nodeType, options.attrs); + var passedOptions = { + run: command, + enable: function enable(state) { return command(state) }, + active: function active(state) { + var ref = state.selection; + var $from = ref.$from; + var to = ref.to; + var node = ref.node; + if (node) { return node.hasMarkup(nodeType, options.attrs) } + return to <= $from.end() && $from.parent.hasMarkup(nodeType, options.attrs) + } + }; + for (var prop in options) { passedOptions[prop] = options[prop]; } + return new MenuItem(passedOptions) + } + + // Work around classList.toggle being broken in IE11 + function setClass(dom, cls, on) { + if (on) { dom.classList.add(cls); } + else { dom.classList.remove(cls); } + } + + var prefix$2 = "ProseMirror-menubar"; + + function isIOS() { + if (typeof navigator == "undefined") { return false } + var agent = navigator.userAgent; + return !/Edge\/\d/.test(agent) && /AppleWebKit/.test(agent) && /Mobile\/\w+/.test(agent) + } + + // :: (Object) → Plugin + // A plugin that will place a menu bar above the editor. Note that + // this involves wrapping the editor in an additional `
`. + // + // options::- + // Supports the following options: + // + // content:: [[MenuElement]] + // Provides the content of the menu, as a nested array to be + // passed to `renderGrouped`. + // + // floating:: ?bool + // Determines whether the menu floats, i.e. whether it sticks to + // the top of the viewport when the editor is partially scrolled + // out of view. + function menuBar(options) { + return new Plugin({ + view: function view(editorView) { return new MenuBarView(editorView, options) } + }) + } + + var MenuBarView = function MenuBarView(editorView, options) { + var this$1 = this; + + this.editorView = editorView; + this.options = options; + + this.wrapper = crelt("div", {class: prefix$2 + "-wrapper"}); + this.menu = this.wrapper.appendChild(crelt("div", {class: prefix$2})); + this.menu.className = prefix$2; + this.spacer = null; + + editorView.dom.parentNode.replaceChild(this.wrapper, editorView.dom); + this.wrapper.appendChild(editorView.dom); + + this.maxHeight = 0; + this.widthForMaxHeight = 0; + this.floating = false; + + var ref = renderGrouped(this.editorView, this.options.content); + var dom = ref.dom; + var update = ref.update; + this.contentUpdate = update; + this.menu.appendChild(dom); + this.update(); + + if (options.floating && !isIOS()) { + this.updateFloat(); + var potentialScrollers = getAllWrapping(this.wrapper); + this.scrollFunc = function (e) { + var root = this$1.editorView.root; + if (!(root.body || root).contains(this$1.wrapper)) { + potentialScrollers.forEach(function (el) { return el.removeEventListener("scroll", this$1.scrollFunc); }); + } else { + this$1.updateFloat(e.target.getBoundingClientRect && e.target); + } + }; + potentialScrollers.forEach(function (el) { return el.addEventListener('scroll', this$1.scrollFunc); }); + } + }; + + MenuBarView.prototype.update = function update () { + this.contentUpdate(this.editorView.state); + + if (this.floating) { + this.updateScrollCursor(); + } else { + if (this.menu.offsetWidth != this.widthForMaxHeight) { + this.widthForMaxHeight = this.menu.offsetWidth; + this.maxHeight = 0; + } + if (this.menu.offsetHeight > this.maxHeight) { + this.maxHeight = this.menu.offsetHeight; + this.menu.style.minHeight = this.maxHeight + "px"; + } + } + }; + + MenuBarView.prototype.updateScrollCursor = function updateScrollCursor () { + var selection = this.editorView.root.getSelection(); + if (!selection.focusNode) { return } + var rects = selection.getRangeAt(0).getClientRects(); + var selRect = rects[selectionIsInverted(selection) ? 0 : rects.length - 1]; + if (!selRect) { return } + var menuRect = this.menu.getBoundingClientRect(); + if (selRect.top < menuRect.bottom && selRect.bottom > menuRect.top) { + var scrollable = findWrappingScrollable(this.wrapper); + if (scrollable) { scrollable.scrollTop -= (menuRect.bottom - selRect.top); } + } + }; + + MenuBarView.prototype.updateFloat = function updateFloat (scrollAncestor) { + var parent = this.wrapper, editorRect = parent.getBoundingClientRect(), + top = scrollAncestor ? Math.max(0, scrollAncestor.getBoundingClientRect().top) : 0; + + if (this.floating) { + if (editorRect.top >= top || editorRect.bottom < this.menu.offsetHeight + 10) { + this.floating = false; + this.menu.style.position = this.menu.style.left = this.menu.style.top = this.menu.style.width = ""; + this.menu.style.display = ""; + this.spacer.parentNode.removeChild(this.spacer); + this.spacer = null; + } else { + var border = (parent.offsetWidth - parent.clientWidth) / 2; + this.menu.style.left = (editorRect.left + border) + "px"; + this.menu.style.display = (editorRect.top > window.innerHeight ? "none" : ""); + if (scrollAncestor) { this.menu.style.top = top + "px"; } + } + } else { + if (editorRect.top < top && editorRect.bottom >= this.menu.offsetHeight + 10) { + this.floating = true; + var menuRect = this.menu.getBoundingClientRect(); + this.menu.style.left = menuRect.left + "px"; + this.menu.style.width = menuRect.width + "px"; + if (scrollAncestor) { this.menu.style.top = top + "px"; } + this.menu.style.position = "fixed"; + this.spacer = crelt("div", {class: prefix$2 + "-spacer", style: ("height: " + (menuRect.height) + "px")}); + parent.insertBefore(this.spacer, this.menu); + } + } + }; + + MenuBarView.prototype.destroy = function destroy () { + if (this.wrapper.parentNode) + { this.wrapper.parentNode.replaceChild(this.editorView.dom, this.wrapper); } + }; + + // Not precise, but close enough + function selectionIsInverted(selection) { + if (selection.anchorNode == selection.focusNode) { return selection.anchorOffset > selection.focusOffset } + return selection.anchorNode.compareDocumentPosition(selection.focusNode) == Node.DOCUMENT_POSITION_FOLLOWING + } + + function findWrappingScrollable(node) { + for (var cur = node.parentNode; cur; cur = cur.parentNode) + { if (cur.scrollHeight > cur.clientHeight) { return cur } } + } + + function getAllWrapping(node) { + var res = [window]; + for (var cur = node.parentNode; cur; cur = cur.parentNode) + { res.push(cur); } + return res + } + + // :: (NodeType, ?Object) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool + // Returns a command function that wraps the selection in a list with + // the given type an attributes. If `dispatch` is null, only return a + // value to indicate whether this is possible, but don't actually + // perform the change. + function wrapInList(listType, attrs) { + return function(state, dispatch) { + var ref = state.selection; + var $from = ref.$from; + var $to = ref.$to; + var range = $from.blockRange($to), doJoin = false, outerRange = range; + if (!range) { return false } + // This is at the top of an existing list item + if (range.depth >= 2 && $from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) { + // Don't do anything if this is the top of the list + if ($from.index(range.depth - 1) == 0) { return false } + var $insert = state.doc.resolve(range.start - 2); + outerRange = new NodeRange($insert, $insert, range.depth); + if (range.endIndex < range.parent.childCount) + { range = new NodeRange($from, state.doc.resolve($to.end(range.depth)), range.depth); } + doJoin = true; + } + var wrap = findWrapping(outerRange, listType, attrs, range); + if (!wrap) { return false } + if (dispatch) { dispatch(doWrapInList(state.tr, range, wrap, doJoin, listType).scrollIntoView()); } + return true + } + } + + function doWrapInList(tr, range, wrappers, joinBefore, listType) { + var content = Fragment.empty; + for (var i = wrappers.length - 1; i >= 0; i--) + { content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content)); } + + tr.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, + new Slice(content, 0, 0), wrappers.length, true)); + + var found = 0; + for (var i$1 = 0; i$1 < wrappers.length; i$1++) { if (wrappers[i$1].type == listType) { found = i$1 + 1; } } + var splitDepth = wrappers.length - found; + + var splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent = range.parent; + for (var i$2 = range.startIndex, e = range.endIndex, first = true; i$2 < e; i$2++, first = false) { + if (!first && canSplit(tr.doc, splitPos, splitDepth)) { + tr.split(splitPos, splitDepth); + splitPos += 2 * splitDepth; + } + splitPos += parent.child(i$2).nodeSize; + } + return tr + } + + // :: (NodeType) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool + // Build a command that splits a non-empty textblock at the top level + // of a list item by also splitting that list item. + function splitListItem(itemType) { + return function(state, dispatch) { + var ref = state.selection; + var $from = ref.$from; + var $to = ref.$to; + var node = ref.node; + if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to)) { return false } + var grandParent = $from.node(-1); + if (grandParent.type != itemType) { return false } + if ($from.parent.content.size == 0 && $from.node(-1).childCount == $from.indexAfter(-1)) { + // In an empty block. If this is a nested list, the wrapping + // list item should be split. Otherwise, bail out and let next + // command handle lifting. + if ($from.depth == 2 || $from.node(-3).type != itemType || + $from.index(-2) != $from.node(-2).childCount - 1) { return false } + if (dispatch) { + var wrap = Fragment.empty, keepItem = $from.index(-1) > 0; + // Build a fragment containing empty versions of the structure + // from the outer list item to the parent node of the cursor + for (var d = $from.depth - (keepItem ? 1 : 2); d >= $from.depth - 3; d--) + { wrap = Fragment.from($from.node(d).copy(wrap)); } + // Add a second list item with an empty default start node + wrap = wrap.append(Fragment.from(itemType.createAndFill())); + var tr$1 = state.tr.replace($from.before(keepItem ? null : -1), $from.after(-3), new Slice(wrap, keepItem ? 3 : 2, 2)); + tr$1.setSelection(state.selection.constructor.near(tr$1.doc.resolve($from.pos + (keepItem ? 3 : 2)))); + dispatch(tr$1.scrollIntoView()); + } + return true + } + var nextType = $to.pos == $from.end() ? grandParent.contentMatchAt(0).defaultType : null; + var tr = state.tr.delete($from.pos, $to.pos); + var types = nextType && [null, {type: nextType}]; + if (!canSplit(tr.doc, $from.pos, 2, types)) { return false } + if (dispatch) { dispatch(tr.split($from.pos, 2, types).scrollIntoView()); } + return true + } + } + + // :: (NodeType) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool + // Create a command to lift the list item around the selection up into + // a wrapping list. + function liftListItem(itemType) { + return function(state, dispatch) { + var ref = state.selection; + var $from = ref.$from; + var $to = ref.$to; + var range = $from.blockRange($to, function (node) { return node.childCount && node.firstChild.type == itemType; }); + if (!range) { return false } + if (!dispatch) { return true } + if ($from.node(range.depth - 1).type == itemType) // Inside a parent list + { return liftToOuterList(state, dispatch, itemType, range) } + else // Outer list node + { return liftOutOfList(state, dispatch, range) } + } + } + + function liftToOuterList(state, dispatch, itemType, range) { + var tr = state.tr, end = range.end, endOfList = range.$to.end(range.depth); + if (end < endOfList) { + // There are siblings after the lifted items, which must become + // children of the last item + tr.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, + new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true)); + range = new NodeRange(tr.doc.resolve(range.$from.pos), tr.doc.resolve(endOfList), range.depth); + } + dispatch(tr.lift(range, liftTarget(range)).scrollIntoView()); + return true + } + + function liftOutOfList(state, dispatch, range) { + var tr = state.tr, list = range.parent; + // Merge the list items into a single big item + for (var pos = range.end, i = range.endIndex - 1, e = range.startIndex; i > e; i--) { + pos -= list.child(i).nodeSize; + tr.delete(pos - 1, pos + 1); + } + var $start = tr.doc.resolve(range.start), item = $start.nodeAfter; + var atStart = range.startIndex == 0, atEnd = range.endIndex == list.childCount; + var parent = $start.node(-1), indexBefore = $start.index(-1); + if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, + item.content.append(atEnd ? Fragment.empty : Fragment.from(list)))) + { return false } + var start = $start.pos, end = start + item.nodeSize; + // Strip off the surrounding list. At the sides where we're not at + // the end of the list, the existing list is closed. At sides where + // this is the end, it is overwritten to its end. + tr.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, + new Slice((atStart ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))) + .append(atEnd ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))), + atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1)); + dispatch(tr.scrollIntoView()); + return true + } + + // :: (NodeType) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool + // Create a command to sink the list item around the selection down + // into an inner list. + function sinkListItem(itemType) { + return function(state, dispatch) { + var ref = state.selection; + var $from = ref.$from; + var $to = ref.$to; + var range = $from.blockRange($to, function (node) { return node.childCount && node.firstChild.type == itemType; }); + if (!range) { return false } + var startIndex = range.startIndex; + if (startIndex == 0) { return false } + var parent = range.parent, nodeBefore = parent.child(startIndex - 1); + if (nodeBefore.type != itemType) { return false } + + if (dispatch) { + var nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type; + var inner = Fragment.from(nestedBefore ? itemType.create() : null); + var slice = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner)))), + nestedBefore ? 3 : 1, 0); + var before = range.start, after = range.end; + dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, + before, after, slice, 1, true)) + .scrollIntoView()); + } + return true + } + } + + // ::- Input rules are regular expressions describing a piece of text + // that, when typed, causes something to happen. This might be + // changing two dashes into an emdash, wrapping a paragraph starting + // with `"> "` into a blockquote, or something entirely different. + var InputRule = function InputRule(match, handler) { + this.match = match; + this.handler = typeof handler == "string" ? stringHandler(handler) : handler; + }; + + function stringHandler(string) { + return function(state, match, start, end) { + var insert = string; + if (match[1]) { + var offset = match[0].lastIndexOf(match[1]); + insert += match[0].slice(offset + match[1].length); + start += offset; + var cutOff = start - end; + if (cutOff > 0) { + insert = match[0].slice(offset - cutOff, offset) + insert; + start = end; + } + } + return state.tr.insertText(insert, start, end) + } + } + + var MAX_MATCH = 500; + + // :: (config: {rules: [InputRule]}) → Plugin + // Create an input rules plugin. When enabled, it will cause text + // input that matches any of the given rules to trigger the rule's + // action. + function inputRules(ref) { + var rules = ref.rules; + + var plugin = new Plugin({ + state: { + init: function init() { return null }, + apply: function apply(tr, prev) { + var stored = tr.getMeta(this); + if (stored) { return stored } + return tr.selectionSet || tr.docChanged ? null : prev + } + }, + + props: { + handleTextInput: function handleTextInput(view, from, to, text) { + return run(view, from, to, text, rules, plugin) + }, + handleDOMEvents: { + compositionend: function (view) { + setTimeout(function () { + var ref = view.state.selection; + var $cursor = ref.$cursor; + if ($cursor) { run(view, $cursor.pos, $cursor.pos, "", rules, plugin); } + }); + } + } + }, + + isInputRules: true + }); + return plugin + } + + function run(view, from, to, text, rules, plugin) { + if (view.composing) { return false } + var state = view.state, $from = state.doc.resolve(from); + if ($from.parent.type.spec.code) { return false } + var textBefore = $from.parent.textBetween(Math.max(0, $from.parentOffset - MAX_MATCH), $from.parentOffset, + null, "\ufffc") + text; + for (var i = 0; i < rules.length; i++) { + var match = rules[i].match.exec(textBefore); + var tr = match && rules[i].handler(state, match, from - (match[0].length - text.length), to); + if (!tr) { continue } + view.dispatch(tr.setMeta(plugin, {transform: tr, from: from, to: to, text: text})); + return true + } + return false + } + + // :: (EditorState, ?(Transaction)) → bool + // This is a command that will undo an input rule, if applying such a + // rule was the last thing that the user did. + function undoInputRule(state, dispatch) { + var plugins = state.plugins; + for (var i = 0; i < plugins.length; i++) { + var plugin = plugins[i], undoable = (void 0); + if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) { + if (dispatch) { + var tr = state.tr, toUndo = undoable.transform; + for (var j = toUndo.steps.length - 1; j >= 0; j--) + { tr.step(toUndo.steps[j].invert(toUndo.docs[j])); } + var marks = tr.doc.resolve(undoable.from).marks(); + dispatch(tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks))); + } + return true + } + } + return false + } + + // :: InputRule Converts double dashes to an emdash. + var emDash = new InputRule(/--$/, "—"); + // :: InputRule Converts three dots to an ellipsis character. + var ellipsis = new InputRule(/\.\.\.$/, "…"); + // :: InputRule “Smart” opening double quotes. + var openDoubleQuote = new InputRule(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(")$/, "“"); + // :: InputRule “Smart” closing double quotes. + var closeDoubleQuote = new InputRule(/"$/, "”"); + // :: InputRule “Smart” opening single quotes. + var openSingleQuote = new InputRule(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(')$/, "‘"); + // :: InputRule “Smart” closing single quotes. + var closeSingleQuote = new InputRule(/'$/, "’"); + + // :: [InputRule] Smart-quote related input rules. + var smartQuotes = [openDoubleQuote, closeDoubleQuote, openSingleQuote, closeSingleQuote]; + + // :: (RegExp, NodeType, ?union, ?([string], Node) → bool) → InputRule + // Build an input rule for automatically wrapping a textblock when a + // given string is typed. The `regexp` argument is + // directly passed through to the `InputRule` constructor. You'll + // probably want the regexp to start with `^`, so that the pattern can + // only occur at the start of a textblock. + // + // `nodeType` is the type of node to wrap in. If it needs attributes, + // you can either pass them directly, or pass a function that will + // compute them from the regular expression match. + // + // By default, if there's a node with the same type above the newly + // wrapped node, the rule will try to [join](#transform.Transform.join) those + // two nodes. You can pass a join predicate, which takes a regular + // expression match and the node before the wrapped node, and can + // return a boolean to indicate whether a join should happen. + function wrappingInputRule(regexp, nodeType, getAttrs, joinPredicate) { + return new InputRule(regexp, function (state, match, start, end) { + var attrs = getAttrs instanceof Function ? getAttrs(match) : getAttrs; + var tr = state.tr.delete(start, end); + var $start = tr.doc.resolve(start), range = $start.blockRange(), wrapping = range && findWrapping(range, nodeType, attrs); + if (!wrapping) { return null } + tr.wrap(range, wrapping); + var before = tr.doc.resolve(start - 1).nodeBefore; + if (before && before.type == nodeType && canJoin(tr.doc, start - 1) && + (!joinPredicate || joinPredicate(match, before))) + { tr.join(start - 1); } + return tr + }) + } + + // :: (RegExp, NodeType, ?union) → InputRule + // Build an input rule that changes the type of a textblock when the + // matched text is typed into it. You'll usually want to start your + // regexp with `^` to that it is only matched at the start of a + // textblock. The optional `getAttrs` parameter can be used to compute + // the new node's attributes, and works the same as in the + // `wrappingInputRule` function. + function textblockTypeInputRule(regexp, nodeType, getAttrs) { + return new InputRule(regexp, function (state, match, start, end) { + var $start = state.doc.resolve(start); + var attrs = getAttrs instanceof Function ? getAttrs(match) : getAttrs; + if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), nodeType)) { return null } + return state.tr + .delete(start, end) + .setBlockType(start, start, nodeType, attrs) + }) + } + + var prefix$3 = "ProseMirror-prompt"; + + function openPrompt(options) { + var wrapper = document.body.appendChild(document.createElement("div")); + wrapper.className = prefix$3; + + var mouseOutside = function (e) { if (!wrapper.contains(e.target)) { close(); } }; + setTimeout(function () { return window.addEventListener("mousedown", mouseOutside); }, 50); + var close = function () { + window.removeEventListener("mousedown", mouseOutside); + if (wrapper.parentNode) { wrapper.parentNode.removeChild(wrapper); } + }; + + var domFields = []; + for (var name in options.fields) { domFields.push(options.fields[name].render()); } + + var submitButton = document.createElement("button"); + submitButton.type = "submit"; + submitButton.className = prefix$3 + "-submit"; + submitButton.textContent = "OK"; + var cancelButton = document.createElement("button"); + cancelButton.type = "button"; + cancelButton.className = prefix$3 + "-cancel"; + cancelButton.textContent = "Cancel"; + cancelButton.addEventListener("click", close); + + var form = wrapper.appendChild(document.createElement("form")); + if (options.title) { form.appendChild(document.createElement("h5")).textContent = options.title; } + domFields.forEach(function (field) { + form.appendChild(document.createElement("div")).appendChild(field); + }); + var buttons = form.appendChild(document.createElement("div")); + buttons.className = prefix$3 + "-buttons"; + buttons.appendChild(submitButton); + buttons.appendChild(document.createTextNode(" ")); + buttons.appendChild(cancelButton); + + var box = wrapper.getBoundingClientRect(); + wrapper.style.top = ((window.innerHeight - box.height) / 2) + "px"; + wrapper.style.left = ((window.innerWidth - box.width) / 2) + "px"; + + var submit = function () { + var params = getValues(options.fields, domFields); + if (params) { + close(); + options.callback(params); + } + }; + + form.addEventListener("submit", function (e) { + e.preventDefault(); + submit(); + }); + + form.addEventListener("keydown", function (e) { + if (e.keyCode == 27) { + e.preventDefault(); + close(); + } else if (e.keyCode == 13 && !(e.ctrlKey || e.metaKey || e.shiftKey)) { + e.preventDefault(); + submit(); + } else if (e.keyCode == 9) { + window.setTimeout(function () { + if (!wrapper.contains(document.activeElement)) { close(); } + }, 500); + } + }); + + var input = form.elements[0]; + if (input) { input.focus(); } + } + + function getValues(fields, domFields) { + var result = Object.create(null), i = 0; + for (var name in fields) { + var field = fields[name], dom = domFields[i++]; + var value = field.read(dom), bad = field.validate(value); + if (bad) { + reportInvalid(dom, bad); + return null + } + result[name] = field.clean(value); + } + return result + } + + function reportInvalid(dom, message) { + // FIXME this is awful and needs a lot more work + var parent = dom.parentNode; + var msg = parent.appendChild(document.createElement("div")); + msg.style.left = (dom.offsetLeft + dom.offsetWidth + 2) + "px"; + msg.style.top = (dom.offsetTop - 5) + "px"; + msg.className = "ProseMirror-invalid"; + msg.textContent = message; + setTimeout(function () { return parent.removeChild(msg); }, 1500); + } + + // ::- The type of field that `FieldPrompt` expects to be passed to it. + var Field = function Field(options) { this.options = options; }; + + // render:: (state: EditorState, props: Object) → dom.Node + // Render the field to the DOM. Should be implemented by all subclasses. + + // :: (dom.Node) → any + // Read the field's value from its DOM node. + Field.prototype.read = function read (dom) { return dom.value }; + + // :: (any) → ?string + // A field-type-specific validation function. + Field.prototype.validateType = function validateType (_value) {}; + + Field.prototype.validate = function validate (value) { + if (!value && this.options.required) + { return "Required field" } + return this.validateType(value) || (this.options.validate && this.options.validate(value)) + }; + + Field.prototype.clean = function clean (value) { + return this.options.clean ? this.options.clean(value) : value + }; + + // ::- A field class for single-line text fields. + var TextField = /*@__PURE__*/(function (Field) { + function TextField () { + Field.apply(this, arguments); + } + + if ( Field ) TextField.__proto__ = Field; + TextField.prototype = Object.create( Field && Field.prototype ); + TextField.prototype.constructor = TextField; + + TextField.prototype.render = function render () { + var input = document.createElement("input"); + input.type = "text"; + input.placeholder = this.options.label; + input.value = this.options.value || ""; + input.autocomplete = "off"; + return input + }; + + return TextField; + }(Field)); + + // Helpers to create specific types of items + + function canInsert(state, nodeType) { + var $from = state.selection.$from; + for (var d = $from.depth; d >= 0; d--) { + var index = $from.index(d); + if ($from.node(d).canReplaceWith(index, index, nodeType)) { return true } + } + return false + } + + function insertImageItem(nodeType) { + return new MenuItem({ + title: "Insert image", + label: "Image", + enable: function enable(state) { return canInsert(state, nodeType) }, + run: function run(state, _, view) { + var ref = state.selection; + var from = ref.from; + var to = ref.to; + var attrs = null; + if (state.selection instanceof NodeSelection && state.selection.node.type == nodeType) + { attrs = state.selection.node.attrs; } + openPrompt({ + title: "Insert image", + fields: { + src: new TextField({label: "Location", required: true, value: attrs && attrs.src}), + title: new TextField({label: "Title", value: attrs && attrs.title}), + alt: new TextField({label: "Description", + value: attrs ? attrs.alt : state.doc.textBetween(from, to, " ")}) + }, + callback: function callback(attrs) { + view.dispatch(view.state.tr.replaceSelectionWith(nodeType.createAndFill(attrs))); + view.focus(); + } + }); + } + }) + } + + function cmdItem(cmd, options) { + var passedOptions = { + label: options.title, + run: cmd + }; + for (var prop in options) { passedOptions[prop] = options[prop]; } + if ((!options.enable || options.enable === true) && !options.select) + { passedOptions[options.enable ? "enable" : "select"] = function (state) { return cmd(state); }; } + + return new MenuItem(passedOptions) + } + + function markActive(state, type) { + var ref = state.selection; + var from = ref.from; + var $from = ref.$from; + var to = ref.to; + var empty = ref.empty; + if (empty) { return type.isInSet(state.storedMarks || $from.marks()) } + else { return state.doc.rangeHasMark(from, to, type) } + } + + function markItem(markType, options) { + var passedOptions = { + active: function active(state) { return markActive(state, markType) }, + enable: true + }; + for (var prop in options) { passedOptions[prop] = options[prop]; } + return cmdItem(toggleMark(markType), passedOptions) + } + + function linkItem(markType) { + return new MenuItem({ + title: "Add or remove link", + icon: icons.link, + active: function active(state) { return markActive(state, markType) }, + enable: function enable(state) { return !state.selection.empty }, + run: function run(state, dispatch, view) { + if (markActive(state, markType)) { + toggleMark(markType)(state, dispatch); + return true + } + openPrompt({ + title: "Create a link", + fields: { + href: new TextField({ + label: "Link target", + required: true + }), + title: new TextField({label: "Title"}) + }, + callback: function callback(attrs) { + toggleMark(markType, attrs)(view.state, view.dispatch); + view.focus(); + } + }); + } + }) + } + + function wrapListItem(nodeType, options) { + return cmdItem(wrapInList(nodeType, options.attrs), options) + } + + // :: (Schema) → Object + // Given a schema, look for default mark and node types in it and + // return an object with relevant menu items relating to those marks: + // + // **`toggleStrong`**`: MenuItem` + // : A menu item to toggle the [strong mark](#schema-basic.StrongMark). + // + // **`toggleEm`**`: MenuItem` + // : A menu item to toggle the [emphasis mark](#schema-basic.EmMark). + // + // **`toggleCode`**`: MenuItem` + // : A menu item to toggle the [code font mark](#schema-basic.CodeMark). + // + // **`toggleLink`**`: MenuItem` + // : A menu item to toggle the [link mark](#schema-basic.LinkMark). + // + // **`insertImage`**`: MenuItem` + // : A menu item to insert an [image](#schema-basic.Image). + // + // **`wrapBulletList`**`: MenuItem` + // : A menu item to wrap the selection in a [bullet list](#schema-list.BulletList). + // + // **`wrapOrderedList`**`: MenuItem` + // : A menu item to wrap the selection in an [ordered list](#schema-list.OrderedList). + // + // **`wrapBlockQuote`**`: MenuItem` + // : A menu item to wrap the selection in a [block quote](#schema-basic.BlockQuote). + // + // **`makeParagraph`**`: MenuItem` + // : A menu item to set the current textblock to be a normal + // [paragraph](#schema-basic.Paragraph). + // + // **`makeCodeBlock`**`: MenuItem` + // : A menu item to set the current textblock to be a + // [code block](#schema-basic.CodeBlock). + // + // **`makeHead[N]`**`: MenuItem` + // : Where _N_ is 1 to 6. Menu items to set the current textblock to + // be a [heading](#schema-basic.Heading) of level _N_. + // + // **`insertHorizontalRule`**`: MenuItem` + // : A menu item to insert a horizontal rule. + // + // The return value also contains some prefabricated menu elements and + // menus, that you can use instead of composing your own menu from + // scratch: + // + // **`insertMenu`**`: Dropdown` + // : A dropdown containing the `insertImage` and + // `insertHorizontalRule` items. + // + // **`typeMenu`**`: Dropdown` + // : A dropdown containing the items for making the current + // textblock a paragraph, code block, or heading. + // + // **`fullMenu`**`: [[MenuElement]]` + // : An array of arrays of menu elements for use as the full menu + // for, for example the [menu bar](https://github.com/prosemirror/prosemirror-menu#user-content-menubar). + function buildMenuItems(schema) { + var r = {}, type; + if (type = schema.marks.strong) + { r.toggleStrong = markItem(type, {title: "Toggle strong style", icon: icons.strong}); } + if (type = schema.marks.em) + { r.toggleEm = markItem(type, {title: "Toggle emphasis", icon: icons.em}); } + if (type = schema.marks.code) + { r.toggleCode = markItem(type, {title: "Toggle code font", icon: icons.code}); } + if (type = schema.marks.link) + { r.toggleLink = linkItem(type); } + + if (type = schema.nodes.image) + { r.insertImage = insertImageItem(type); } + if (type = schema.nodes.bullet_list) + { r.wrapBulletList = wrapListItem(type, { + title: "Wrap in bullet list", + icon: icons.bulletList + }); } + if (type = schema.nodes.ordered_list) + { r.wrapOrderedList = wrapListItem(type, { + title: "Wrap in ordered list", + icon: icons.orderedList + }); } + if (type = schema.nodes.blockquote) + { r.wrapBlockQuote = wrapItem(type, { + title: "Wrap in block quote", + icon: icons.blockquote + }); } + if (type = schema.nodes.paragraph) + { r.makeParagraph = blockTypeItem(type, { + title: "Change to paragraph", + label: "Plain" + }); } + if (type = schema.nodes.code_block) + { r.makeCodeBlock = blockTypeItem(type, { + title: "Change to code block", + label: "Code" + }); } + if (type = schema.nodes.heading) + { for (var i = 1; i <= 10; i++) + { r["makeHead" + i] = blockTypeItem(type, { + title: "Change to heading " + i, + label: "Level " + i, + attrs: {level: i} + }); } } + if (type = schema.nodes.horizontal_rule) { + var hr = type; + r.insertHorizontalRule = new MenuItem({ + title: "Insert horizontal rule", + label: "Horizontal rule", + enable: function enable(state) { return canInsert(state, hr) }, + run: function run(state, dispatch) { dispatch(state.tr.replaceSelectionWith(hr.create())); } + }); + } + + var cut = function (arr) { return arr.filter(function (x) { return x; }); }; + r.insertMenu = new Dropdown(cut([r.insertImage, r.insertHorizontalRule]), {label: "Insert"}); + r.typeMenu = new Dropdown(cut([r.makeParagraph, r.makeCodeBlock, r.makeHead1 && new DropdownSubmenu(cut([ + r.makeHead1, r.makeHead2, r.makeHead3, r.makeHead4, r.makeHead5, r.makeHead6 + ]), {label: "Heading"})]), {label: "Type..."}); + + r.inlineMenu = [cut([r.toggleStrong, r.toggleEm, r.toggleCode, r.toggleLink])]; + r.blockMenu = [cut([r.wrapBulletList, r.wrapOrderedList, r.wrapBlockQuote, joinUpItem, + liftItem, selectParentNodeItem])]; + r.fullMenu = r.inlineMenu.concat([[r.insertMenu, r.typeMenu]], [[undoItem, redoItem$1]], r.blockMenu); + + return r + } + + var mac$3 = typeof navigator != "undefined" ? /Mac/.test(navigator.platform) : false; + + // :: (Schema, ?Object) → Object + // Inspect the given schema looking for marks and nodes from the + // basic schema, and if found, add key bindings related to them. + // This will add: + // + // * **Mod-b** for toggling [strong](#schema-basic.StrongMark) + // * **Mod-i** for toggling [emphasis](#schema-basic.EmMark) + // * **Mod-`** for toggling [code font](#schema-basic.CodeMark) + // * **Ctrl-Shift-0** for making the current textblock a paragraph + // * **Ctrl-Shift-1** to **Ctrl-Shift-Digit6** for making the current + // textblock a heading of the corresponding level + // * **Ctrl-Shift-Backslash** to make the current textblock a code block + // * **Ctrl-Shift-8** to wrap the selection in an ordered list + // * **Ctrl-Shift-9** to wrap the selection in a bullet list + // * **Ctrl->** to wrap the selection in a block quote + // * **Enter** to split a non-empty textblock in a list item while at + // the same time splitting the list item + // * **Mod-Enter** to insert a hard break + // * **Mod-_** to insert a horizontal rule + // * **Backspace** to undo an input rule + // * **Alt-ArrowUp** to `joinUp` + // * **Alt-ArrowDown** to `joinDown` + // * **Mod-BracketLeft** to `lift` + // * **Escape** to `selectParentNode` + // + // You can suppress or map these bindings by passing a `mapKeys` + // argument, which maps key names (say `"Mod-B"` to either `false`, to + // remove the binding, or a new key name string. + function buildKeymap(schema, mapKeys) { + var keys = {}, type; + function bind(key, cmd) { + if (mapKeys) { + var mapped = mapKeys[key]; + if (mapped === false) { return } + if (mapped) { key = mapped; } + } + keys[key] = cmd; + } + + + bind("Mod-z", undo$1); + bind("Shift-Mod-z", redo$1); + bind("Backspace", undoInputRule); + if (!mac$3) { bind("Mod-y", redo$1); } + + bind("Alt-ArrowUp", joinUp); + bind("Alt-ArrowDown", joinDown); + bind("Mod-BracketLeft", lift); + bind("Escape", selectParentNode); + + if (type = schema.marks.strong) { + bind("Mod-b", toggleMark(type)); + bind("Mod-B", toggleMark(type)); + } + if (type = schema.marks.em) { + bind("Mod-i", toggleMark(type)); + bind("Mod-I", toggleMark(type)); + } + if (type = schema.marks.code) + { bind("Mod-`", toggleMark(type)); } + + if (type = schema.nodes.bullet_list) + { bind("Shift-Ctrl-8", wrapInList(type)); } + if (type = schema.nodes.ordered_list) + { bind("Shift-Ctrl-9", wrapInList(type)); } + if (type = schema.nodes.blockquote) + { bind("Ctrl->", wrapIn(type)); } + if (type = schema.nodes.hard_break) { + var br = type, cmd = chainCommands(exitCode, function (state, dispatch) { + dispatch(state.tr.replaceSelectionWith(br.create()).scrollIntoView()); + return true + }); + bind("Mod-Enter", cmd); + bind("Shift-Enter", cmd); + if (mac$3) { bind("Ctrl-Enter", cmd); } + } + if (type = schema.nodes.list_item) { + bind("Enter", splitListItem(type)); + bind("Mod-[", liftListItem(type)); + bind("Mod-]", sinkListItem(type)); + } + if (type = schema.nodes.paragraph) + { bind("Shift-Ctrl-0", setBlockType(type)); } + if (type = schema.nodes.code_block) + { bind("Shift-Ctrl-\\", setBlockType(type)); } + if (type = schema.nodes.heading) + { for (var i = 1; i <= 6; i++) { bind("Shift-Ctrl-" + i, setBlockType(type, {level: i})); } } + if (type = schema.nodes.horizontal_rule) { + var hr = type; + bind("Mod-_", function (state, dispatch) { + dispatch(state.tr.replaceSelectionWith(hr.create()).scrollIntoView()); + return true + }); + } + + return keys + } + + // : (NodeType) → InputRule + // Given a blockquote node type, returns an input rule that turns `"> "` + // at the start of a textblock into a blockquote. + function blockQuoteRule(nodeType) { + return wrappingInputRule(/^\s*>\s$/, nodeType) + } + + // : (NodeType) → InputRule + // Given a list node type, returns an input rule that turns a number + // followed by a dot at the start of a textblock into an ordered list. + function orderedListRule(nodeType) { + return wrappingInputRule(/^(\d+)\.\s$/, nodeType, function (match) { return ({order: +match[1]}); }, + function (match, node) { return node.childCount + node.attrs.order == +match[1]; }) + } + + // : (NodeType) → InputRule + // Given a list node type, returns an input rule that turns a bullet + // (dash, plush, or asterisk) at the start of a textblock into a + // bullet list. + function bulletListRule(nodeType) { + return wrappingInputRule(/^\s*([-+*])\s$/, nodeType) + } + + // : (NodeType) → InputRule + // Given a code block node type, returns an input rule that turns a + // textblock starting with three backticks into a code block. + function codeBlockRule(nodeType) { + return textblockTypeInputRule(/^```$/, nodeType) + } + + // : (NodeType, number) → InputRule + // Given a node type and a maximum level, creates an input rule that + // turns up to that number of `#` characters followed by a space at + // the start of a textblock into a heading whose level corresponds to + // the number of `#` signs. + function headingRule(nodeType, maxLevel) { + return textblockTypeInputRule(new RegExp("^(#{1," + maxLevel + "})\\s$"), + nodeType, function (match) { return ({level: match[1].length}); }) + } + + // : (Schema) → Plugin + // A set of input rules for creating the basic block quotes, lists, + // code blocks, and heading. + function buildInputRules(schema) { + var rules = smartQuotes.concat(ellipsis, emDash), type; + if (type = schema.nodes.blockquote) { rules.push(blockQuoteRule(type)); } + if (type = schema.nodes.ordered_list) { rules.push(orderedListRule(type)); } + if (type = schema.nodes.bullet_list) { rules.push(bulletListRule(type)); } + if (type = schema.nodes.code_block) { rules.push(codeBlockRule(type)); } + if (type = schema.nodes.heading) { rules.push(headingRule(type, 6)); } + return inputRules({rules: rules}) + } + + // !! This module exports helper functions for deriving a set of basic + // menu items, input rules, or key bindings from a schema. These + // values need to know about the schema for two reasons—they need + // access to specific instances of node and mark types, and they need + // to know which of the node and mark types that they know about are + // actually present in the schema. + // + // The `exampleSetup` plugin ties these together into a plugin that + // will automatically enable this basic functionality in an editor. + + // :: (Object) → [Plugin] + // A convenience plugin that bundles together a simple menu with basic + // key bindings, input rules, and styling for the example schema. + // Probably only useful for quickly setting up a passable + // editor—you'll need more control over your settings in most + // real-world situations. + // + // options::- The following options are recognized: + // + // schema:: Schema + // The schema to generate key bindings and menu items for. + // + // mapKeys:: ?Object + // Can be used to [adjust](#example-setup.buildKeymap) the key bindings created. + // + // menuBar:: ?bool + // Set to false to disable the menu bar. + // + // history:: ?bool + // Set to false to disable the history plugin. + // + // floatingMenu:: ?bool + // Set to false to make the menu bar non-floating. + // + // menuContent:: [[MenuItem]] + // Can be used to override the menu content. + function exampleSetup(options) { + var plugins = [ + buildInputRules(options.schema), + keymap(buildKeymap(options.schema, options.mapKeys)), + keymap(baseKeymap), + dropCursor(), + gapCursor() + ]; + if (options.menuBar !== false) + { plugins.push(menuBar({floating: options.floatingMenu !== false, + content: options.menuContent || buildMenuItems(options.schema).fullMenu})); } + if (options.history !== false) + { plugins.push(history()); } + + return plugins.concat(new Plugin({ + props: { + attributes: {class: "ProseMirror-example-setup-style"} + } + })) + } + + /* eslint-env browser */ + + window.addEventListener('load', () => { + const ydoc = new Doc(); + const provider = new WebrtcProvider('prosemirror-debug', ydoc); + const type = ydoc.getXmlFragment('prosemirror'); + + const editor = document.createElement('div'); + editor.setAttribute('id', 'editor'); + const editorContainer = document.createElement('div'); + editorContainer.insertBefore(editor, null); + const prosemirrorView = new EditorView(editor, { + state: EditorState.create({ + schema, + plugins: [ + ySyncPlugin(type), + yCursorPlugin(provider.awareness), + yUndoPlugin(), + keymap({ + 'Mod-z': undo, + 'Mod-y': redo, + 'Mod-Shift-z': redo + }) + ].concat(exampleSetup({ schema })) + }) + }); + document.body.insertBefore(editorContainer, null); + + const connectBtn = /** @type {HTMLElement} */ (document.getElementById('y-connect-btn')); + connectBtn.addEventListener('click', () => { + if (provider.shouldConnect) { + provider.disconnect(); + connectBtn.textContent = 'Connect'; + } else { + provider.connect(); + connectBtn.textContent = 'Disconnect'; + } + }); + + // @ts-ignore + window.example = { provider, ydoc, type, prosemirrorView }; + }); + +}()); +//# sourceMappingURL=prosemirror.js.map diff --git a/demo/dist/prosemirror.js.map b/demo/dist/prosemirror.js.map new file mode 100644 index 0000000..c7bbab4 --- /dev/null +++ b/demo/dist/prosemirror.js.map @@ -0,0 +1 @@ +{"version":3,"file":"prosemirror.js","sources":["../../node_modules/lib0/map.js","../../node_modules/lib0/set.js","../../node_modules/lib0/array.js","../../node_modules/lib0/observable.js","../../node_modules/lib0/math.js","../../node_modules/lib0/string.js","../../node_modules/lib0/conditions.js","../../node_modules/lib0/storage.js","../../node_modules/lib0/environment.js","../../node_modules/lib0/binary.js","../../node_modules/lib0/decoding.js","../../node_modules/lib0/buffer.js","../../node_modules/lib0/number.js","../../node_modules/lib0/encoding.js","../../node_modules/isomorphic.js/iso-browser.js","../../node_modules/lib0/isomorphic.js","../../node_modules/lib0/random.js","../../node_modules/lib0/error.js","../../node_modules/lib0/object.js","../../node_modules/lib0/function.js","../../node_modules/lib0/symbol.js","../../node_modules/lib0/pair.js","../../node_modules/lib0/dom.js","../../node_modules/lib0/eventloop.js","../../node_modules/lib0/time.js","../../node_modules/lib0/logging.js","../../node_modules/lib0/iterator.js","../../node_modules/yjs/dist/yjs.mjs","../../node_modules/lib0/websocket.js","../../node_modules/lib0/promise.js","../../node_modules/lib0/broadcastchannel.js","../../node_modules/lib0/mutex.js","../../node_modules/simple-peer/simplepeer.min.js","../../node_modules/y-protocols/sync.js","../../node_modules/y-protocols/awareness.js","../../node_modules/y-webrtc/src/crypto.js","../../node_modules/y-webrtc/src/y-webrtc.js","../../node_modules/orderedmap/index.es.js","../../node_modules/prosemirror-model/dist/index.es.js","../../node_modules/prosemirror-transform/dist/index.es.js","../../node_modules/prosemirror-state/dist/index.es.js","../../node_modules/prosemirror-view/dist/index.es.js","../../node_modules/lib0/diff.js","../../src/plugins/keys.js","../../src/plugins/sync-plugin.js","../../src/lib.js","../../src/plugins/cursor-plugin.js","../../src/plugins/undo-plugin.js","../schema.js","../../node_modules/w3c-keyname/index.es.js","../../node_modules/prosemirror-keymap/dist/index.es.js","../../node_modules/rope-sequence/dist/index.es.js","../../node_modules/prosemirror-history/dist/index.es.js","../../node_modules/prosemirror-commands/dist/index.es.js","../../node_modules/prosemirror-dropcursor/dist/index.es.js","../../node_modules/prosemirror-gapcursor/dist/index.es.js","../../node_modules/crelt/index.es.js","../../node_modules/prosemirror-menu/dist/index.es.js","../../node_modules/prosemirror-schema-list/dist/index.es.js","../../node_modules/prosemirror-inputrules/dist/index.es.js","../../node_modules/prosemirror-example-setup/dist/index.es.js","../prosemirror.js"],"sourcesContent":["/**\n * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template X,Y\n * @param {Map} m\n * @return {Map}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template T,K\n * @param {Map} map\n * @param {K} key\n * @param {function():T} createT\n * @return {T}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map} m\n * @param {function(V,K):R} f\n * @return {Array}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n","/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set} set\n * @return {Array}\n */\nexport const toArray = set => Array.from(set)\n","/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {Array} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array}\n */\nexport const create = () => /** @type {Array} */ ([])\n\n/**\n * @template D\n * @param {Array} a\n * @return {Array}\n */\nexport const copy = a => /** @type {Array} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array} dest\n * @param {Array} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike|Iterable} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template ITEM\n *\n * @param {Array} arr\n * @param {function(ITEM, number, Array):boolean} f\n * @return {boolean}\n */\nexport const every = (arr, f) => arr.every(f)\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template S\n * @param {Array} arr\n * @param {function(S, number, Array):boolean} f\n * @return {boolean}\n */\nexport const some = (arr, f) => arr.some(f)\n\n/**\n * @template ELEM\n *\n * @param {Array} a\n * @param {Array} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n","/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n *\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n","/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* istanbul ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* istanbul ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* istanbul ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* istanbul ignore next */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* istanbul ignore next */\n utf8TextDecoder = null\n}\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* istanbul ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n","/**\n * Often used conditions.\n *\n * @module conditions\n */\n\n/**\n * @template T\n * @param {T|null|undefined} v\n * @return {T|null}\n */\n/* istanbul ignore next */\nexport const undefinedToNull = v => v === undefined ? null : v\n","/* global localStorage */\n\n/**\n * Isomorphic variable storage.\n *\n * Uses LocalStorage in the browser and falls back to in-memory storage.\n *\n * @module storage\n */\n\n/* istanbul ignore next */\nclass VarStoragePolyfill {\n constructor () {\n this.map = new Map()\n }\n\n /**\n * @param {string} key\n * @param {any} value\n */\n setItem (key, value) {\n this.map.set(key, value)\n }\n\n /**\n * @param {string} key\n */\n getItem (key) {\n return this.map.get(key)\n }\n}\n\n/* istanbul ignore next */\n/**\n * @type {any}\n */\nlet _localStorage = new VarStoragePolyfill()\n\ntry {\n // if the same-origin rule is violated, accessing localStorage might thrown an error\n /* istanbul ignore next */\n if (typeof localStorage !== 'undefined') {\n _localStorage = localStorage\n }\n} catch (e) { }\n\n/* istanbul ignore next */\n/**\n * This is basically localStorage in browser, or a polyfill in nodejs\n */\nexport const varStorage = _localStorage\n","/**\n * Isomorphic module to work access the environment (query params, env variables).\n *\n * @module map\n */\n\nimport * as map from './map.js'\nimport * as string from './string.js'\nimport * as conditions from './conditions.js'\nimport * as storage from './storage.js'\n\n/* istanbul ignore next */\n// @ts-ignore\nexport const isNode = typeof process !== 'undefined' && process.release && /node|io\\.js/.test(process.release.name)\n/* istanbul ignore next */\nexport const isBrowser = typeof window !== 'undefined' && !isNode\n/* istanbul ignore next */\nexport const isMac = typeof navigator !== 'undefined' ? /Mac/.test(navigator.platform) : false\n\n/**\n * @type {Map}\n */\nlet params\nconst args = []\n\n/* istanbul ignore next */\nconst computeParams = () => {\n if (params === undefined) {\n if (isNode) {\n params = map.create()\n const pargs = process.argv\n let currParamName = null\n /* istanbul ignore next */\n for (let i = 0; i < pargs.length; i++) {\n const parg = pargs[i]\n if (parg[0] === '-') {\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n currParamName = parg\n } else {\n if (currParamName !== null) {\n params.set(currParamName, parg)\n currParamName = null\n } else {\n args.push(parg)\n }\n }\n }\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n // in ReactNative for example this would not be true (unless connected to the Remote Debugger)\n } else if (typeof location === 'object') {\n params = map.create()\n // eslint-disable-next-line no-undef\n ;(location.search || '?').slice(1).split('&').forEach(kv => {\n if (kv.length !== 0) {\n const [key, value] = kv.split('=')\n params.set(`--${string.fromCamelCase(key, '-')}`, value)\n params.set(`-${string.fromCamelCase(key, '-')}`, value)\n }\n })\n } else {\n params = map.create()\n }\n }\n return params\n}\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* istanbul ignore next */\nexport const hasParam = name => computeParams().has(name)\n\n/**\n * @param {string} name\n * @param {string} defaultVal\n * @return {string}\n */\n/* istanbul ignore next */\nexport const getParam = (name, defaultVal) => computeParams().get(name) || defaultVal\n// export const getArgs = name => computeParams() && args\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* istanbul ignore next */\nexport const getVariable = name => isNode ? conditions.undefinedToNull(process.env[name.toUpperCase()]) : conditions.undefinedToNull(storage.varStorage.getItem(name))\n\n/**\n * @param {string} name\n * @return {string|null}\n */\nexport const getConf = name => computeParams().get('--' + name) || getVariable(name)\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* istanbul ignore next */\nexport const hasConf = name => hasParam('--' + name) || getVariable(name) !== null\n\n/* istanbul ignore next */\nexport const production = hasConf('production')\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = new encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = new decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as binary from './binary.js'\nimport * as math from './math.js'\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n */\nexport class Decoder {\n /**\n * @param {Uint8Array} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @param {Uint8Array} uint8Array\n * @return {Decoder}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = buffer.createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing position.\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing position.\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing position.\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let len = 0\n while (true) {\n const r = decoder.arr[decoder.pos++]\n num = num | ((r & binary.BITS7) << len)\n len += 7\n if (r < binary.BIT8) {\n return num >>> 0 // return unsigned number!\n }\n /* istanbul ignore if */\n if (len > 35) {\n throw new Error('Integer out of range!')\n }\n }\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if unmber is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let len = 6\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n while (true) {\n r = decoder.arr[decoder.pos++]\n num = num | ((r & binary.BITS7) << len)\n len += 7\n if (r < binary.BIT8) {\n return sign * (num >>> 0)\n }\n /* istanbul ignore if */\n if (len > 41) {\n throw new Error('Integer out of range!')\n }\n }\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\nexport const readVarString = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0)\n\n/**\n * @type {Array}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object\n const len = readVarUint(decoder)\n /**\n * @type {Object}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = diff >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","/**\n * Utility functions to work with buffers (Uint8Array).\n *\n * @module buffer\n */\n\nimport * as string from './string.js'\nimport * as env from './environment.js'\nimport * as encoding from './encoding.js'\nimport * as decoding from './decoding.js'\n\n/**\n * @param {number} len\n */\nexport const createUint8ArrayFromLen = len => new Uint8Array(len)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n * @param {number} byteOffset\n * @param {number} length\n */\nexport const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n */\nexport const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)\n\n/* istanbul ignore next */\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Browser = bytes => {\n let s = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n s += string.fromCharCode(bytes[i])\n }\n // eslint-disable-next-line no-undef\n return btoa(s)\n}\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')\n\n/* istanbul ignore next */\n/**\n * @param {string} s\n * @return {Uint8Array}\n */\nconst fromBase64Browser = s => {\n // eslint-disable-next-line no-undef\n const a = atob(s)\n const bytes = createUint8ArrayFromLen(a.length)\n for (let i = 0; i < a.length; i++) {\n bytes[i] = a.charCodeAt(i)\n }\n return bytes\n}\n\n/**\n * @param {string} s\n */\nconst fromBase64Node = s => {\n const buf = Buffer.from(s, 'base64')\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n\n/* istanbul ignore next */\nexport const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node\n\n/* istanbul ignore next */\nexport const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node\n\n/**\n * Copy the content of an Uint8Array view to a new ArrayBuffer.\n *\n * @param {Uint8Array} uint8Array\n * @return {Uint8Array}\n */\nexport const copyUint8Array = uint8Array => {\n const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)\n newBuf.set(uint8Array)\n return newBuf\n}\n\n/**\n * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.\n * See encoding.writeAny for more information.\n *\n * @param {any} data\n * @return {Uint8Array}\n */\nexport const encodeAny = data => {\n const encoder = encoding.createEncoder()\n encoding.writeAny(encoder, data)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Decode an any-encoded value.\n *\n * @param {Uint8Array} buf\n * @return {any}\n */\nexport const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\n/**\n * @type {number}\n */\nexport const HIGHEST_INT32 = binary.BITS31\n\n/**\n * @module number\n */\n\n/* istanbul ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = new encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = new decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as buffer from './buffer.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nconst verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(buffer.createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer.\n *\n * Encodes integers in the range from [0, 4294967295] / [0, 0xffffffff]. (max 32 bit unsigned integer)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num >>>= 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * Encodes integers in the range from [-2147483648, -2147483647].\n *\n * We don't use zig-zag encoding because we want to keep the option open\n * to use the same function for BigInt and 53bit integers (doubles).\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num >>>= 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num >>>= 7\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeVarString = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write the content of another Encoder.\n *\n * TODO: can be improved!\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && data <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (data instanceof Array) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/* eslint-env browser */\nconst perf = typeof performance === 'undefined' ? null : performance\n\nconst isoCrypto = typeof crypto === 'undefined' ? null : crypto\n\n/**\n * @type {function(number):ArrayBuffer}\n */\nconst cryptoRandomBuffer = isoCrypto !== null\n ? len => {\n // browser\n const buf = new ArrayBuffer(len)\n const arr = new Uint8Array(buf)\n isoCrypto.getRandomValues(arr)\n return buf\n }\n : len => {\n // polyfill\n const buf = new ArrayBuffer(len)\n const arr = new Uint8Array(buf)\n for (let i = 0; i < len; i++) {\n arr[i] = Math.ceil((Math.random() * 0xFFFFFFFF) >>> 0)\n }\n return buf\n }\n\nexports.performance = perf\nexports.cryptoRandomBuffer = cryptoRandomBuffer\n","/**\n * Isomorphic library exports from isomorphic.js.\n *\n * @module isomorphic\n */\n\n// @ts-ignore\nimport iso from 'isomorphic.js'\n\nexport const performance = /** @type {any} */ (iso.performance)\nexport const cryptoRandomBuffer = /** @type {any} */ (iso.cryptoRandomBuffer)\n","\n/**\n * Isomorphic module for true random numbers / buffers / uuids.\n *\n * Attention: falls back to Math.random if the browser does not support crypto.\n *\n * @module random\n */\n\nimport * as math from './math.js'\nimport { cryptoRandomBuffer } from './isomorphic.js'\n\nexport const rand = Math.random\n\n/* istanbul ignore next */\nexport const uint32 = () => new Uint32Array(cryptoRandomBuffer(4))[0]\n\n/**\n * @template T\n * @param {Array} arr\n * @return {T}\n */\nexport const oneOf = arr => arr[math.floor(rand() * arr.length)]\n\n// @ts-ignore\nconst uuidv4Template = [1e7] + -1e3 + -4e3 + -8e3 + -1e11\nexport const uuidv4 = () => uuidv4Template.replace(/[018]/g, /** @param {number} c */ c =>\n (c ^ uint32() & 15 >> c / 4).toString(16)\n)\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* istanbul ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* istanbul ignore next */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* istanbul ignore next */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n","/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object} obj\n */\nexport const keys = Object.keys\n\n/**\n * @param {Object} obj\n * @param {function(any,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @template R\n * @param {Object} obj\n * @param {function(any,string):R} f\n * @return {Array}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @param {Object} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))\n","/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array} fs\n * @param {Array} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array|object} a\n * @param {Array|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((a instanceof Array && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a == null || b == null) {\n return equalityStrict(a, b)\n }\n if (a.constructor !== b.constructor) {\n return false\n }\n if (a === b) {\n return true\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n","/**\n * Utility module to work with EcmaScript Symbols.\n *\n * @module symbol\n */\n\n/**\n * Return fresh symbol.\n *\n * @return {Symbol}\n */\nexport const create = Symbol\n\n/**\n * @param {any} s\n * @return {boolean}\n */\nexport const isSymbol = s => typeof s === 'symbol'\n","/**\n * Working with value pairs.\n *\n * @module pair\n */\n\n/**\n * @template L,R\n */\nexport class Pair {\n /**\n * @param {L} left\n * @param {R} right\n */\n constructor (left, right) {\n this.left = left\n this.right = right\n }\n}\n\n/**\n * @template L,R\n * @param {L} left\n * @param {R} right\n * @return {Pair}\n */\nexport const create = (left, right) => new Pair(left, right)\n\n/**\n * @template L,R\n * @param {R} right\n * @param {L} left\n * @return {Pair}\n */\nexport const createReversed = (right, left) => new Pair(left, right)\n\n/**\n * @template L,R\n * @param {Array>} arr\n * @param {function(L, R):any} f\n */\nexport const forEach = (arr, f) => arr.forEach(p => f(p.left, p.right))\n\n/**\n * @template L,R,X\n * @param {Array>} arr\n * @param {function(L, R):X} f\n * @return {Array}\n */\nexport const map = (arr, f) => arr.map(p => f(p.left, p.right))\n","/* eslint-env browser */\n\n/**\n * Utility module to work with the DOM.\n *\n * @module dom\n */\n\nimport * as pair from './pair.js'\nimport * as map from './map.js'\n\n/* istanbul ignore next */\n/**\n * @type {Document}\n */\nexport const doc = /** @type {Document} */ (typeof document !== 'undefined' ? document : {})\n\n/**\n * @param {string} name\n * @return {HTMLElement}\n */\n/* istanbul ignore next */\nexport const createElement = name => doc.createElement(name)\n\n/**\n * @return {DocumentFragment}\n */\n/* istanbul ignore next */\nexport const createDocumentFragment = () => doc.createDocumentFragment()\n\n/**\n * @param {string} text\n * @return {Text}\n */\n/* istanbul ignore next */\nexport const createTextNode = text => doc.createTextNode(text)\n\n/* istanbul ignore next */\nexport const domParser = /** @type {DOMParser} */ (typeof DOMParser !== 'undefined' ? new DOMParser() : null)\n\n/**\n * @param {HTMLElement} el\n * @param {string} name\n * @param {Object} opts\n */\n/* istanbul ignore next */\nexport const emitCustomEvent = (el, name, opts) => el.dispatchEvent(new CustomEvent(name, opts))\n\n/**\n * @param {Element} el\n * @param {Array>} attrs Array of key-value pairs\n * @return {Element}\n */\n/* istanbul ignore next */\nexport const setAttributes = (el, attrs) => {\n pair.forEach(attrs, (key, value) => {\n if (value === false) {\n el.removeAttribute(key)\n } else if (value === true) {\n el.setAttribute(key, '')\n } else {\n // @ts-ignore\n el.setAttribute(key, value)\n }\n })\n return el\n}\n\n/**\n * @param {Element} el\n * @param {Map} attrs Array of key-value pairs\n * @return {Element}\n */\n/* istanbul ignore next */\nexport const setAttributesMap = (el, attrs) => {\n attrs.forEach((value, key) => { el.setAttribute(key, value) })\n return el\n}\n\n/**\n * @param {Array|HTMLCollection} children\n * @return {DocumentFragment}\n */\n/* istanbul ignore next */\nexport const fragment = children => {\n const fragment = createDocumentFragment()\n for (let i = 0; i < children.length; i++) {\n appendChild(fragment, children[i])\n }\n return fragment\n}\n\n/**\n * @param {Element} parent\n * @param {Array} nodes\n * @return {Element}\n */\n/* istanbul ignore next */\nexport const append = (parent, nodes) => {\n appendChild(parent, fragment(nodes))\n return parent\n}\n\n/**\n * @param {HTMLElement} el\n */\n/* istanbul ignore next */\nexport const remove = el => el.remove()\n\n/**\n * @param {EventTarget} el\n * @param {string} name\n * @param {EventListener} f\n */\n/* istanbul ignore next */\nexport const addEventListener = (el, name, f) => el.addEventListener(name, f)\n\n/**\n * @param {EventTarget} el\n * @param {string} name\n * @param {EventListener} f\n */\n/* istanbul ignore next */\nexport const removeEventListener = (el, name, f) => el.removeEventListener(name, f)\n\n/**\n * @param {Node} node\n * @param {Array>} listeners\n * @return {Node}\n */\n/* istanbul ignore next */\nexport const addEventListeners = (node, listeners) => {\n pair.forEach(listeners, (name, f) => addEventListener(node, name, f))\n return node\n}\n\n/**\n * @param {Node} node\n * @param {Array>} listeners\n * @return {Node}\n */\n/* istanbul ignore next */\nexport const removeEventListeners = (node, listeners) => {\n pair.forEach(listeners, (name, f) => removeEventListener(node, name, f))\n return node\n}\n\n/**\n * @param {string} name\n * @param {Array|pair.Pair>} attrs Array of key-value pairs\n * @param {Array} children\n * @return {Element}\n */\n/* istanbul ignore next */\nexport const element = (name, attrs = [], children = []) =>\n append(setAttributes(createElement(name), attrs), children)\n\n/**\n * @param {number} width\n * @param {number} height\n */\n/* istanbul ignore next */\nexport const canvas = (width, height) => {\n const c = /** @type {HTMLCanvasElement} */ (createElement('canvas'))\n c.height = height\n c.width = width\n return c\n}\n\n/**\n * @param {string} t\n * @return {Text}\n */\n/* istanbul ignore next */\nexport const text = createTextNode\n\n/**\n * @param {pair.Pair} pair\n */\n/* istanbul ignore next */\nexport const pairToStyleString = pair => `${pair.left}:${pair.right};`\n\n/**\n * @param {Array>} pairs\n * @return {string}\n */\n/* istanbul ignore next */\nexport const pairsToStyleString = pairs => pairs.map(pairToStyleString).join('')\n\n/**\n * @param {Map} m\n * @return {string}\n */\n/* istanbul ignore next */\nexport const mapToStyleString = m => map.map(m, (value, key) => `${key}:${value};`).join('')\n\n/**\n * @todo should always query on a dom element\n *\n * @param {HTMLElement|ShadowRoot} el\n * @param {string} query\n * @return {HTMLElement | null}\n */\n/* istanbul ignore next */\nexport const querySelector = (el, query) => el.querySelector(query)\n\n/**\n * @param {HTMLElement|ShadowRoot} el\n * @param {string} query\n * @return {NodeListOf}\n */\n/* istanbul ignore next */\nexport const querySelectorAll = (el, query) => el.querySelectorAll(query)\n\n/**\n * @param {string} id\n * @return {HTMLElement}\n */\n/* istanbul ignore next */\nexport const getElementById = id => /** @type {HTMLElement} */ (doc.getElementById(id))\n\n/**\n * @param {string} html\n * @return {HTMLElement}\n */\n/* istanbul ignore next */\nconst _parse = html => domParser.parseFromString(`${html}`, 'text/html').body\n\n/**\n * @param {string} html\n * @return {DocumentFragment}\n */\n/* istanbul ignore next */\nexport const parseFragment = html => fragment(/** @type {any} */ (_parse(html).childNodes))\n\n/**\n * @param {string} html\n * @return {HTMLElement}\n */\n/* istanbul ignore next */\nexport const parseElement = html => /** @type HTMLElement */ (_parse(html).firstElementChild)\n\n/**\n * @param {HTMLElement} oldEl\n * @param {HTMLElement|DocumentFragment} newEl\n */\n/* istanbul ignore next */\nexport const replaceWith = (oldEl, newEl) => oldEl.replaceWith(newEl)\n\n/**\n * @param {HTMLElement} parent\n * @param {HTMLElement} el\n * @param {Node|null} ref\n * @return {HTMLElement}\n */\n/* istanbul ignore next */\nexport const insertBefore = (parent, el, ref) => parent.insertBefore(el, ref)\n\n/**\n * @param {Node} parent\n * @param {Node} child\n * @return {Node}\n */\n/* istanbul ignore next */\nexport const appendChild = (parent, child) => parent.appendChild(child)\n\nexport const ELEMENT_NODE = doc.ELEMENT_NODE\nexport const TEXT_NODE = doc.TEXT_NODE\nexport const CDATA_SECTION_NODE = doc.CDATA_SECTION_NODE\nexport const COMMENT_NODE = doc.COMMENT_NODE\nexport const DOCUMENT_NODE = doc.DOCUMENT_NODE\nexport const DOCUMENT_TYPE_NODE = doc.DOCUMENT_TYPE_NODE\nexport const DOCUMENT_FRAGMENT_NODE = doc.DOCUMENT_FRAGMENT_NODE\n\n/**\n * @param {any} node\n * @param {number} type\n */\nexport const checkNodeType = (node, type) => node.nodeType === type\n\n/**\n * @param {Node} parent\n * @param {HTMLElement} child\n */\nexport const isParentOf = (parent, child) => {\n let p = child.parentNode\n while (p && p !== parent) {\n p = p.parentNode\n }\n return p === parent\n}\n","/* global requestIdleCallback, requestAnimationFrame, cancelIdleCallback, cancelAnimationFrame */\n\n/**\n * Utility module to work with EcmaScript's event loop.\n *\n * @module eventloop\n */\n\n/**\n * @type {Array}\n */\nlet queue = []\n\nconst _runQueue = () => {\n for (let i = 0; i < queue.length; i++) {\n queue[i]()\n }\n queue = []\n}\n\n/**\n * @param {function():void} f\n */\nexport const enqueue = f => {\n queue.push(f)\n if (queue.length === 1) {\n setTimeout(_runQueue, 0)\n }\n}\n\n/**\n * @typedef {Object} TimeoutObject\n * @property {function} TimeoutObject.destroy\n */\n\n/**\n * @param {function(number):void} clearFunction\n */\nconst createTimeoutClass = clearFunction => class TT {\n /**\n * @param {number} timeoutId\n */\n constructor (timeoutId) {\n this._ = timeoutId\n }\n\n destroy () {\n clearFunction(this._)\n }\n}\n\nconst Timeout = createTimeoutClass(clearTimeout)\n\n/**\n * @param {number} timeout\n * @param {function} callback\n * @return {TimeoutObject}\n */\nexport const timeout = (timeout, callback) => new Timeout(setTimeout(callback, timeout))\n\nconst Interval = createTimeoutClass(clearInterval)\n\n/**\n * @param {number} timeout\n * @param {function} callback\n * @return {TimeoutObject}\n */\nexport const interval = (timeout, callback) => new Interval(setInterval(callback, timeout))\n\n/* istanbul ignore next */\nexport const Animation = createTimeoutClass(arg => typeof requestAnimationFrame !== 'undefined' && cancelAnimationFrame(arg))\n\n/* istanbul ignore next */\n/**\n * @param {function(number):void} cb\n * @return {TimeoutObject}\n */\nexport const animationFrame = cb => typeof requestAnimationFrame === 'undefined' ? timeout(0, cb) : new Animation(requestAnimationFrame(cb))\n\n/* istanbul ignore next */\n// @ts-ignore\nconst Idle = createTimeoutClass(arg => typeof cancelIdleCallback !== 'undefined' && cancelIdleCallback(arg))\n\n/* istanbul ignore next */\n/**\n * Note: this is experimental and is probably only useful in browsers.\n *\n * @param {function} cb\n * @return {TimeoutObject}\n */\n// @ts-ignore\nexport const idleCallback = cb => typeof requestIdleCallback !== 'undefined' ? new Idle(requestIdleCallback(cb)) : timeout(1000, cb)\n\n/**\n * @param {number} timeout Timeout of the debounce action\n * @return {function(function():void):void}\n */\nexport const createDebouncer = timeout => {\n let timer = -1\n return f => {\n clearTimeout(timer)\n if (f) {\n timer = /** @type {any} */ (setTimeout(f, timeout))\n }\n }\n}\n","/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* istanbul ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n","/**\n * Isomorphic logging module with support for colors!\n *\n * @module logging\n */\n\nimport * as env from './environment.js'\nimport * as symbol from './symbol.js'\nimport * as pair from './pair.js'\nimport * as dom from './dom.js'\nimport * as json from './json.js'\nimport * as map from './map.js'\nimport * as eventloop from './eventloop.js'\nimport * as math from './math.js'\nimport * as time from './time.js'\nimport * as func from './function.js'\n\nexport const BOLD = symbol.create()\nexport const UNBOLD = symbol.create()\nexport const BLUE = symbol.create()\nexport const GREY = symbol.create()\nexport const GREEN = symbol.create()\nexport const RED = symbol.create()\nexport const PURPLE = symbol.create()\nexport const ORANGE = symbol.create()\nexport const UNCOLOR = symbol.create()\n\n/**\n * @type {Object>}\n */\nconst _browserStyleMap = {\n [BOLD]: pair.create('font-weight', 'bold'),\n [UNBOLD]: pair.create('font-weight', 'normal'),\n [BLUE]: pair.create('color', 'blue'),\n [GREEN]: pair.create('color', 'green'),\n [GREY]: pair.create('color', 'grey'),\n [RED]: pair.create('color', 'red'),\n [PURPLE]: pair.create('color', 'purple'),\n [ORANGE]: pair.create('color', 'orange'), // not well supported in chrome when debugging node with inspector - TODO: deprecate\n [UNCOLOR]: pair.create('color', 'black')\n}\n\nconst _nodeStyleMap = {\n [BOLD]: '\\u001b[1m',\n [UNBOLD]: '\\u001b[2m',\n [BLUE]: '\\x1b[34m',\n [GREEN]: '\\x1b[32m',\n [GREY]: '\\u001b[37m',\n [RED]: '\\x1b[31m',\n [PURPLE]: '\\x1b[35m',\n [ORANGE]: '\\x1b[38;5;208m',\n [UNCOLOR]: '\\x1b[0m'\n}\n\n/* istanbul ignore next */\n/**\n * @param {Array} args\n * @return {Array}\n */\nconst computeBrowserLoggingArgs = args => {\n const strBuilder = []\n const styles = []\n const currentStyle = map.create()\n /**\n * @type {Array}\n */\n let logArgs = []\n // try with formatting until we find something unsupported\n let i = 0\n\n for (; i < args.length; i++) {\n const arg = args[i]\n // @ts-ignore\n const style = _browserStyleMap[arg]\n if (style !== undefined) {\n currentStyle.set(style.left, style.right)\n } else {\n if (arg.constructor === String || arg.constructor === Number) {\n const style = dom.mapToStyleString(currentStyle)\n if (i > 0 || style.length > 0) {\n strBuilder.push('%c' + arg)\n styles.push(style)\n } else {\n strBuilder.push(arg)\n }\n } else {\n break\n }\n }\n }\n\n if (i > 0) {\n // create logArgs with what we have so far\n logArgs = styles\n logArgs.unshift(strBuilder.join(''))\n }\n // append the rest\n for (; i < args.length; i++) {\n const arg = args[i]\n if (!(arg instanceof Symbol)) {\n logArgs.push(arg)\n }\n }\n return logArgs\n}\n\n/**\n * @param {Array} args\n * @return {Array}\n */\nconst computeNodeLoggingArgs = args => {\n const strBuilder = []\n const logArgs = []\n\n // try with formatting until we find something unsupported\n let i = 0\n\n for (; i < args.length; i++) {\n const arg = args[i]\n // @ts-ignore\n const style = _nodeStyleMap[arg]\n if (style !== undefined) {\n strBuilder.push(style)\n } else {\n if (arg.constructor === String || arg.constructor === Number) {\n strBuilder.push(arg)\n } else {\n break\n }\n }\n }\n if (i > 0) {\n // create logArgs with what we have so far\n strBuilder.push('\\x1b[0m')\n logArgs.push(strBuilder.join(''))\n }\n // append the rest\n for (; i < args.length; i++) {\n const arg = args[i]\n /* istanbul ignore else */\n if (!(arg instanceof Symbol)) {\n logArgs.push(arg)\n }\n }\n return logArgs\n}\n\n/* istanbul ignore next */\nconst computeLoggingArgs = env.isNode ? computeNodeLoggingArgs : computeBrowserLoggingArgs\n\n/**\n * @param {Array} args\n */\nexport const print = (...args) => {\n console.log(...computeLoggingArgs(args))\n /* istanbul ignore next */\n vconsoles.forEach(vc => vc.print(args))\n}\n\n/* istanbul ignore next */\n/**\n * @param {Array} args\n */\nexport const warn = (...args) => {\n console.warn(...computeLoggingArgs(args))\n args.unshift(ORANGE)\n vconsoles.forEach(vc => vc.print(args))\n}\n\n/* istanbul ignore next */\n/**\n * @param {Error} err\n */\nexport const printError = err => {\n console.error(err)\n vconsoles.forEach(vc => vc.printError(err))\n}\n\n/* istanbul ignore next */\n/**\n * @param {string} url image location\n * @param {number} height height of the image in pixel\n */\nexport const printImg = (url, height) => {\n if (env.isBrowser) {\n console.log('%c ', `font-size: ${height}px; background-size: contain; background-repeat: no-repeat; background-image: url(${url})`)\n // console.log('%c ', `font-size: ${height}x; background: url(${url}) no-repeat;`)\n }\n vconsoles.forEach(vc => vc.printImg(url, height))\n}\n\n/* istanbul ignore next */\n/**\n * @param {string} base64\n * @param {number} height\n */\nexport const printImgBase64 = (base64, height) => printImg(`data:image/gif;base64,${base64}`, height)\n\n/**\n * @param {Array} args\n */\nexport const group = (...args) => {\n console.group(...computeLoggingArgs(args))\n /* istanbul ignore next */\n vconsoles.forEach(vc => vc.group(args))\n}\n\n/**\n * @param {Array} args\n */\nexport const groupCollapsed = (...args) => {\n console.groupCollapsed(...computeLoggingArgs(args))\n /* istanbul ignore next */\n vconsoles.forEach(vc => vc.groupCollapsed(args))\n}\n\nexport const groupEnd = () => {\n console.groupEnd()\n /* istanbul ignore next */\n vconsoles.forEach(vc => vc.groupEnd())\n}\n\n/* istanbul ignore next */\n/**\n * @param {function():Node} createNode\n */\nexport const printDom = createNode =>\n vconsoles.forEach(vc => vc.printDom(createNode()))\n\n/* istanbul ignore next */\n/**\n * @param {HTMLCanvasElement} canvas\n * @param {number} height\n */\nexport const printCanvas = (canvas, height) => printImg(canvas.toDataURL(), height)\n\nexport const vconsoles = new Set()\n\n/* istanbul ignore next */\n/**\n * @param {Array} args\n * @return {Array}\n */\nconst _computeLineSpans = args => {\n const spans = []\n const currentStyle = new Map()\n // try with formatting until we find something unsupported\n let i = 0\n for (; i < args.length; i++) {\n const arg = args[i]\n // @ts-ignore\n const style = _browserStyleMap[arg]\n if (style !== undefined) {\n currentStyle.set(style.left, style.right)\n } else {\n if (arg.constructor === String || arg.constructor === Number) {\n // @ts-ignore\n const span = dom.element('span', [pair.create('style', dom.mapToStyleString(currentStyle))], [dom.text(arg)])\n if (span.innerHTML === '') {\n span.innerHTML = ' '\n }\n spans.push(span)\n } else {\n break\n }\n }\n }\n // append the rest\n for (; i < args.length; i++) {\n let content = args[i]\n if (!(content instanceof Symbol)) {\n if (content.constructor !== String && content.constructor !== Number) {\n content = ' ' + json.stringify(content) + ' '\n }\n spans.push(dom.element('span', [], [dom.text(/** @type {string} */ (content))]))\n }\n }\n return spans\n}\n\nconst lineStyle = 'font-family:monospace;border-bottom:1px solid #e2e2e2;padding:2px;'\n\n/* istanbul ignore next */\nexport class VConsole {\n /**\n * @param {Element} dom\n */\n constructor (dom) {\n this.dom = dom\n /**\n * @type {Element}\n */\n this.ccontainer = this.dom\n this.depth = 0\n vconsoles.add(this)\n }\n\n /**\n * @param {Array} args\n * @param {boolean} collapsed\n */\n group (args, collapsed = false) {\n eventloop.enqueue(() => {\n const triangleDown = dom.element('span', [pair.create('hidden', collapsed), pair.create('style', 'color:grey;font-size:120%;')], [dom.text('▼')])\n const triangleRight = dom.element('span', [pair.create('hidden', !collapsed), pair.create('style', 'color:grey;font-size:125%;')], [dom.text('▶')])\n const content = dom.element('div', [pair.create('style', `${lineStyle};padding-left:${this.depth * 10}px`)], [triangleDown, triangleRight, dom.text(' ')].concat(_computeLineSpans(args)))\n const nextContainer = dom.element('div', [pair.create('hidden', collapsed)])\n const nextLine = dom.element('div', [], [content, nextContainer])\n dom.append(this.ccontainer, [nextLine])\n this.ccontainer = nextContainer\n this.depth++\n // when header is clicked, collapse/uncollapse container\n dom.addEventListener(content, 'click', event => {\n nextContainer.toggleAttribute('hidden')\n triangleDown.toggleAttribute('hidden')\n triangleRight.toggleAttribute('hidden')\n })\n })\n }\n\n /**\n * @param {Array} args\n */\n groupCollapsed (args) {\n this.group(args, true)\n }\n\n groupEnd () {\n eventloop.enqueue(() => {\n if (this.depth > 0) {\n this.depth--\n // @ts-ignore\n this.ccontainer = this.ccontainer.parentElement.parentElement\n }\n })\n }\n\n /**\n * @param {Array} args\n */\n print (args) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [dom.element('div', [pair.create('style', `${lineStyle};padding-left:${this.depth * 10}px`)], _computeLineSpans(args))])\n })\n }\n\n /**\n * @param {Error} err\n */\n printError (err) {\n this.print([RED, BOLD, err.toString()])\n }\n\n /**\n * @param {string} url\n * @param {number} height\n */\n printImg (url, height) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [dom.element('img', [pair.create('src', url), pair.create('height', `${math.round(height * 1.5)}px`)])])\n })\n }\n\n /**\n * @param {Node} node\n */\n printDom (node) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [node])\n })\n }\n\n destroy () {\n eventloop.enqueue(() => {\n vconsoles.delete(this)\n })\n }\n}\n\n/* istanbul ignore next */\n/**\n * @param {Element} dom\n */\nexport const createVConsole = dom => new VConsole(dom)\n\nconst loggingColors = [GREEN, PURPLE, ORANGE, BLUE]\nlet nextColor = 0\nlet lastLoggingTime = time.getUnixTime()\n\n/**\n * @param {string} moduleName\n * @return {function(...any)}\n */\nexport const createModuleLogger = moduleName => {\n const color = loggingColors[nextColor]\n const debugRegexVar = env.getVariable('log')\n const doLogging = debugRegexVar !== null && (debugRegexVar === '*' || debugRegexVar === 'true' || new RegExp(debugRegexVar, 'gi').test(moduleName))\n nextColor = (nextColor + 1) % loggingColors.length\n moduleName += ': '\n\n return !doLogging ? func.nop : (...args) => {\n const timeNow = time.getUnixTime()\n const timeDiff = timeNow - lastLoggingTime\n lastLoggingTime = timeNow\n print(color, moduleName, UNCOLOR, ...args.map(arg => (typeof arg === 'string' || typeof arg === 'symbol') ? arg : JSON.stringify(arg)), color, ' +' + timeDiff + 'ms')\n }\n}\n","/**\n * Utility module to create and manipulate Iterators.\n *\n * @module iterator\n */\n\n/**\n * @template T,R\n * @param {Iterator} iterator\n * @param {function(T):R} f\n * @return {IterableIterator}\n */\nexport const mapIterator = (iterator, f) => ({\n /**\n * @param {function(T):R} f\n */\n [Symbol.iterator] () {\n return this\n },\n // @ts-ignore\n next () {\n const r = iterator.next()\n return { value: r.done ? undefined : f(r.value), done: r.done }\n }\n})\n\n/**\n * @template T\n * @param {function():IteratorResult} next\n * @return {IterableIterator}\n */\nexport const createIterator = next => ({\n /**\n * @return {IterableIterator}\n */\n [Symbol.iterator] () {\n return this\n },\n // @ts-ignore\n next\n})\n\n/**\n * @template T\n * @param {Iterator} iterator\n * @param {function(T):boolean} filter\n */\nexport const iteratorFilter = (iterator, filter) => createIterator(() => {\n let res\n do {\n res = iterator.next()\n } while (!res.done && !filter(res.value))\n return res\n})\n\n/**\n * @template T,M\n * @param {Iterator} iterator\n * @param {function(T):M} fmap\n */\nexport const iteratorMap = (iterator, fmap) => createIterator(() => {\n const { done, value } = iterator.next()\n return { done, value: done ? undefined : fmap(value) }\n})\n","import { Observable } from 'lib0/observable.js';\nimport { appendTo, from, last } from 'lib0/array.js';\nimport { floor, min, max, abs } from 'lib0/math.js';\nimport { setIfUndefined, any, create as create$2, copy } from 'lib0/map.js';\nimport { writeVarUint, Encoder, toUint8Array, IntDiffOptRleEncoder, UintOptRleEncoder, RleEncoder, writeUint8, StringEncoder, createEncoder, writeVarUint8Array, writeUint8Array, writeAny, writeVarString } from 'lib0/encoding.js';\nimport { readVarUint, createDecoder, readUint8, IntDiffOptRleDecoder, readVarUint8Array, UintOptRleDecoder, RleDecoder, StringDecoder, readAny, readVarString } from 'lib0/decoding.js';\nimport { uuidv4, uint32 } from 'lib0/random.js';\nimport { copyUint8Array } from 'lib0/buffer.js';\nimport { unexpectedCase, methodUnimplemented, create as create$1 } from 'lib0/error.js';\nimport { BITS5, BIT8, BIT7, BIT6, BIT2, BIT4, BIT1, BIT3 } from 'lib0/binary.js';\nimport { callAll } from 'lib0/function.js';\nimport { create } from 'lib0/set.js';\nimport { print, ORANGE, BOLD, UNBOLD, RED } from 'lib0/logging.js';\nimport { getUnixTime } from 'lib0/time.js';\nimport { iteratorFilter, iteratorMap } from 'lib0/iterator.js';\nimport { equalFlat } from 'lib0/object.js';\n\n/**\n * This is an abstract interface that all Connectors should implement to keep them interchangeable.\n *\n * @note This interface is experimental and it is not advised to actually inherit this class.\n * It just serves as typing information.\n *\n * @extends {Observable}\n */\nclass AbstractConnector extends Observable {\n /**\n * @param {Doc} ydoc\n * @param {any} awareness\n */\n constructor (ydoc, awareness) {\n super();\n this.doc = ydoc;\n this.awareness = awareness;\n }\n}\n\nclass DeleteItem {\n /**\n * @param {number} clock\n * @param {number} len\n */\n constructor (clock, len) {\n /**\n * @type {number}\n */\n this.clock = clock;\n /**\n * @type {number}\n */\n this.len = len;\n }\n}\n\n/**\n * We no longer maintain a DeleteStore. DeleteSet is a temporary object that is created when needed.\n * - When created in a transaction, it must only be accessed after sorting, and merging\n * - This DeleteSet is send to other clients\n * - We do not create a DeleteSet when we send a sync message. The DeleteSet message is created directly from StructStore\n * - We read a DeleteSet as part of a sync/update message. In this case the DeleteSet is already sorted and merged.\n */\nclass DeleteSet {\n constructor () {\n /**\n * @type {Map>}\n */\n this.clients = new Map();\n }\n}\n\n/**\n * Iterate over all structs that the DeleteSet gc's.\n *\n * @param {Transaction} transaction\n * @param {DeleteSet} ds\n * @param {function(GC|Item):void} f\n *\n * @function\n */\nconst iterateDeletedStructs = (transaction, ds, f) =>\n ds.clients.forEach((deletes, clientid) => {\n const structs = /** @type {Array} */ (transaction.doc.store.clients.get(clientid));\n for (let i = 0; i < deletes.length; i++) {\n const del = deletes[i];\n iterateStructs(transaction, structs, del.clock, del.len, f);\n }\n });\n\n/**\n * @param {Array} dis\n * @param {number} clock\n * @return {number|null}\n *\n * @private\n * @function\n */\nconst findIndexDS = (dis, clock) => {\n let left = 0;\n let right = dis.length - 1;\n while (left <= right) {\n const midindex = floor((left + right) / 2);\n const mid = dis[midindex];\n const midclock = mid.clock;\n if (midclock <= clock) {\n if (clock < midclock + mid.len) {\n return midindex\n }\n left = midindex + 1;\n } else {\n right = midindex - 1;\n }\n }\n return null\n};\n\n/**\n * @param {DeleteSet} ds\n * @param {ID} id\n * @return {boolean}\n *\n * @private\n * @function\n */\nconst isDeleted = (ds, id) => {\n const dis = ds.clients.get(id.client);\n return dis !== undefined && findIndexDS(dis, id.clock) !== null\n};\n\n/**\n * @param {DeleteSet} ds\n *\n * @private\n * @function\n */\nconst sortAndMergeDeleteSet = ds => {\n ds.clients.forEach(dels => {\n dels.sort((a, b) => a.clock - b.clock);\n // merge items without filtering or splicing the array\n // i is the current pointer\n // j refers to the current insert position for the pointed item\n // try to merge dels[i] into dels[j-1] or set dels[j]=dels[i]\n let i, j;\n for (i = 1, j = 1; i < dels.length; i++) {\n const left = dels[j - 1];\n const right = dels[i];\n if (left.clock + left.len === right.clock) {\n left.len += right.len;\n } else {\n if (j < i) {\n dels[j] = right;\n }\n j++;\n }\n }\n dels.length = j;\n });\n};\n\n/**\n * @param {Array} dss\n * @return {DeleteSet} A fresh DeleteSet\n */\nconst mergeDeleteSets = dss => {\n const merged = new DeleteSet();\n for (let dssI = 0; dssI < dss.length; dssI++) {\n dss[dssI].clients.forEach((delsLeft, client) => {\n if (!merged.clients.has(client)) {\n // Write all missing keys from current ds and all following.\n // If merged already contains `client` current ds has already been added.\n /**\n * @type {Array}\n */\n const dels = delsLeft.slice();\n for (let i = dssI + 1; i < dss.length; i++) {\n appendTo(dels, dss[i].clients.get(client) || []);\n }\n merged.clients.set(client, dels);\n }\n });\n }\n sortAndMergeDeleteSet(merged);\n return merged\n};\n\n/**\n * @param {DeleteSet} ds\n * @param {number} client\n * @param {number} clock\n * @param {number} length\n *\n * @private\n * @function\n */\nconst addToDeleteSet = (ds, client, clock, length) => {\n setIfUndefined(ds.clients, client, () => []).push(new DeleteItem(clock, length));\n};\n\nconst createDeleteSet = () => new DeleteSet();\n\n/**\n * @param {StructStore} ss\n * @return {DeleteSet} Merged and sorted DeleteSet\n *\n * @private\n * @function\n */\nconst createDeleteSetFromStructStore = ss => {\n const ds = createDeleteSet();\n ss.clients.forEach((structs, client) => {\n /**\n * @type {Array}\n */\n const dsitems = [];\n for (let i = 0; i < structs.length; i++) {\n const struct = structs[i];\n if (struct.deleted) {\n const clock = struct.id.clock;\n let len = struct.length;\n if (i + 1 < structs.length) {\n for (let next = structs[i + 1]; i + 1 < structs.length && next.id.clock === clock + len && next.deleted; next = structs[++i + 1]) {\n len += next.length;\n }\n }\n dsitems.push(new DeleteItem(clock, len));\n }\n }\n if (dsitems.length > 0) {\n ds.clients.set(client, dsitems);\n }\n });\n return ds\n};\n\n/**\n * @param {AbstractDSEncoder} encoder\n * @param {DeleteSet} ds\n *\n * @private\n * @function\n */\nconst writeDeleteSet = (encoder, ds) => {\n writeVarUint(encoder.restEncoder, ds.clients.size);\n ds.clients.forEach((dsitems, client) => {\n encoder.resetDsCurVal();\n writeVarUint(encoder.restEncoder, client);\n const len = dsitems.length;\n writeVarUint(encoder.restEncoder, len);\n for (let i = 0; i < len; i++) {\n const item = dsitems[i];\n encoder.writeDsClock(item.clock);\n encoder.writeDsLen(item.len);\n }\n });\n};\n\n/**\n * @param {AbstractDSDecoder} decoder\n * @return {DeleteSet}\n *\n * @private\n * @function\n */\nconst readDeleteSet = decoder => {\n const ds = new DeleteSet();\n const numClients = readVarUint(decoder.restDecoder);\n for (let i = 0; i < numClients; i++) {\n decoder.resetDsCurVal();\n const client = readVarUint(decoder.restDecoder);\n const numberOfDeletes = readVarUint(decoder.restDecoder);\n if (numberOfDeletes > 0) {\n const dsField = setIfUndefined(ds.clients, client, () => []);\n for (let i = 0; i < numberOfDeletes; i++) {\n dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen()));\n }\n }\n }\n return ds\n};\n\n/**\n * @todo YDecoder also contains references to String and other Decoders. Would make sense to exchange YDecoder.toUint8Array for YDecoder.DsToUint8Array()..\n */\n\n/**\n * @param {AbstractDSDecoder} decoder\n * @param {Transaction} transaction\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nconst readAndApplyDeleteSet = (decoder, transaction, store) => {\n const unappliedDS = new DeleteSet();\n const numClients = readVarUint(decoder.restDecoder);\n for (let i = 0; i < numClients; i++) {\n decoder.resetDsCurVal();\n const client = readVarUint(decoder.restDecoder);\n const numberOfDeletes = readVarUint(decoder.restDecoder);\n const structs = store.clients.get(client) || [];\n const state = getState(store, client);\n for (let i = 0; i < numberOfDeletes; i++) {\n const clock = decoder.readDsClock();\n const clockEnd = clock + decoder.readDsLen();\n if (clock < state) {\n if (state < clockEnd) {\n addToDeleteSet(unappliedDS, client, state, clockEnd - state);\n }\n let index = findIndexSS(structs, clock);\n /**\n * We can ignore the case of GC and Delete structs, because we are going to skip them\n * @type {Item}\n */\n // @ts-ignore\n let struct = structs[index];\n // split the first item if necessary\n if (!struct.deleted && struct.id.clock < clock) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock));\n index++; // increase we now want to use the next struct\n }\n while (index < structs.length) {\n // @ts-ignore\n struct = structs[index++];\n if (struct.id.clock < clockEnd) {\n if (!struct.deleted) {\n if (clockEnd < struct.id.clock + struct.length) {\n structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock));\n }\n struct.delete(transaction);\n }\n } else {\n break\n }\n }\n } else {\n addToDeleteSet(unappliedDS, client, clock, clockEnd - clock);\n }\n }\n }\n if (unappliedDS.clients.size > 0) {\n // TODO: no need for encoding+decoding ds anymore\n const unappliedDSEncoder = new DSEncoderV2();\n writeDeleteSet(unappliedDSEncoder, unappliedDS);\n store.pendingDeleteReaders.push(new DSDecoderV2(createDecoder((unappliedDSEncoder.toUint8Array()))));\n }\n};\n\n/**\n * @module Y\n */\n\nconst generateNewClientId = uint32;\n\n/**\n * @typedef {Object} DocOpts\n * @property {boolean} [DocOpts.gc=true] Disable garbage collection (default: gc=true)\n * @property {function(Item):boolean} [DocOpts.gcFilter] Will be called before an Item is garbage collected. Return false to keep the Item.\n * @property {string} [DocOpts.guid] Define a globally unique identifier for this document\n * @property {any} [DocOpts.meta] Any kind of meta information you want to associate with this document. If this is a subdocument, remote peers will store the meta information as well.\n * @property {boolean} [DocOpts.autoLoad] If a subdocument, automatically load document. If this is a subdocument, remote peers will load the document as well automatically.\n */\n\n/**\n * A Yjs instance handles the state of shared data.\n * @extends Observable\n */\nclass Doc extends Observable {\n /**\n * @param {DocOpts} [opts] configuration\n */\n constructor ({ guid = uuidv4(), gc = true, gcFilter = () => true, meta = null, autoLoad = false } = {}) {\n super();\n this.gc = gc;\n this.gcFilter = gcFilter;\n this.clientID = generateNewClientId();\n this.guid = guid;\n /**\n * @type {Map>}\n */\n this.share = new Map();\n this.store = new StructStore();\n /**\n * @type {Transaction | null}\n */\n this._transaction = null;\n /**\n * @type {Array}\n */\n this._transactionCleanups = [];\n /**\n * @type {Set}\n */\n this.subdocs = new Set();\n /**\n * If this document is a subdocument - a document integrated into another document - then _item is defined.\n * @type {Item?}\n */\n this._item = null;\n this.shouldLoad = autoLoad;\n this.autoLoad = autoLoad;\n this.meta = meta;\n }\n\n /**\n * Notify the parent document that you request to load data into this subdocument (if it is a subdocument).\n *\n * `load()` might be used in the future to request any provider to load the most current data.\n *\n * It is safe to call `load()` multiple times.\n */\n load () {\n const item = this._item;\n if (item !== null && !this.shouldLoad) {\n transact(/** @type {any} */ (item.parent).doc, transaction => {\n transaction.subdocsLoaded.add(this);\n }, null, true);\n }\n this.shouldLoad = true;\n }\n\n getSubdocs () {\n return this.subdocs\n }\n\n getSubdocGuids () {\n return new Set(Array.from(this.subdocs).map(doc => doc.guid))\n }\n\n /**\n * Changes that happen inside of a transaction are bundled. This means that\n * the observer fires _after_ the transaction is finished and that all changes\n * that happened inside of the transaction are sent as one message to the\n * other peers.\n *\n * @param {function(Transaction):void} f The function that should be executed as a transaction\n * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin\n *\n * @public\n */\n transact (f, origin = null) {\n transact(this, f, origin);\n }\n\n /**\n * Define a shared data type.\n *\n * Multiple calls of `y.get(name, TypeConstructor)` yield the same result\n * and do not overwrite each other. I.e.\n * `y.define(name, Y.Array) === y.define(name, Y.Array)`\n *\n * After this method is called, the type is also available on `y.share.get(name)`.\n *\n * *Best Practices:*\n * Define all types right after the Yjs instance is created and store them in a separate object.\n * Also use the typed methods `getText(name)`, `getArray(name)`, ..\n *\n * @example\n * const y = new Y(..)\n * const appState = {\n * document: y.getText('document')\n * comments: y.getArray('comments')\n * }\n *\n * @param {string} name\n * @param {Function} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ...\n * @return {AbstractType} The created type. Constructed with TypeConstructor\n *\n * @public\n */\n get (name, TypeConstructor = AbstractType) {\n const type = setIfUndefined(this.share, name, () => {\n // @ts-ignore\n const t = new TypeConstructor();\n t._integrate(this, null);\n return t\n });\n const Constr = type.constructor;\n if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) {\n if (Constr === AbstractType) {\n // @ts-ignore\n const t = new TypeConstructor();\n t._map = type._map;\n type._map.forEach(/** @param {Item?} n */ n => {\n for (; n !== null; n = n.left) {\n // @ts-ignore\n n.parent = t;\n }\n });\n t._start = type._start;\n for (let n = t._start; n !== null; n = n.right) {\n n.parent = t;\n }\n t._length = type._length;\n this.share.set(name, t);\n t._integrate(this, null);\n return t\n } else {\n throw new Error(`Type with the name ${name} has already been defined with a different constructor`)\n }\n }\n return type\n }\n\n /**\n * @template T\n * @param {string} [name]\n * @return {YArray}\n *\n * @public\n */\n getArray (name = '') {\n // @ts-ignore\n return this.get(name, YArray)\n }\n\n /**\n * @param {string} [name]\n * @return {YText}\n *\n * @public\n */\n getText (name = '') {\n // @ts-ignore\n return this.get(name, YText)\n }\n\n /**\n * @param {string} [name]\n * @return {YMap}\n *\n * @public\n */\n getMap (name = '') {\n // @ts-ignore\n return this.get(name, YMap)\n }\n\n /**\n * @param {string} [name]\n * @return {YXmlFragment}\n *\n * @public\n */\n getXmlFragment (name = '') {\n // @ts-ignore\n return this.get(name, YXmlFragment)\n }\n\n /**\n * Converts the entire document into a js object, recursively traversing each yjs type\n *\n * @return {Object}\n */\n toJSON () {\n /**\n * @type {Object}\n */\n const doc = {};\n\n this.share.forEach((value, key) => {\n doc[key] = value.toJSON();\n });\n\n return doc\n }\n\n /**\n * Emit `destroy` event and unregister all event handlers.\n */\n destroy () {\n from(this.subdocs).forEach(subdoc => subdoc.destroy());\n const item = this._item;\n if (item !== null) {\n this._item = null;\n const content = /** @type {ContentDoc} */ (item.content);\n if (item.deleted) {\n // @ts-ignore\n content.doc = null;\n } else {\n content.doc = new Doc({ guid: this.guid, ...content.opts });\n content.doc._item = item;\n }\n transact(/** @type {any} */ (item).parent.doc, transaction => {\n if (!item.deleted) {\n transaction.subdocsAdded.add(content.doc);\n }\n transaction.subdocsRemoved.add(this);\n }, null, true);\n }\n this.emit('destroyed', [true]);\n super.destroy();\n }\n\n /**\n * @param {string} eventName\n * @param {function(...any):any} f\n */\n on (eventName, f) {\n super.on(eventName, f);\n }\n\n /**\n * @param {string} eventName\n * @param {function} f\n */\n off (eventName, f) {\n super.off(eventName, f);\n }\n}\n\nclass DSDecoderV1 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n this.restDecoder = decoder;\n }\n\n resetDsCurVal () {\n // nop\n }\n\n /**\n * @return {number}\n */\n readDsClock () {\n return readVarUint(this.restDecoder)\n }\n\n /**\n * @return {number}\n */\n readDsLen () {\n return readVarUint(this.restDecoder)\n }\n}\n\nclass UpdateDecoderV1 extends DSDecoderV1 {\n /**\n * @return {ID}\n */\n readLeftID () {\n return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder))\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder))\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n */\n readClient () {\n return readVarUint(this.restDecoder)\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n return readUint8(this.restDecoder)\n }\n\n /**\n * @return {string}\n */\n readString () {\n return readVarString(this.restDecoder)\n }\n\n /**\n * @return {boolean} isKey\n */\n readParentInfo () {\n return readVarUint(this.restDecoder) === 1\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readTypeRef () {\n return readVarUint(this.restDecoder)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number} len\n */\n readLen () {\n return readVarUint(this.restDecoder)\n }\n\n /**\n * @return {any}\n */\n readAny () {\n return readAny(this.restDecoder)\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n return copyUint8Array(readVarUint8Array(this.restDecoder))\n }\n\n /**\n * Legacy implementation uses JSON parse. We use any-decoding in v2.\n *\n * @return {any}\n */\n readJSON () {\n return JSON.parse(readVarString(this.restDecoder))\n }\n\n /**\n * @return {string}\n */\n readKey () {\n return readVarString(this.restDecoder)\n }\n}\n\nclass DSDecoderV2 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n this.dsCurrVal = 0;\n this.restDecoder = decoder;\n }\n\n resetDsCurVal () {\n this.dsCurrVal = 0;\n }\n\n readDsClock () {\n this.dsCurrVal += readVarUint(this.restDecoder);\n return this.dsCurrVal\n }\n\n readDsLen () {\n const diff = readVarUint(this.restDecoder) + 1;\n this.dsCurrVal += diff;\n return diff\n }\n}\n\nclass UpdateDecoderV2 extends DSDecoderV2 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n super(decoder);\n /**\n * List of cached keys. If the keys[id] does not exist, we read a new key\n * from stringEncoder and push it to keys.\n *\n * @type {Array}\n */\n this.keys = [];\n readUint8(decoder); // read feature flag - currently unused\n this.keyClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));\n this.clientDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));\n this.leftClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));\n this.rightClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));\n this.infoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8);\n this.stringDecoder = new StringDecoder(readVarUint8Array(decoder));\n this.parentInfoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8);\n this.typeRefDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));\n this.lenDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));\n }\n\n /**\n * @return {ID}\n */\n readLeftID () {\n return new ID(this.clientDecoder.read(), this.leftClockDecoder.read())\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n return new ID(this.clientDecoder.read(), this.rightClockDecoder.read())\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n */\n readClient () {\n return this.clientDecoder.read()\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n return /** @type {number} */ (this.infoDecoder.read())\n }\n\n /**\n * @return {string}\n */\n readString () {\n return this.stringDecoder.read()\n }\n\n /**\n * @return {boolean}\n */\n readParentInfo () {\n return this.parentInfoDecoder.read() === 1\n }\n\n /**\n * @return {number} An unsigned 8-bit integer\n */\n readTypeRef () {\n return this.typeRefDecoder.read()\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number}\n */\n readLen () {\n return this.lenDecoder.read()\n }\n\n /**\n * @return {any}\n */\n readAny () {\n return readAny(this.restDecoder)\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n return readVarUint8Array(this.restDecoder)\n }\n\n /**\n * This is mainly here for legacy purposes.\n *\n * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.\n *\n * @return {any}\n */\n readJSON () {\n return readAny(this.restDecoder)\n }\n\n /**\n * @return {string}\n */\n readKey () {\n const keyClock = this.keyClockDecoder.read();\n if (keyClock < this.keys.length) {\n return this.keys[keyClock]\n } else {\n const key = this.stringDecoder.read();\n this.keys.push(key);\n return key\n }\n }\n}\n\nclass DSEncoderV1 {\n constructor () {\n this.restEncoder = new Encoder();\n }\n\n toUint8Array () {\n return toUint8Array(this.restEncoder)\n }\n\n resetDsCurVal () {\n // nop\n }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) {\n writeVarUint(this.restEncoder, clock);\n }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) {\n writeVarUint(this.restEncoder, len);\n }\n}\n\nclass UpdateEncoderV1 extends DSEncoderV1 {\n /**\n * @param {ID} id\n */\n writeLeftID (id) {\n writeVarUint(this.restEncoder, id.client);\n writeVarUint(this.restEncoder, id.clock);\n }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) {\n writeVarUint(this.restEncoder, id.client);\n writeVarUint(this.restEncoder, id.clock);\n }\n\n /**\n * Use writeClient and writeClock instead of writeID if possible.\n * @param {number} client\n */\n writeClient (client) {\n writeVarUint(this.restEncoder, client);\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) {\n writeUint8(this.restEncoder, info);\n }\n\n /**\n * @param {string} s\n */\n writeString (s) {\n writeVarString(this.restEncoder, s);\n }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) {\n writeVarUint(this.restEncoder, isYKey ? 1 : 0);\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) {\n writeVarUint(this.restEncoder, info);\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) {\n writeVarUint(this.restEncoder, len);\n }\n\n /**\n * @param {any} any\n */\n writeAny (any) {\n writeAny(this.restEncoder, any);\n }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) {\n writeVarUint8Array(this.restEncoder, buf);\n }\n\n /**\n * @param {any} embed\n */\n writeJSON (embed) {\n writeVarString(this.restEncoder, JSON.stringify(embed));\n }\n\n /**\n * @param {string} key\n */\n writeKey (key) {\n writeVarString(this.restEncoder, key);\n }\n}\n\nclass DSEncoderV2 {\n constructor () {\n this.restEncoder = new Encoder(); // encodes all the rest / non-optimized\n this.dsCurrVal = 0;\n }\n\n toUint8Array () {\n return toUint8Array(this.restEncoder)\n }\n\n resetDsCurVal () {\n this.dsCurrVal = 0;\n }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) {\n const diff = clock - this.dsCurrVal;\n this.dsCurrVal = clock;\n writeVarUint(this.restEncoder, diff);\n }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) {\n if (len === 0) {\n unexpectedCase();\n }\n writeVarUint(this.restEncoder, len - 1);\n this.dsCurrVal += len;\n }\n}\n\nclass UpdateEncoderV2 extends DSEncoderV2 {\n constructor () {\n super();\n /**\n * @type {Map}\n */\n this.keyMap = new Map();\n /**\n * Refers to the next uniqe key-identifier to me used.\n * See writeKey method for more information.\n *\n * @type {number}\n */\n this.keyClock = 0;\n this.keyClockEncoder = new IntDiffOptRleEncoder();\n this.clientEncoder = new UintOptRleEncoder();\n this.leftClockEncoder = new IntDiffOptRleEncoder();\n this.rightClockEncoder = new IntDiffOptRleEncoder();\n this.infoEncoder = new RleEncoder(writeUint8);\n this.stringEncoder = new StringEncoder();\n this.parentInfoEncoder = new RleEncoder(writeUint8);\n this.typeRefEncoder = new UintOptRleEncoder();\n this.lenEncoder = new UintOptRleEncoder();\n }\n\n toUint8Array () {\n const encoder = createEncoder();\n writeUint8(encoder, 0); // this is a feature flag that we might use in the future\n writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array());\n writeVarUint8Array(encoder, this.clientEncoder.toUint8Array());\n writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array());\n writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array());\n writeVarUint8Array(encoder, toUint8Array(this.infoEncoder));\n writeVarUint8Array(encoder, this.stringEncoder.toUint8Array());\n writeVarUint8Array(encoder, toUint8Array(this.parentInfoEncoder));\n writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array());\n writeVarUint8Array(encoder, this.lenEncoder.toUint8Array());\n // @note The rest encoder is appended! (note the missing var)\n writeUint8Array(encoder, toUint8Array(this.restEncoder));\n return toUint8Array(encoder)\n }\n\n /**\n * @param {ID} id\n */\n writeLeftID (id) {\n this.clientEncoder.write(id.client);\n this.leftClockEncoder.write(id.clock);\n }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) {\n this.clientEncoder.write(id.client);\n this.rightClockEncoder.write(id.clock);\n }\n\n /**\n * @param {number} client\n */\n writeClient (client) {\n this.clientEncoder.write(client);\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) {\n this.infoEncoder.write(info);\n }\n\n /**\n * @param {string} s\n */\n writeString (s) {\n this.stringEncoder.write(s);\n }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) {\n this.parentInfoEncoder.write(isYKey ? 1 : 0);\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) {\n this.typeRefEncoder.write(info);\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) {\n this.lenEncoder.write(len);\n }\n\n /**\n * @param {any} any\n */\n writeAny (any) {\n writeAny(this.restEncoder, any);\n }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) {\n writeVarUint8Array(this.restEncoder, buf);\n }\n\n /**\n * This is mainly here for legacy purposes.\n *\n * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.\n *\n * @param {any} embed\n */\n writeJSON (embed) {\n writeAny(this.restEncoder, embed);\n }\n\n /**\n * Property keys are often reused. For example, in y-prosemirror the key `bold` might\n * occur very often. For a 3d application, the key `position` might occur very often.\n *\n * We cache these keys in a Map and refer to them via a unique number.\n *\n * @param {string} key\n */\n writeKey (key) {\n const clock = this.keyMap.get(key);\n if (clock === undefined) {\n this.keyClockEncoder.write(this.keyClock++);\n this.stringEncoder.write(key);\n } else {\n this.keyClockEncoder.write(this.keyClock++);\n }\n }\n}\n\nlet DefaultDSEncoder = DSEncoderV1;\nlet DefaultDSDecoder = DSDecoderV1;\nlet DefaultUpdateEncoder = UpdateEncoderV1;\nlet DefaultUpdateDecoder = UpdateDecoderV1;\n\n/**\n * @param {AbstractUpdateEncoder} encoder\n * @param {Array} structs All structs by `client`\n * @param {number} client\n * @param {number} clock write structs starting with `ID(client,clock)`\n *\n * @function\n */\nconst writeStructs = (encoder, structs, client, clock) => {\n // write first id\n const startNewStructs = findIndexSS(structs, clock);\n // write # encoded structs\n writeVarUint(encoder.restEncoder, structs.length - startNewStructs);\n encoder.writeClient(client);\n writeVarUint(encoder.restEncoder, clock);\n const firstStruct = structs[startNewStructs];\n // write first struct with an offset\n firstStruct.write(encoder, clock - firstStruct.id.clock);\n for (let i = startNewStructs + 1; i < structs.length; i++) {\n structs[i].write(encoder, 0);\n }\n};\n\n/**\n * @param {AbstractUpdateEncoder} encoder\n * @param {StructStore} store\n * @param {Map} _sm\n *\n * @private\n * @function\n */\nconst writeClientsStructs = (encoder, store, _sm) => {\n // we filter all valid _sm entries into sm\n const sm = new Map();\n _sm.forEach((clock, client) => {\n // only write if new structs are available\n if (getState(store, client) > clock) {\n sm.set(client, clock);\n }\n });\n getStateVector(store).forEach((clock, client) => {\n if (!_sm.has(client)) {\n sm.set(client, 0);\n }\n });\n // write # states that were updated\n writeVarUint(encoder.restEncoder, sm.size);\n // Write items with higher client ids first\n // This heavily improves the conflict algorithm.\n Array.from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {\n // @ts-ignore\n writeStructs(encoder, store.clients.get(client), client, clock);\n });\n};\n\n/**\n * @param {AbstractUpdateDecoder} decoder The decoder object to read data from.\n * @param {Map>} clientRefs\n * @param {Doc} doc\n * @return {Map>}\n *\n * @private\n * @function\n */\nconst readClientsStructRefs = (decoder, clientRefs, doc) => {\n const numOfStateUpdates = readVarUint(decoder.restDecoder);\n for (let i = 0; i < numOfStateUpdates; i++) {\n const numberOfStructs = readVarUint(decoder.restDecoder);\n /**\n * @type {Array}\n */\n const refs = new Array(numberOfStructs);\n const client = decoder.readClient();\n let clock = readVarUint(decoder.restDecoder);\n // const start = performance.now()\n clientRefs.set(client, refs);\n for (let i = 0; i < numberOfStructs; i++) {\n const info = decoder.readInfo();\n if ((BITS5 & info) !== 0) {\n /**\n * The optimized implementation doesn't use any variables because inlining variables is faster.\n * Below a non-optimized version is shown that implements the basic algorithm with\n * a few comments\n */\n const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0;\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const struct = new Item(\n createID(client, clock),\n null, // leftd\n (info & BIT8) === BIT8 ? decoder.readLeftID() : null, // origin\n null, // right\n (info & BIT7) === BIT7 ? decoder.readRightID() : null, // right origin\n cantCopyParentInfo ? (decoder.readParentInfo() ? doc.get(decoder.readString()) : decoder.readLeftID()) : null, // parent\n cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n );\n /* A non-optimized implementation of the above algorithm:\n\n // The item that was originally to the left of this item.\n const origin = (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null\n // The item that was originally to the right of this item.\n const rightOrigin = (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0\n const hasParentYKey = cantCopyParentInfo ? decoder.readParentInfo() : false\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const parentYKey = cantCopyParentInfo && hasParentYKey ? decoder.readString() : null\n\n const struct = new Item(\n createID(client, clock),\n null, // leftd\n origin, // origin\n null, // right\n rightOrigin, // right origin\n cantCopyParentInfo && !hasParentYKey ? decoder.readLeftID() : (parentYKey !== null ? doc.get(parentYKey) : null), // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n )\n */\n refs[i] = struct;\n clock += struct.length;\n } else {\n const len = decoder.readLen();\n refs[i] = new GC(createID(client, clock), len);\n clock += len;\n }\n }\n // console.log('time to read: ', performance.now() - start) // @todo remove\n }\n return clientRefs\n};\n\n/**\n * Resume computing structs generated by struct readers.\n *\n * While there is something to do, we integrate structs in this order\n * 1. top element on stack, if stack is not empty\n * 2. next element from current struct reader (if empty, use next struct reader)\n *\n * If struct causally depends on another struct (ref.missing), we put next reader of\n * `ref.id.client` on top of stack.\n *\n * At some point we find a struct that has no causal dependencies,\n * then we start emptying the stack.\n *\n * It is not possible to have circles: i.e. struct1 (from client1) depends on struct2 (from client2)\n * depends on struct3 (from client1). Therefore the max stack size is eqaul to `structReaders.length`.\n *\n * This method is implemented in a way so that we can resume computation if this update\n * causally depends on another update.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nconst resumeStructIntegration = (transaction, store) => {\n const stack = store.pendingStack; // @todo don't forget to append stackhead at the end\n const clientsStructRefs = store.pendingClientsStructRefs;\n // sort them so that we take the higher id first, in case of conflicts the lower id will probably not conflict with the id from the higher user.\n const clientsStructRefsIds = Array.from(clientsStructRefs.keys()).sort((a, b) => a - b);\n if (clientsStructRefsIds.length === 0) {\n return\n }\n const getNextStructTarget = () => {\n let nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]));\n while (nextStructsTarget.refs.length === nextStructsTarget.i) {\n clientsStructRefsIds.pop();\n if (clientsStructRefsIds.length > 0) {\n nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]));\n } else {\n store.pendingClientsStructRefs.clear();\n return null\n }\n }\n return nextStructsTarget\n };\n let curStructsTarget = getNextStructTarget();\n if (curStructsTarget === null && stack.length === 0) {\n return\n }\n /**\n * @type {GC|Item}\n */\n let stackHead = stack.length > 0\n ? /** @type {GC|Item} */ (stack.pop())\n : /** @type {any} */ (curStructsTarget).refs[/** @type {any} */ (curStructsTarget).i++];\n // caching the state because it is used very often\n const state = new Map();\n // iterate over all struct readers until we are done\n while (true) {\n const localClock = setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client));\n const offset = stackHead.id.clock < localClock ? localClock - stackHead.id.clock : 0;\n if (stackHead.id.clock + offset !== localClock) {\n // A previous message from this client is missing\n // check if there is a pending structRef with a smaller clock and switch them\n /**\n * @type {{ refs: Array, i: number }}\n */\n const structRefs = clientsStructRefs.get(stackHead.id.client) || { refs: [], i: 0 };\n if (structRefs.refs.length !== structRefs.i) {\n const r = structRefs.refs[structRefs.i];\n if (r.id.clock < stackHead.id.clock) {\n // put ref with smaller clock on stack instead and continue\n structRefs.refs[structRefs.i] = stackHead;\n stackHead = r;\n // sort the set because this approach might bring the list out of order\n structRefs.refs = structRefs.refs.slice(structRefs.i).sort((r1, r2) => r1.id.clock - r2.id.clock);\n structRefs.i = 0;\n continue\n }\n }\n // wait until missing struct is available\n stack.push(stackHead);\n return\n }\n const missing = stackHead.getMissing(transaction, store);\n if (missing === null) {\n if (offset === 0 || offset < stackHead.length) {\n stackHead.integrate(transaction, offset);\n state.set(stackHead.id.client, stackHead.id.clock + stackHead.length);\n }\n // iterate to next stackHead\n if (stack.length > 0) {\n stackHead = /** @type {GC|Item} */ (stack.pop());\n } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) {\n stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++]);\n } else {\n curStructsTarget = getNextStructTarget();\n if (curStructsTarget === null) {\n // we are done!\n break\n } else {\n stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++]);\n }\n }\n } else {\n // get the struct reader that has the missing struct\n /**\n * @type {{ refs: Array, i: number }}\n */\n const structRefs = clientsStructRefs.get(missing) || { refs: [], i: 0 };\n if (structRefs.refs.length === structRefs.i) {\n // This update message causally depends on another update message.\n stack.push(stackHead);\n return\n }\n stack.push(stackHead);\n stackHead = structRefs.refs[structRefs.i++];\n }\n }\n store.pendingClientsStructRefs.clear();\n};\n\n/**\n * @param {Transaction} transaction\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nconst tryResumePendingDeleteReaders = (transaction, store) => {\n const pendingReaders = store.pendingDeleteReaders;\n store.pendingDeleteReaders = [];\n for (let i = 0; i < pendingReaders.length; i++) {\n readAndApplyDeleteSet(pendingReaders[i], transaction, store);\n }\n};\n\n/**\n * @param {AbstractUpdateEncoder} encoder\n * @param {Transaction} transaction\n *\n * @private\n * @function\n */\nconst writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState);\n\n/**\n * @param {StructStore} store\n * @param {Map>} clientsStructsRefs\n *\n * @private\n * @function\n */\nconst mergeReadStructsIntoPendingReads = (store, clientsStructsRefs) => {\n const pendingClientsStructRefs = store.pendingClientsStructRefs;\n clientsStructsRefs.forEach((structRefs, client) => {\n const pendingStructRefs = pendingClientsStructRefs.get(client);\n if (pendingStructRefs === undefined) {\n pendingClientsStructRefs.set(client, { refs: structRefs, i: 0 });\n } else {\n // merge into existing structRefs\n const merged = pendingStructRefs.i > 0 ? pendingStructRefs.refs.slice(pendingStructRefs.i) : pendingStructRefs.refs;\n for (let i = 0; i < structRefs.length; i++) {\n merged.push(structRefs[i]);\n }\n pendingStructRefs.i = 0;\n pendingStructRefs.refs = merged.sort((r1, r2) => r1.id.clock - r2.id.clock);\n }\n });\n};\n\n/**\n * @param {Map,i:number}>} pendingClientsStructRefs\n */\nconst cleanupPendingStructs = pendingClientsStructRefs => {\n // cleanup pendingClientsStructs if not fully finished\n pendingClientsStructRefs.forEach((refs, client) => {\n if (refs.i === refs.refs.length) {\n pendingClientsStructRefs.delete(client);\n } else {\n refs.refs.splice(0, refs.i);\n refs.i = 0;\n }\n });\n};\n\n/**\n * Read the next Item in a Decoder and fill this Item with the read data.\n *\n * This is called when data is received from a remote peer.\n *\n * @param {AbstractUpdateDecoder} decoder The decoder object to read data from.\n * @param {Transaction} transaction\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nconst readStructs = (decoder, transaction, store) => {\n const clientsStructRefs = new Map();\n // let start = performance.now()\n readClientsStructRefs(decoder, clientsStructRefs, transaction.doc);\n // console.log('time to read structs: ', performance.now() - start) // @todo remove\n // start = performance.now()\n mergeReadStructsIntoPendingReads(store, clientsStructRefs);\n // console.log('time to merge: ', performance.now() - start) // @todo remove\n // start = performance.now()\n resumeStructIntegration(transaction, store);\n // console.log('time to integrate: ', performance.now() - start) // @todo remove\n // start = performance.now()\n cleanupPendingStructs(store.pendingClientsStructRefs);\n // console.log('time to cleanup: ', performance.now() - start) // @todo remove\n // start = performance.now()\n tryResumePendingDeleteReaders(transaction, store);\n // console.log('time to resume delete readers: ', performance.now() - start) // @todo remove\n // start = performance.now()\n};\n\n/**\n * Read and apply a document update.\n *\n * This function has the same effect as `applyUpdate` but accepts an decoder.\n *\n * @param {decoding.Decoder} decoder\n * @param {Doc} ydoc\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n * @param {AbstractUpdateDecoder} [structDecoder]\n *\n * @function\n */\nconst readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) =>\n transact(ydoc, transaction => {\n readStructs(structDecoder, transaction, ydoc.store);\n readAndApplyDeleteSet(structDecoder, transaction, ydoc.store);\n }, transactionOrigin, false);\n\n/**\n * Read and apply a document update.\n *\n * This function has the same effect as `applyUpdate` but accepts an decoder.\n *\n * @param {decoding.Decoder} decoder\n * @param {Doc} ydoc\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n *\n * @function\n */\nconst readUpdate = (decoder, ydoc, transactionOrigin) => readUpdateV2(decoder, ydoc, transactionOrigin, new DefaultUpdateDecoder(decoder));\n\n/**\n * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.\n *\n * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.\n *\n * @param {Doc} ydoc\n * @param {Uint8Array} update\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder]\n *\n * @function\n */\nconst applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => {\n const decoder = createDecoder(update);\n readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder));\n};\n\n/**\n * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.\n *\n * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.\n *\n * @param {Doc} ydoc\n * @param {Uint8Array} update\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n *\n * @function\n */\nconst applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, DefaultUpdateDecoder);\n\n/**\n * Write all the document as a single update message. If you specify the state of the remote client (`targetStateVector`) it will\n * only write the operations that are missing.\n *\n * @param {AbstractUpdateEncoder} encoder\n * @param {Doc} doc\n * @param {Map} [targetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n *\n * @function\n */\nconst writeStateAsUpdate = (encoder, doc, targetStateVector = new Map()) => {\n writeClientsStructs(encoder, doc.store, targetStateVector);\n writeDeleteSet(encoder, createDeleteSetFromStructStore(doc.store));\n};\n\n/**\n * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will\n * only write the operations that are missing.\n *\n * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder\n *\n * @param {Doc} doc\n * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n * @param {AbstractUpdateEncoder} [encoder]\n * @return {Uint8Array}\n *\n * @function\n */\nconst encodeStateAsUpdateV2 = (doc, encodedTargetStateVector, encoder = new UpdateEncoderV2()) => {\n const targetStateVector = encodedTargetStateVector == null ? new Map() : decodeStateVector(encodedTargetStateVector);\n writeStateAsUpdate(encoder, doc, targetStateVector);\n return encoder.toUint8Array()\n};\n\n/**\n * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will\n * only write the operations that are missing.\n *\n * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder\n *\n * @param {Doc} doc\n * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n * @return {Uint8Array}\n *\n * @function\n */\nconst encodeStateAsUpdate = (doc, encodedTargetStateVector) => encodeStateAsUpdateV2(doc, encodedTargetStateVector, new DefaultUpdateEncoder());\n\n/**\n * Read state vector from Decoder and return as Map\n *\n * @param {AbstractDSDecoder} decoder\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nconst readStateVector = decoder => {\n const ss = new Map();\n const ssLength = readVarUint(decoder.restDecoder);\n for (let i = 0; i < ssLength; i++) {\n const client = readVarUint(decoder.restDecoder);\n const clock = readVarUint(decoder.restDecoder);\n ss.set(client, clock);\n }\n return ss\n};\n\n/**\n * Read decodedState and return State as Map.\n *\n * @param {Uint8Array} decodedState\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nconst decodeStateVectorV2 = decodedState => readStateVector(new DSDecoderV2(createDecoder(decodedState)));\n\n/**\n * Read decodedState and return State as Map.\n *\n * @param {Uint8Array} decodedState\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nconst decodeStateVector = decodedState => readStateVector(new DefaultDSDecoder(createDecoder(decodedState)));\n\n/**\n * @param {AbstractDSEncoder} encoder\n * @param {Map} sv\n * @function\n */\nconst writeStateVector = (encoder, sv) => {\n writeVarUint(encoder.restEncoder, sv.size);\n sv.forEach((clock, client) => {\n writeVarUint(encoder.restEncoder, client); // @todo use a special client decoder that is based on mapping\n writeVarUint(encoder.restEncoder, clock);\n });\n return encoder\n};\n\n/**\n * @param {AbstractDSEncoder} encoder\n * @param {Doc} doc\n *\n * @function\n */\nconst writeDocumentStateVector = (encoder, doc) => writeStateVector(encoder, getStateVector(doc.store));\n\n/**\n * Encode State as Uint8Array.\n *\n * @param {Doc} doc\n * @param {AbstractDSEncoder} [encoder]\n * @return {Uint8Array}\n *\n * @function\n */\nconst encodeStateVectorV2 = (doc, encoder = new DSEncoderV2()) => {\n writeDocumentStateVector(encoder, doc);\n return encoder.toUint8Array()\n};\n\n/**\n * Encode State as Uint8Array.\n *\n * @param {Doc} doc\n * @return {Uint8Array}\n *\n * @function\n */\nconst encodeStateVector = doc => encodeStateVectorV2(doc, new DefaultDSEncoder());\n\n/**\n * General event handler implementation.\n *\n * @template ARG0, ARG1\n *\n * @private\n */\nclass EventHandler {\n constructor () {\n /**\n * @type {Array}\n */\n this.l = [];\n }\n}\n\n/**\n * @template ARG0,ARG1\n * @returns {EventHandler}\n *\n * @private\n * @function\n */\nconst createEventHandler = () => new EventHandler();\n\n/**\n * Adds an event listener that is called when\n * {@link EventHandler#callEventListeners} is called.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {function(ARG0,ARG1):void} f The event handler.\n *\n * @private\n * @function\n */\nconst addEventHandlerListener = (eventHandler, f) =>\n eventHandler.l.push(f);\n\n/**\n * Removes an event listener.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {function(ARG0,ARG1):void} f The event handler that was added with\n * {@link EventHandler#addEventListener}\n *\n * @private\n * @function\n */\nconst removeEventHandlerListener = (eventHandler, f) => {\n const l = eventHandler.l;\n const len = l.length;\n eventHandler.l = l.filter(g => f !== g);\n if (len === eventHandler.l.length) {\n console.error('[yjs] Tried to remove event handler that doesn\\'t exist.');\n }\n};\n\n/**\n * Call all event listeners that were added via\n * {@link EventHandler#addEventListener}.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {ARG0} arg0\n * @param {ARG1} arg1\n *\n * @private\n * @function\n */\nconst callEventHandlerListeners = (eventHandler, arg0, arg1) =>\n callAll(eventHandler.l, [arg0, arg1]);\n\nclass ID {\n /**\n * @param {number} client client id\n * @param {number} clock unique per client id, continuous number\n */\n constructor (client, clock) {\n /**\n * Client id\n * @type {number}\n */\n this.client = client;\n /**\n * unique per client id, continuous number\n * @type {number}\n */\n this.clock = clock;\n }\n}\n\n/**\n * @param {ID | null} a\n * @param {ID | null} b\n * @return {boolean}\n *\n * @function\n */\nconst compareIDs = (a, b) => a === b || (a !== null && b !== null && a.client === b.client && a.clock === b.clock);\n\n/**\n * @param {number} client\n * @param {number} clock\n *\n * @private\n * @function\n */\nconst createID = (client, clock) => new ID(client, clock);\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {ID} id\n *\n * @private\n * @function\n */\nconst writeID = (encoder, id) => {\n writeVarUint(encoder, id.client);\n writeVarUint(encoder, id.clock);\n};\n\n/**\n * Read ID.\n * * If first varUint read is 0xFFFFFF a RootID is returned.\n * * Otherwise an ID is returned\n *\n * @param {decoding.Decoder} decoder\n * @return {ID}\n *\n * @private\n * @function\n */\nconst readID = decoder =>\n createID(readVarUint(decoder), readVarUint(decoder));\n\n/**\n * The top types are mapped from y.share.get(keyname) => type.\n * `type` does not store any information about the `keyname`.\n * This function finds the correct `keyname` for `type` and throws otherwise.\n *\n * @param {AbstractType} type\n * @return {string}\n *\n * @private\n * @function\n */\nconst findRootTypeKey = type => {\n // @ts-ignore _y must be defined, otherwise unexpected case\n for (const [key, value] of type.doc.share.entries()) {\n if (value === type) {\n return key\n }\n }\n throw unexpectedCase()\n};\n\n/**\n * Check if `parent` is a parent of `child`.\n *\n * @param {AbstractType} parent\n * @param {Item|null} child\n * @return {Boolean} Whether `parent` is a parent of `child`.\n *\n * @private\n * @function\n */\nconst isParentOf = (parent, child) => {\n while (child !== null) {\n if (child.parent === parent) {\n return true\n }\n child = /** @type {AbstractType} */ (child.parent)._item;\n }\n return false\n};\n\n/**\n * Convenient helper to log type information.\n *\n * Do not use in productive systems as the output can be immense!\n *\n * @param {AbstractType} type\n */\nconst logType = type => {\n const res = [];\n let n = type._start;\n while (n) {\n res.push(n);\n n = n.right;\n }\n console.log('Children: ', res);\n console.log('Children content: ', res.filter(m => !m.deleted).map(m => m.content));\n};\n\nclass PermanentUserData {\n /**\n * @param {Doc} doc\n * @param {YMap} [storeType]\n */\n constructor (doc, storeType = doc.getMap('users')) {\n /**\n * @type {Map}\n */\n const dss = new Map();\n this.yusers = storeType;\n this.doc = doc;\n /**\n * Maps from clientid to userDescription\n *\n * @type {Map}\n */\n this.clients = new Map();\n this.dss = dss;\n /**\n * @param {YMap} user\n * @param {string} userDescription\n */\n const initUser = (user, userDescription) => {\n /**\n * @type {YArray}\n */\n const ds = user.get('ds');\n const ids = user.get('ids');\n const addClientId = /** @param {number} clientid */ clientid => this.clients.set(clientid, userDescription);\n ds.observe(/** @param {YArrayEvent} event */ event => {\n event.changes.added.forEach(item => {\n item.content.getContent().forEach(encodedDs => {\n if (encodedDs instanceof Uint8Array) {\n this.dss.set(userDescription, mergeDeleteSets([this.dss.get(userDescription) || createDeleteSet(), readDeleteSet(new DSDecoderV1(createDecoder(encodedDs)))]));\n }\n });\n });\n });\n this.dss.set(userDescription, mergeDeleteSets(ds.map(encodedDs => readDeleteSet(new DSDecoderV1(createDecoder(encodedDs))))));\n ids.observe(/** @param {YArrayEvent} event */ event =>\n event.changes.added.forEach(item => item.content.getContent().forEach(addClientId))\n );\n ids.forEach(addClientId);\n };\n // observe users\n storeType.observe(event => {\n event.keysChanged.forEach(userDescription =>\n initUser(storeType.get(userDescription), userDescription)\n );\n });\n // add intial data\n storeType.forEach(initUser);\n }\n\n /**\n * @param {Doc} doc\n * @param {number} clientid\n * @param {string} userDescription\n * @param {Object} [conf]\n * @param {function(Transaction, DeleteSet):boolean} [conf.filter]\n */\n setUserMapping (doc, clientid, userDescription, { filter = () => true } = {}) {\n const users = this.yusers;\n let user = users.get(userDescription);\n if (!user) {\n user = new YMap();\n user.set('ids', new YArray());\n user.set('ds', new YArray());\n users.set(userDescription, user);\n }\n user.get('ids').push([clientid]);\n users.observe(event => {\n setTimeout(() => {\n const userOverwrite = users.get(userDescription);\n if (userOverwrite !== user) {\n // user was overwritten, port all data over to the next user object\n // @todo Experiment with Y.Sets here\n user = userOverwrite;\n // @todo iterate over old type\n this.clients.forEach((_userDescription, clientid) => {\n if (userDescription === _userDescription) {\n user.get('ids').push([clientid]);\n }\n });\n const encoder = new DSEncoderV1();\n const ds = this.dss.get(userDescription);\n if (ds) {\n writeDeleteSet(encoder, ds);\n user.get('ds').push([encoder.toUint8Array()]);\n }\n }\n }, 0);\n });\n doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => {\n setTimeout(() => {\n const yds = user.get('ds');\n const ds = transaction.deleteSet;\n if (transaction.local && ds.clients.size > 0 && filter(transaction, ds)) {\n const encoder = new DSEncoderV1();\n writeDeleteSet(encoder, ds);\n yds.push([encoder.toUint8Array()]);\n }\n });\n });\n }\n\n /**\n * @param {number} clientid\n * @return {any}\n */\n getUserByClientId (clientid) {\n return this.clients.get(clientid) || null\n }\n\n /**\n * @param {ID} id\n * @return {string | null}\n */\n getUserByDeletedId (id) {\n for (const [userDescription, ds] of this.dss.entries()) {\n if (isDeleted(ds, id)) {\n return userDescription\n }\n }\n return null\n }\n}\n\n/**\n * A relative position is based on the Yjs model and is not affected by document changes.\n * E.g. If you place a relative position before a certain character, it will always point to this character.\n * If you place a relative position at the end of a type, it will always point to the end of the type.\n *\n * A numeric position is often unsuited for user selections, because it does not change when content is inserted\n * before or after.\n *\n * ```Insert(0, 'x')('a|bc') = 'xa|bc'``` Where | is the relative position.\n *\n * One of the properties must be defined.\n *\n * @example\n * // Current cursor position is at position 10\n * const relativePosition = createRelativePositionFromIndex(yText, 10)\n * // modify yText\n * yText.insert(0, 'abc')\n * yText.delete(3, 10)\n * // Compute the cursor position\n * const absolutePosition = createAbsolutePositionFromRelativePosition(y, relativePosition)\n * absolutePosition.type === yText // => true\n * console.log('cursor location is ' + absolutePosition.index) // => cursor location is 3\n *\n */\nclass RelativePosition {\n /**\n * @param {ID|null} type\n * @param {string|null} tname\n * @param {ID|null} item\n */\n constructor (type, tname, item) {\n /**\n * @type {ID|null}\n */\n this.type = type;\n /**\n * @type {string|null}\n */\n this.tname = tname;\n /**\n * @type {ID | null}\n */\n this.item = item;\n }\n}\n\n/**\n * @param {any} json\n * @return {RelativePosition}\n *\n * @function\n */\nconst createRelativePositionFromJSON = json => new RelativePosition(json.type == null ? null : createID(json.type.client, json.type.clock), json.tname || null, json.item == null ? null : createID(json.item.client, json.item.clock));\n\nclass AbsolutePosition {\n /**\n * @param {AbstractType} type\n * @param {number} index\n */\n constructor (type, index) {\n /**\n * @type {AbstractType}\n */\n this.type = type;\n /**\n * @type {number}\n */\n this.index = index;\n }\n}\n\n/**\n * @param {AbstractType} type\n * @param {number} index\n *\n * @function\n */\nconst createAbsolutePosition = (type, index) => new AbsolutePosition(type, index);\n\n/**\n * @param {AbstractType} type\n * @param {ID|null} item\n *\n * @function\n */\nconst createRelativePosition = (type, item) => {\n let typeid = null;\n let tname = null;\n if (type._item === null) {\n tname = findRootTypeKey(type);\n } else {\n typeid = createID(type._item.id.client, type._item.id.clock);\n }\n return new RelativePosition(typeid, tname, item)\n};\n\n/**\n * Create a relativePosition based on a absolute position.\n *\n * @param {AbstractType} type The base type (e.g. YText or YArray).\n * @param {number} index The absolute position.\n * @return {RelativePosition}\n *\n * @function\n */\nconst createRelativePositionFromTypeIndex = (type, index) => {\n let t = type._start;\n while (t !== null) {\n if (!t.deleted && t.countable) {\n if (t.length > index) {\n // case 1: found position somewhere in the linked list\n return createRelativePosition(type, createID(t.id.client, t.id.clock + index))\n }\n index -= t.length;\n }\n t = t.right;\n }\n return createRelativePosition(type, null)\n};\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {RelativePosition} rpos\n *\n * @function\n */\nconst writeRelativePosition = (encoder, rpos) => {\n const { type, tname, item } = rpos;\n if (item !== null) {\n writeVarUint(encoder, 0);\n writeID(encoder, item);\n } else if (tname !== null) {\n // case 2: found position at the end of the list and type is stored in y.share\n writeUint8(encoder, 1);\n writeVarString(encoder, tname);\n } else if (type !== null) {\n // case 3: found position at the end of the list and type is attached to an item\n writeUint8(encoder, 2);\n writeID(encoder, type);\n } else {\n throw unexpectedCase()\n }\n return encoder\n};\n\n/**\n * @param {decoding.Decoder} decoder\n * @return {RelativePosition|null}\n *\n * @function\n */\nconst readRelativePosition = decoder => {\n let type = null;\n let tname = null;\n let itemID = null;\n switch (readVarUint(decoder)) {\n case 0:\n // case 1: found position somewhere in the linked list\n itemID = readID(decoder);\n break\n case 1:\n // case 2: found position at the end of the list and type is stored in y.share\n tname = readVarString(decoder);\n break\n case 2: {\n // case 3: found position at the end of the list and type is attached to an item\n type = readID(decoder);\n }\n }\n return new RelativePosition(type, tname, itemID)\n};\n\n/**\n * @param {RelativePosition} rpos\n * @param {Doc} doc\n * @return {AbsolutePosition|null}\n *\n * @function\n */\nconst createAbsolutePositionFromRelativePosition = (rpos, doc) => {\n const store = doc.store;\n const rightID = rpos.item;\n const typeID = rpos.type;\n const tname = rpos.tname;\n let type = null;\n let index = 0;\n if (rightID !== null) {\n if (getState(store, rightID.client) <= rightID.clock) {\n return null\n }\n const res = followRedone(store, rightID);\n const right = res.item;\n if (!(right instanceof Item)) {\n return null\n }\n type = /** @type {AbstractType} */ (right.parent);\n if (type._item === null || !type._item.deleted) {\n index = right.deleted || !right.countable ? 0 : res.diff;\n let n = right.left;\n while (n !== null) {\n if (!n.deleted && n.countable) {\n index += n.length;\n }\n n = n.left;\n }\n }\n } else {\n if (tname !== null) {\n type = doc.get(tname);\n } else if (typeID !== null) {\n if (getState(store, typeID.client) <= typeID.clock) {\n // type does not exist yet\n return null\n }\n const { item } = followRedone(store, typeID);\n if (item instanceof Item && item.content instanceof ContentType) {\n type = item.content.type;\n } else {\n // struct is garbage collected\n return null\n }\n } else {\n throw unexpectedCase()\n }\n index = type._length;\n }\n return createAbsolutePosition(type, index)\n};\n\n/**\n * @param {RelativePosition|null} a\n * @param {RelativePosition|null} b\n *\n * @function\n */\nconst compareRelativePositions = (a, b) => a === b || (\n a !== null && b !== null && a.tname === b.tname && compareIDs(a.item, b.item) && compareIDs(a.type, b.type)\n);\n\nclass Snapshot {\n /**\n * @param {DeleteSet} ds\n * @param {Map} sv state map\n */\n constructor (ds, sv) {\n /**\n * @type {DeleteSet}\n */\n this.ds = ds;\n /**\n * State Map\n * @type {Map}\n */\n this.sv = sv;\n }\n}\n\n/**\n * @param {Snapshot} snap1\n * @param {Snapshot} snap2\n * @return {boolean}\n */\nconst equalSnapshots = (snap1, snap2) => {\n const ds1 = snap1.ds.clients;\n const ds2 = snap2.ds.clients;\n const sv1 = snap1.sv;\n const sv2 = snap2.sv;\n if (sv1.size !== sv2.size || ds1.size !== ds2.size) {\n return false\n }\n for (const [key, value] of sv1.entries()) {\n if (sv2.get(key) !== value) {\n return false\n }\n }\n for (const [client, dsitems1] of ds1.entries()) {\n const dsitems2 = ds2.get(client) || [];\n if (dsitems1.length !== dsitems2.length) {\n return false\n }\n for (let i = 0; i < dsitems1.length; i++) {\n const dsitem1 = dsitems1[i];\n const dsitem2 = dsitems2[i];\n if (dsitem1.clock !== dsitem2.clock || dsitem1.len !== dsitem2.len) {\n return false\n }\n }\n }\n return true\n};\n\n/**\n * @param {Snapshot} snapshot\n * @param {AbstractDSEncoder} [encoder]\n * @return {Uint8Array}\n */\nconst encodeSnapshotV2 = (snapshot, encoder = new DSEncoderV2()) => {\n writeDeleteSet(encoder, snapshot.ds);\n writeStateVector(encoder, snapshot.sv);\n return encoder.toUint8Array()\n};\n\n/**\n * @param {Snapshot} snapshot\n * @return {Uint8Array}\n */\nconst encodeSnapshot = snapshot => encodeSnapshotV2(snapshot, new DefaultDSEncoder());\n\n/**\n * @param {Uint8Array} buf\n * @param {AbstractDSDecoder} [decoder]\n * @return {Snapshot}\n */\nconst decodeSnapshotV2 = (buf, decoder = new DSDecoderV2(createDecoder(buf))) => {\n return new Snapshot(readDeleteSet(decoder), readStateVector(decoder))\n};\n\n/**\n * @param {Uint8Array} buf\n * @return {Snapshot}\n */\nconst decodeSnapshot = buf => decodeSnapshotV2(buf, new DSDecoderV1(createDecoder(buf)));\n\n/**\n * @param {DeleteSet} ds\n * @param {Map} sm\n * @return {Snapshot}\n */\nconst createSnapshot = (ds, sm) => new Snapshot(ds, sm);\n\nconst emptySnapshot = createSnapshot(createDeleteSet(), new Map());\n\n/**\n * @param {Doc} doc\n * @return {Snapshot}\n */\nconst snapshot = doc => createSnapshot(createDeleteSetFromStructStore(doc.store), getStateVector(doc.store));\n\n/**\n * @param {Item} item\n * @param {Snapshot|undefined} snapshot\n *\n * @protected\n * @function\n */\nconst isVisible = (item, snapshot) => snapshot === undefined ? !item.deleted : (\n snapshot.sv.has(item.id.client) && (snapshot.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot.ds, item.id)\n);\n\n/**\n * @param {Transaction} transaction\n * @param {Snapshot} snapshot\n */\nconst splitSnapshotAffectedStructs = (transaction, snapshot) => {\n const meta = setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, create);\n const store = transaction.doc.store;\n // check if we already split for this snapshot\n if (!meta.has(snapshot)) {\n snapshot.sv.forEach((clock, client) => {\n if (clock < getState(store, client)) {\n getItemCleanStart(transaction, createID(client, clock));\n }\n });\n iterateDeletedStructs(transaction, snapshot.ds, item => {});\n meta.add(snapshot);\n }\n};\n\n/**\n * @param {Doc} originDoc\n * @param {Snapshot} snapshot\n * @param {Doc} [newDoc] Optionally, you may define the Yjs document that receives the data from originDoc\n * @return {Doc}\n */\nconst createDocFromSnapshot = (originDoc, snapshot, newDoc = new Doc()) => {\n if (originDoc.gc) {\n // we should not try to restore a GC-ed document, because some of the restored items might have their content deleted\n throw new Error('originDoc must not be garbage collected')\n }\n const { sv, ds } = snapshot;\n\n const encoder = new UpdateEncoderV2();\n originDoc.transact(transaction => {\n let size = 0;\n sv.forEach(clock => {\n if (clock > 0) {\n size++;\n }\n });\n writeVarUint(encoder.restEncoder, size);\n // splitting the structs before writing them to the encoder\n for (const [client, clock] of sv) {\n if (clock === 0) {\n continue\n }\n if (clock < getState(originDoc.store, client)) {\n getItemCleanStart(transaction, createID(client, clock));\n }\n const structs = originDoc.store.clients.get(client) || [];\n const lastStructIndex = findIndexSS(structs, clock - 1);\n // write # encoded structs\n writeVarUint(encoder.restEncoder, lastStructIndex + 1);\n encoder.writeClient(client);\n // first clock written is 0\n writeVarUint(encoder.restEncoder, 0);\n for (let i = 0; i <= lastStructIndex; i++) {\n structs[i].write(encoder, 0);\n }\n }\n writeDeleteSet(encoder, ds);\n });\n\n applyUpdateV2(newDoc, encoder.toUint8Array(), 'snapshot');\n return newDoc\n};\n\nclass StructStore {\n constructor () {\n /**\n * @type {Map>}\n */\n this.clients = new Map();\n /**\n * Store incompleted struct reads here\n * `i` denotes to the next read operation\n * We could shift the array of refs instead, but shift is incredible\n * slow in Chrome for arrays with more than 100k elements\n * @see tryResumePendingStructRefs\n * @type {Map}>}\n */\n this.pendingClientsStructRefs = new Map();\n /**\n * Stack of pending structs waiting for struct dependencies\n * Maximum length of stack is structReaders.size\n * @type {Array}\n */\n this.pendingStack = [];\n /**\n * @type {Array}\n */\n this.pendingDeleteReaders = [];\n }\n}\n\n/**\n * Return the states as a Map.\n * Note that clock refers to the next expected clock id.\n *\n * @param {StructStore} store\n * @return {Map}\n *\n * @public\n * @function\n */\nconst getStateVector = store => {\n const sm = new Map();\n store.clients.forEach((structs, client) => {\n const struct = structs[structs.length - 1];\n sm.set(client, struct.id.clock + struct.length);\n });\n return sm\n};\n\n/**\n * @param {StructStore} store\n * @param {number} client\n * @return {number}\n *\n * @public\n * @function\n */\nconst getState = (store, client) => {\n const structs = store.clients.get(client);\n if (structs === undefined) {\n return 0\n }\n const lastStruct = structs[structs.length - 1];\n return lastStruct.id.clock + lastStruct.length\n};\n\n/**\n * @param {StructStore} store\n * @param {GC|Item} struct\n *\n * @private\n * @function\n */\nconst addStruct = (store, struct) => {\n let structs = store.clients.get(struct.id.client);\n if (structs === undefined) {\n structs = [];\n store.clients.set(struct.id.client, structs);\n } else {\n const lastStruct = structs[structs.length - 1];\n if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) {\n throw unexpectedCase()\n }\n }\n structs.push(struct);\n};\n\n/**\n * Perform a binary search on a sorted array\n * @param {Array} structs\n * @param {number} clock\n * @return {number}\n *\n * @private\n * @function\n */\nconst findIndexSS = (structs, clock) => {\n let left = 0;\n let right = structs.length - 1;\n let mid = structs[right];\n let midclock = mid.id.clock;\n if (midclock === clock) {\n return right\n }\n // @todo does it even make sense to pivot the search?\n // If a good split misses, it might actually increase the time to find the correct item.\n // Currently, the only advantage is that search with pivoting might find the item on the first try.\n let midindex = floor((clock / (midclock + mid.length - 1)) * right); // pivoting the search\n while (left <= right) {\n mid = structs[midindex];\n midclock = mid.id.clock;\n if (midclock <= clock) {\n if (clock < midclock + mid.length) {\n return midindex\n }\n left = midindex + 1;\n } else {\n right = midindex - 1;\n }\n midindex = floor((left + right) / 2);\n }\n // Always check state before looking for a struct in StructStore\n // Therefore the case of not finding a struct is unexpected\n throw unexpectedCase()\n};\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {StructStore} store\n * @param {ID} id\n * @return {GC|Item}\n *\n * @private\n * @function\n */\nconst find = (store, id) => {\n /**\n * @type {Array}\n */\n // @ts-ignore\n const structs = store.clients.get(id.client);\n return structs[findIndexSS(structs, id.clock)]\n};\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n * @private\n * @function\n */\nconst getItem = /** @type {function(StructStore,ID):Item} */ (find);\n\n/**\n * @param {Transaction} transaction\n * @param {Array} structs\n * @param {number} clock\n */\nconst findIndexCleanStart = (transaction, structs, clock) => {\n const index = findIndexSS(structs, clock);\n const struct = structs[index];\n if (struct.id.clock < clock && struct instanceof Item) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock));\n return index + 1\n }\n return index\n};\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {Transaction} transaction\n * @param {ID} id\n * @return {Item}\n *\n * @private\n * @function\n */\nconst getItemCleanStart = (transaction, id) => {\n const structs = /** @type {Array} */ (transaction.doc.store.clients.get(id.client));\n return structs[findIndexCleanStart(transaction, structs, id.clock)]\n};\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @param {ID} id\n * @return {Item}\n *\n * @private\n * @function\n */\nconst getItemCleanEnd = (transaction, store, id) => {\n /**\n * @type {Array}\n */\n // @ts-ignore\n const structs = store.clients.get(id.client);\n const index = findIndexSS(structs, id.clock);\n const struct = structs[index];\n if (id.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, id.clock - struct.id.clock + 1));\n }\n return struct\n};\n\n/**\n * Replace `item` with `newitem` in store\n * @param {StructStore} store\n * @param {GC|Item} struct\n * @param {GC|Item} newStruct\n *\n * @private\n * @function\n */\nconst replaceStruct = (store, struct, newStruct) => {\n const structs = /** @type {Array} */ (store.clients.get(struct.id.client));\n structs[findIndexSS(structs, struct.id.clock)] = newStruct;\n};\n\n/**\n * Iterate over a range of structs\n *\n * @param {Transaction} transaction\n * @param {Array} structs\n * @param {number} clockStart Inclusive start\n * @param {number} len\n * @param {function(GC|Item):void} f\n *\n * @function\n */\nconst iterateStructs = (transaction, structs, clockStart, len, f) => {\n if (len === 0) {\n return\n }\n const clockEnd = clockStart + len;\n let index = findIndexCleanStart(transaction, structs, clockStart);\n let struct;\n do {\n struct = structs[index++];\n if (clockEnd < struct.id.clock + struct.length) {\n findIndexCleanStart(transaction, structs, clockEnd);\n }\n f(struct);\n } while (index < structs.length && structs[index].id.clock < clockEnd)\n};\n\n/**\n * A transaction is created for every change on the Yjs model. It is possible\n * to bundle changes on the Yjs model in a single transaction to\n * minimize the number on messages sent and the number of observer calls.\n * If possible the user of this library should bundle as many changes as\n * possible. Here is an example to illustrate the advantages of bundling:\n *\n * @example\n * const map = y.define('map', YMap)\n * // Log content when change is triggered\n * map.observe(() => {\n * console.log('change triggered')\n * })\n * // Each change on the map type triggers a log message:\n * map.set('a', 0) // => \"change triggered\"\n * map.set('b', 0) // => \"change triggered\"\n * // When put in a transaction, it will trigger the log after the transaction:\n * y.transact(() => {\n * map.set('a', 1)\n * map.set('b', 1)\n * }) // => \"change triggered\"\n *\n * @public\n */\nclass Transaction {\n /**\n * @param {Doc} doc\n * @param {any} origin\n * @param {boolean} local\n */\n constructor (doc, origin, local) {\n /**\n * The Yjs instance.\n * @type {Doc}\n */\n this.doc = doc;\n /**\n * Describes the set of deleted items by ids\n * @type {DeleteSet}\n */\n this.deleteSet = new DeleteSet();\n /**\n * Holds the state before the transaction started.\n * @type {Map}\n */\n this.beforeState = getStateVector(doc.store);\n /**\n * Holds the state after the transaction.\n * @type {Map}\n */\n this.afterState = new Map();\n /**\n * All types that were directly modified (property added or child\n * inserted/deleted). New types are not included in this Set.\n * Maps from type to parentSubs (`item.parentSub = null` for YArray)\n * @type {Map,Set>}\n */\n this.changed = new Map();\n /**\n * Stores the events for the types that observe also child elements.\n * It is mainly used by `observeDeep`.\n * @type {Map,Array>}\n */\n this.changedParentTypes = new Map();\n /**\n * @type {Array}\n */\n this._mergeStructs = [];\n /**\n * @type {any}\n */\n this.origin = origin;\n /**\n * Stores meta information on the transaction\n * @type {Map}\n */\n this.meta = new Map();\n /**\n * Whether this change originates from this doc.\n * @type {boolean}\n */\n this.local = local;\n /**\n * @type {Set}\n */\n this.subdocsAdded = new Set();\n /**\n * @type {Set}\n */\n this.subdocsRemoved = new Set();\n /**\n * @type {Set}\n */\n this.subdocsLoaded = new Set();\n }\n}\n\n/**\n * @param {AbstractUpdateEncoder} encoder\n * @param {Transaction} transaction\n * @return {boolean} Whether data was written.\n */\nconst writeUpdateMessageFromTransaction = (encoder, transaction) => {\n if (transaction.deleteSet.clients.size === 0 && !any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) {\n return false\n }\n sortAndMergeDeleteSet(transaction.deleteSet);\n writeStructsFromTransaction(encoder, transaction);\n writeDeleteSet(encoder, transaction.deleteSet);\n return true\n};\n\n/**\n * If `type.parent` was added in current transaction, `type` technically\n * did not change, it was just added and we should not fire events for `type`.\n *\n * @param {Transaction} transaction\n * @param {AbstractType} type\n * @param {string|null} parentSub\n */\nconst addChangedTypeToTransaction = (transaction, type, parentSub) => {\n const item = type._item;\n if (item === null || (item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted)) {\n setIfUndefined(transaction.changed, type, create).add(parentSub);\n }\n};\n\n/**\n * @param {Array} structs\n * @param {number} pos\n */\nconst tryToMergeWithLeft = (structs, pos) => {\n const left = structs[pos - 1];\n const right = structs[pos];\n if (left.deleted === right.deleted && left.constructor === right.constructor) {\n if (left.mergeWith(right)) {\n structs.splice(pos, 1);\n if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType} */ (right.parent)._map.get(right.parentSub) === right) {\n /** @type {AbstractType} */ (right.parent)._map.set(right.parentSub, /** @type {Item} */ (left));\n }\n }\n }\n};\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n * @param {function(Item):boolean} gcFilter\n */\nconst tryGcDeleteSet = (ds, store, gcFilter) => {\n for (const [client, deleteItems] of ds.clients.entries()) {\n const structs = /** @type {Array} */ (store.clients.get(client));\n for (let di = deleteItems.length - 1; di >= 0; di--) {\n const deleteItem = deleteItems[di];\n const endDeleteItemClock = deleteItem.clock + deleteItem.len;\n for (\n let si = findIndexSS(structs, deleteItem.clock), struct = structs[si];\n si < structs.length && struct.id.clock < endDeleteItemClock;\n struct = structs[++si]\n ) {\n const struct = structs[si];\n if (deleteItem.clock + deleteItem.len <= struct.id.clock) {\n break\n }\n if (struct instanceof Item && struct.deleted && !struct.keep && gcFilter(struct)) {\n struct.gc(store, false);\n }\n }\n }\n }\n};\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n */\nconst tryMergeDeleteSet = (ds, store) => {\n // try to merge deleted / gc'd items\n // merge from right to left for better efficiecy and so we don't miss any merge targets\n ds.clients.forEach((deleteItems, client) => {\n const structs = /** @type {Array} */ (store.clients.get(client));\n for (let di = deleteItems.length - 1; di >= 0; di--) {\n const deleteItem = deleteItems[di];\n // start with merging the item next to the last deleted item\n const mostRightIndexToCheck = min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1));\n for (\n let si = mostRightIndexToCheck, struct = structs[si];\n si > 0 && struct.id.clock >= deleteItem.clock;\n struct = structs[--si]\n ) {\n tryToMergeWithLeft(structs, si);\n }\n }\n });\n};\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n * @param {function(Item):boolean} gcFilter\n */\nconst tryGc = (ds, store, gcFilter) => {\n tryGcDeleteSet(ds, store, gcFilter);\n tryMergeDeleteSet(ds, store);\n};\n\n/**\n * @param {Array} transactionCleanups\n * @param {number} i\n */\nconst cleanupTransactions = (transactionCleanups, i) => {\n if (i < transactionCleanups.length) {\n const transaction = transactionCleanups[i];\n const doc = transaction.doc;\n const store = doc.store;\n const ds = transaction.deleteSet;\n const mergeStructs = transaction._mergeStructs;\n try {\n sortAndMergeDeleteSet(ds);\n transaction.afterState = getStateVector(transaction.doc.store);\n doc._transaction = null;\n doc.emit('beforeObserverCalls', [transaction, doc]);\n /**\n * An array of event callbacks.\n *\n * Each callback is called even if the other ones throw errors.\n *\n * @type {Array}\n */\n const fs = [];\n // observe events on changed types\n transaction.changed.forEach((subs, itemtype) =>\n fs.push(() => {\n if (itemtype._item === null || !itemtype._item.deleted) {\n itemtype._callObserver(transaction, subs);\n }\n })\n );\n fs.push(() => {\n // deep observe events\n transaction.changedParentTypes.forEach((events, type) =>\n fs.push(() => {\n // We need to think about the possibility that the user transforms the\n // Y.Doc in the event.\n if (type._item === null || !type._item.deleted) {\n events = events\n .filter(event =>\n event.target._item === null || !event.target._item.deleted\n );\n events\n .forEach(event => {\n event.currentTarget = type;\n });\n // sort events by path length so that top-level events are fired first.\n events\n .sort((event1, event2) => event1.path.length - event2.path.length);\n // We don't need to check for events.length\n // because we know it has at least one element\n callEventHandlerListeners(type._dEH, events, transaction);\n }\n })\n );\n fs.push(() => doc.emit('afterTransaction', [transaction, doc]));\n });\n callAll(fs, []);\n } finally {\n // Replace deleted items with ItemDeleted / GC.\n // This is where content is actually remove from the Yjs Doc.\n if (doc.gc) {\n tryGcDeleteSet(ds, store, doc.gcFilter);\n }\n tryMergeDeleteSet(ds, store);\n\n // on all affected store.clients props, try to merge\n transaction.afterState.forEach((clock, client) => {\n const beforeClock = transaction.beforeState.get(client) || 0;\n if (beforeClock !== clock) {\n const structs = /** @type {Array} */ (store.clients.get(client));\n // we iterate from right to left so we can safely remove entries\n const firstChangePos = max(findIndexSS(structs, beforeClock), 1);\n for (let i = structs.length - 1; i >= firstChangePos; i--) {\n tryToMergeWithLeft(structs, i);\n }\n }\n });\n // try to merge mergeStructs\n // @todo: it makes more sense to transform mergeStructs to a DS, sort it, and merge from right to left\n // but at the moment DS does not handle duplicates\n for (let i = 0; i < mergeStructs.length; i++) {\n const { client, clock } = mergeStructs[i].id;\n const structs = /** @type {Array} */ (store.clients.get(client));\n const replacedStructPos = findIndexSS(structs, clock);\n if (replacedStructPos + 1 < structs.length) {\n tryToMergeWithLeft(structs, replacedStructPos + 1);\n }\n if (replacedStructPos > 0) {\n tryToMergeWithLeft(structs, replacedStructPos);\n }\n }\n if (!transaction.local && transaction.afterState.get(doc.clientID) !== transaction.beforeState.get(doc.clientID)) {\n doc.clientID = generateNewClientId();\n print(ORANGE, BOLD, '[yjs] ', UNBOLD, RED, 'Changed the client-id because another client seems to be using it.');\n }\n // @todo Merge all the transactions into one and provide send the data as a single update message\n doc.emit('afterTransactionCleanup', [transaction, doc]);\n if (doc._observers.has('update')) {\n const encoder = new DefaultUpdateEncoder();\n const hasContent = writeUpdateMessageFromTransaction(encoder, transaction);\n if (hasContent) {\n doc.emit('update', [encoder.toUint8Array(), transaction.origin, doc]);\n }\n }\n if (doc._observers.has('updateV2')) {\n const encoder = new UpdateEncoderV2();\n const hasContent = writeUpdateMessageFromTransaction(encoder, transaction);\n if (hasContent) {\n doc.emit('updateV2', [encoder.toUint8Array(), transaction.origin, doc]);\n }\n }\n transaction.subdocsAdded.forEach(subdoc => doc.subdocs.add(subdoc));\n transaction.subdocsRemoved.forEach(subdoc => doc.subdocs.delete(subdoc));\n\n doc.emit('subdocs', [{ loaded: transaction.subdocsLoaded, added: transaction.subdocsAdded, removed: transaction.subdocsRemoved }]);\n transaction.subdocsRemoved.forEach(subdoc => subdoc.destroy());\n\n if (transactionCleanups.length <= i + 1) {\n doc._transactionCleanups = [];\n doc.emit('afterAllTransactions', [doc, transactionCleanups]);\n } else {\n cleanupTransactions(transactionCleanups, i + 1);\n }\n }\n }\n};\n\n/**\n * Implements the functionality of `y.transact(()=>{..})`\n *\n * @param {Doc} doc\n * @param {function(Transaction):void} f\n * @param {any} [origin=true]\n *\n * @function\n */\nconst transact = (doc, f, origin = null, local = true) => {\n const transactionCleanups = doc._transactionCleanups;\n let initialCall = false;\n if (doc._transaction === null) {\n initialCall = true;\n doc._transaction = new Transaction(doc, origin, local);\n transactionCleanups.push(doc._transaction);\n if (transactionCleanups.length === 1) {\n doc.emit('beforeAllTransactions', [doc]);\n }\n doc.emit('beforeTransaction', [doc._transaction, doc]);\n }\n try {\n f(doc._transaction);\n } finally {\n if (initialCall && transactionCleanups[0] === doc._transaction) {\n // The first transaction ended, now process observer calls.\n // Observer call may create new transactions for which we need to call the observers and do cleanup.\n // We don't want to nest these calls, so we execute these calls one after\n // another.\n // Also we need to ensure that all cleanups are called, even if the\n // observes throw errors.\n // This file is full of hacky try {} finally {} blocks to ensure that an\n // event can throw errors and also that the cleanup is called.\n cleanupTransactions(transactionCleanups, 0);\n }\n }\n};\n\nclass StackItem {\n /**\n * @param {DeleteSet} ds\n * @param {Map} beforeState\n * @param {Map} afterState\n */\n constructor (ds, beforeState, afterState) {\n this.ds = ds;\n this.beforeState = beforeState;\n this.afterState = afterState;\n /**\n * Use this to save and restore metadata like selection range\n */\n this.meta = new Map();\n }\n}\n\n/**\n * @param {UndoManager} undoManager\n * @param {Array} stack\n * @param {string} eventType\n * @return {StackItem?}\n */\nconst popStackItem = (undoManager, stack, eventType) => {\n /**\n * Whether a change happened\n * @type {StackItem?}\n */\n let result = null;\n const doc = undoManager.doc;\n const scope = undoManager.scope;\n transact(doc, transaction => {\n while (stack.length > 0 && result === null) {\n const store = doc.store;\n const stackItem = /** @type {StackItem} */ (stack.pop());\n /**\n * @type {Set}\n */\n const itemsToRedo = new Set();\n /**\n * @type {Array}\n */\n const itemsToDelete = [];\n let performedChange = false;\n stackItem.afterState.forEach((endClock, client) => {\n const startClock = stackItem.beforeState.get(client) || 0;\n const len = endClock - startClock;\n // @todo iterateStructs should not need the structs parameter\n const structs = /** @type {Array} */ (store.clients.get(client));\n if (startClock !== endClock) {\n // make sure structs don't overlap with the range of created operations [stackItem.start, stackItem.start + stackItem.end)\n // this must be executed before deleted structs are iterated.\n getItemCleanStart(transaction, createID(client, startClock));\n if (endClock < getState(doc.store, client)) {\n getItemCleanStart(transaction, createID(client, endClock));\n }\n iterateStructs(transaction, structs, startClock, len, struct => {\n if (struct instanceof Item) {\n if (struct.redone !== null) {\n let { item, diff } = followRedone(store, struct.id);\n if (diff > 0) {\n item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff));\n }\n if (item.length > len) {\n getItemCleanStart(transaction, createID(item.id.client, endClock));\n }\n struct = item;\n }\n if (!struct.deleted && scope.some(type => isParentOf(type, /** @type {Item} */ (struct)))) {\n itemsToDelete.push(struct);\n }\n }\n });\n }\n });\n iterateDeletedStructs(transaction, stackItem.ds, struct => {\n const id = struct.id;\n const clock = id.clock;\n const client = id.client;\n const startClock = stackItem.beforeState.get(client) || 0;\n const endClock = stackItem.afterState.get(client) || 0;\n if (\n struct instanceof Item &&\n scope.some(type => isParentOf(type, struct)) &&\n // Never redo structs in [stackItem.start, stackItem.start + stackItem.end) because they were created and deleted in the same capture interval.\n !(clock >= startClock && clock < endClock)\n ) {\n itemsToRedo.add(struct);\n }\n });\n itemsToRedo.forEach(struct => {\n performedChange = redoItem(transaction, struct, itemsToRedo) !== null || performedChange;\n });\n // We want to delete in reverse order so that children are deleted before\n // parents, so we have more information available when items are filtered.\n for (let i = itemsToDelete.length - 1; i >= 0; i--) {\n const item = itemsToDelete[i];\n if (undoManager.deleteFilter(item)) {\n item.delete(transaction);\n performedChange = true;\n }\n }\n result = stackItem;\n if (result != null) {\n undoManager.emit('stack-item-popped', [{ stackItem: result, type: eventType }, undoManager]);\n }\n }\n transaction.changed.forEach((subProps, type) => {\n // destroy search marker if necessary\n if (subProps.has(null) && type._searchMarker) {\n type._searchMarker.length = 0;\n }\n });\n }, undoManager);\n return result\n};\n\n/**\n * @typedef {Object} UndoManagerOptions\n * @property {number} [UndoManagerOptions.captureTimeout=500]\n * @property {function(Item):boolean} [UndoManagerOptions.deleteFilter=()=>true] Sometimes\n * it is necessary to filter whan an Undo/Redo operation can delete. If this\n * filter returns false, the type/item won't be deleted even it is in the\n * undo/redo scope.\n * @property {Set} [UndoManagerOptions.trackedOrigins=new Set([null])]\n */\n\n/**\n * Fires 'stack-item-added' event when a stack item was added to either the undo- or\n * the redo-stack. You may store additional stack information via the\n * metadata property on `event.stackItem.meta` (it is a `Map` of metadata properties).\n * Fires 'stack-item-popped' event when a stack item was popped from either the\n * undo- or the redo-stack. You may restore the saved stack information from `event.stackItem.meta`.\n *\n * @extends {Observable<'stack-item-added'|'stack-item-popped'>}\n */\nclass UndoManager extends Observable {\n /**\n * @param {AbstractType|Array>} typeScope Accepts either a single type, or an array of types\n * @param {UndoManagerOptions} options\n */\n constructor (typeScope, { captureTimeout = 500, deleteFilter = () => true, trackedOrigins = new Set([null]) } = {}) {\n super();\n this.scope = typeScope instanceof Array ? typeScope : [typeScope];\n this.deleteFilter = deleteFilter;\n trackedOrigins.add(this);\n this.trackedOrigins = trackedOrigins;\n /**\n * @type {Array}\n */\n this.undoStack = [];\n /**\n * @type {Array}\n */\n this.redoStack = [];\n /**\n * Whether the client is currently undoing (calling UndoManager.undo)\n *\n * @type {boolean}\n */\n this.undoing = false;\n this.redoing = false;\n this.doc = /** @type {Doc} */ (this.scope[0].doc);\n this.lastChange = 0;\n this.doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => {\n // Only track certain transactions\n if (!this.scope.some(type => transaction.changedParentTypes.has(type)) || (!this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor)))) {\n return\n }\n const undoing = this.undoing;\n const redoing = this.redoing;\n const stack = undoing ? this.redoStack : this.undoStack;\n if (undoing) {\n this.stopCapturing(); // next undo should not be appended to last stack item\n } else if (!redoing) {\n // neither undoing nor redoing: delete redoStack\n this.redoStack = [];\n }\n const beforeState = transaction.beforeState;\n const afterState = transaction.afterState;\n const now = getUnixTime();\n if (now - this.lastChange < captureTimeout && stack.length > 0 && !undoing && !redoing) {\n // append change to last stack op\n const lastOp = stack[stack.length - 1];\n lastOp.ds = mergeDeleteSets([lastOp.ds, transaction.deleteSet]);\n lastOp.afterState = afterState;\n } else {\n // create a new stack op\n stack.push(new StackItem(transaction.deleteSet, beforeState, afterState));\n }\n if (!undoing && !redoing) {\n this.lastChange = now;\n }\n // make sure that deleted structs are not gc'd\n iterateDeletedStructs(transaction, transaction.deleteSet, /** @param {Item|GC} item */ item => {\n if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) {\n keepItem(item, true);\n }\n });\n this.emit('stack-item-added', [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? 'redo' : 'undo' }, this]);\n });\n }\n\n clear () {\n this.doc.transact(transaction => {\n /**\n * @param {StackItem} stackItem\n */\n const clearItem = stackItem => {\n iterateDeletedStructs(transaction, stackItem.ds, item => {\n if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) {\n keepItem(item, false);\n }\n });\n };\n this.undoStack.forEach(clearItem);\n this.redoStack.forEach(clearItem);\n });\n this.undoStack = [];\n this.redoStack = [];\n }\n\n /**\n * UndoManager merges Undo-StackItem if they are created within time-gap\n * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next\n * StackItem won't be merged.\n *\n *\n * @example\n * // without stopCapturing\n * ytext.insert(0, 'a')\n * ytext.insert(1, 'b')\n * um.undo()\n * ytext.toString() // => '' (note that 'ab' was removed)\n * // with stopCapturing\n * ytext.insert(0, 'a')\n * um.stopCapturing()\n * ytext.insert(0, 'b')\n * um.undo()\n * ytext.toString() // => 'a' (note that only 'b' was removed)\n *\n */\n stopCapturing () {\n this.lastChange = 0;\n }\n\n /**\n * Undo last changes on type.\n *\n * @return {StackItem?} Returns StackItem if a change was applied\n */\n undo () {\n this.undoing = true;\n let res;\n try {\n res = popStackItem(this, this.undoStack, 'undo');\n } finally {\n this.undoing = false;\n }\n return res\n }\n\n /**\n * Redo last undo operation.\n *\n * @return {StackItem?} Returns StackItem if a change was applied\n */\n redo () {\n this.redoing = true;\n let res;\n try {\n res = popStackItem(this, this.redoStack, 'redo');\n } finally {\n this.redoing = false;\n }\n return res\n }\n}\n\n/**\n * YEvent describes the changes on a YType.\n */\nclass YEvent {\n /**\n * @param {AbstractType} target The changed type.\n * @param {Transaction} transaction\n */\n constructor (target, transaction) {\n /**\n * The type on which this event was created on.\n * @type {AbstractType}\n */\n this.target = target;\n /**\n * The current target on which the observe callback is called.\n * @type {AbstractType}\n */\n this.currentTarget = target;\n /**\n * The transaction that triggered this event.\n * @type {Transaction}\n */\n this.transaction = transaction;\n /**\n * @type {Object|null}\n */\n this._changes = null;\n }\n\n /**\n * Computes the path from `y` to the changed type.\n *\n * The following property holds:\n * @example\n * let type = y\n * event.path.forEach(dir => {\n * type = type.get(dir)\n * })\n * type === event.target // => true\n */\n get path () {\n // @ts-ignore _item is defined because target is integrated\n return getPathTo(this.currentTarget, this.target)\n }\n\n /**\n * Check if a struct is deleted by this event.\n *\n * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.\n *\n * @param {AbstractStruct} struct\n * @return {boolean}\n */\n deletes (struct) {\n return isDeleted(this.transaction.deleteSet, struct.id)\n }\n\n /**\n * Check if a struct is added by this event.\n *\n * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.\n *\n * @param {AbstractStruct} struct\n * @return {boolean}\n */\n adds (struct) {\n return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0)\n }\n\n /**\n * @return {{added:Set,deleted:Set,keys:Map,delta:Array<{insert:Array}|{delete:number}|{retain:number}>}}\n */\n get changes () {\n let changes = this._changes;\n if (changes === null) {\n const target = this.target;\n const added = create();\n const deleted = create();\n /**\n * @type {Array<{insert:Array}|{delete:number}|{retain:number}>}\n */\n const delta = [];\n /**\n * @type {Map}\n */\n const keys = new Map();\n changes = {\n added, deleted, delta, keys\n };\n const changed = /** @type Set */ (this.transaction.changed.get(target));\n if (changed.has(null)) {\n /**\n * @type {any}\n */\n let lastOp = null;\n const packOp = () => {\n if (lastOp) {\n delta.push(lastOp);\n }\n };\n for (let item = target._start; item !== null; item = item.right) {\n if (item.deleted) {\n if (this.deletes(item) && !this.adds(item)) {\n if (lastOp === null || lastOp.delete === undefined) {\n packOp();\n lastOp = { delete: 0 };\n }\n lastOp.delete += item.length;\n deleted.add(item);\n } // else nop\n } else {\n if (this.adds(item)) {\n if (lastOp === null || lastOp.insert === undefined) {\n packOp();\n lastOp = { insert: [] };\n }\n lastOp.insert = lastOp.insert.concat(item.content.getContent());\n added.add(item);\n } else {\n if (lastOp === null || lastOp.retain === undefined) {\n packOp();\n lastOp = { retain: 0 };\n }\n lastOp.retain += item.length;\n }\n }\n }\n if (lastOp !== null && lastOp.retain === undefined) {\n packOp();\n }\n }\n changed.forEach(key => {\n if (key !== null) {\n const item = /** @type {Item} */ (target._map.get(key));\n /**\n * @type {'delete' | 'add' | 'update'}\n */\n let action;\n let oldValue;\n if (this.adds(item)) {\n let prev = item.left;\n while (prev !== null && this.adds(prev)) {\n prev = prev.left;\n }\n if (this.deletes(item)) {\n if (prev !== null && this.deletes(prev)) {\n action = 'delete';\n oldValue = last(prev.content.getContent());\n } else {\n return\n }\n } else {\n if (prev !== null && this.deletes(prev)) {\n action = 'update';\n oldValue = last(prev.content.getContent());\n } else {\n action = 'add';\n oldValue = undefined;\n }\n }\n } else {\n if (this.deletes(item)) {\n action = 'delete';\n oldValue = last(/** @type {Item} */ item.content.getContent());\n } else {\n return // nop\n }\n }\n keys.set(key, { action, oldValue });\n }\n });\n this._changes = changes;\n }\n return /** @type {any} */ (changes)\n }\n}\n\n/**\n * Compute the path from this type to the specified target.\n *\n * @example\n * // `child` should be accessible via `type.get(path[0]).get(path[1])..`\n * const path = type.getPathTo(child)\n * // assuming `type instanceof YArray`\n * console.log(path) // might look like => [2, 'key1']\n * child === type.get(path[0]).get(path[1])\n *\n * @param {AbstractType} parent\n * @param {AbstractType} child target\n * @return {Array} Path to the target\n *\n * @private\n * @function\n */\nconst getPathTo = (parent, child) => {\n const path = [];\n while (child._item !== null && child !== parent) {\n if (child._item.parentSub !== null) {\n // parent is map-ish\n path.unshift(child._item.parentSub);\n } else {\n // parent is array-ish\n let i = 0;\n let c = /** @type {AbstractType} */ (child._item.parent)._start;\n while (c !== child._item && c !== null) {\n if (!c.deleted) {\n i++;\n }\n c = c.right;\n }\n path.unshift(i);\n }\n child = /** @type {AbstractType} */ (child._item.parent);\n }\n return path\n};\n\nconst maxSearchMarker = 80;\n\n/**\n * A unique timestamp that identifies each marker.\n *\n * Time is relative,.. this is more like an ever-increasing clock.\n *\n * @type {number}\n */\nlet globalSearchMarkerTimestamp = 0;\n\nclass ArraySearchMarker {\n /**\n * @param {Item} p\n * @param {number} index\n */\n constructor (p, index) {\n p.marker = true;\n this.p = p;\n this.index = index;\n this.timestamp = globalSearchMarkerTimestamp++;\n }\n}\n\n/**\n * @param {ArraySearchMarker} marker\n */\nconst refreshMarkerTimestamp = marker => { marker.timestamp = globalSearchMarkerTimestamp++; };\n\n/**\n * This is rather complex so this function is the only thing that should overwrite a marker\n *\n * @param {ArraySearchMarker} marker\n * @param {Item} p\n * @param {number} index\n */\nconst overwriteMarker = (marker, p, index) => {\n marker.p.marker = false;\n marker.p = p;\n p.marker = true;\n marker.index = index;\n marker.timestamp = globalSearchMarkerTimestamp++;\n};\n\n/**\n * @param {Array} searchMarker\n * @param {Item} p\n * @param {number} index\n */\nconst markPosition = (searchMarker, p, index) => {\n if (searchMarker.length >= maxSearchMarker) {\n // override oldest marker (we don't want to create more objects)\n const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b);\n overwriteMarker(marker, p, index);\n return marker\n } else {\n // create new marker\n const pm = new ArraySearchMarker(p, index);\n searchMarker.push(pm);\n return pm\n }\n};\n\n/**\n * Search marker help us to find positions in the associative array faster.\n *\n * They speed up the process of finding a position without much bookkeeping.\n *\n * A maximum of `maxSearchMarker` objects are created.\n *\n * This function always returns a refreshed marker (updated timestamp)\n *\n * @param {AbstractType} yarray\n * @param {number} index\n */\nconst findMarker = (yarray, index) => {\n if (yarray._start === null || index === 0 || yarray._searchMarker === null) {\n return null\n }\n const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => abs(index - a.index) < abs(index - b.index) ? a : b);\n let p = yarray._start;\n let pindex = 0;\n if (marker !== null) {\n p = marker.p;\n pindex = marker.index;\n refreshMarkerTimestamp(marker); // we used it, we might need to use it again\n }\n // iterate to right if possible\n while (p.right !== null && pindex < index) {\n if (!p.deleted && p.countable) {\n if (index < pindex + p.length) {\n break\n }\n pindex += p.length;\n }\n p = p.right;\n }\n // iterate to left if necessary (might be that pindex > index)\n while (p.left !== null && pindex > index) {\n p = p.left;\n if (!p.deleted && p.countable) {\n pindex -= p.length;\n }\n }\n // we want to make sure that p can't be merged with left, because that would screw up everything\n // in that cas just return what we have (it is most likely the best marker anyway)\n // iterate to left until p can't be merged with left\n while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) {\n p = p.left;\n if (!p.deleted && p.countable) {\n pindex -= p.length;\n }\n }\n\n // @todo remove!\n // assure position\n // {\n // let start = yarray._start\n // let pos = 0\n // while (start !== p) {\n // if (!start.deleted && start.countable) {\n // pos += start.length\n // }\n // start = /** @type {Item} */ (start.right)\n // }\n // if (pos !== pindex) {\n // debugger\n // throw new Error('Gotcha position fail!')\n // }\n // }\n // if (marker) {\n // if (window.lengthes == null) {\n // window.lengthes = []\n // window.getLengthes = () => window.lengthes.sort((a, b) => a - b)\n // }\n // window.lengthes.push(marker.index - pindex)\n // console.log('distance', marker.index - pindex, 'len', p && p.parent.length)\n // }\n if (marker !== null && abs(marker.index - pindex) < /** @type {YText|YArray} */ (p.parent).length / maxSearchMarker) {\n // adjust existing marker\n overwriteMarker(marker, p, pindex);\n return marker\n } else {\n // create new marker\n return markPosition(yarray._searchMarker, p, pindex)\n }\n};\n\n/**\n * Update markers when a change happened.\n *\n * This should be called before doing a deletion!\n *\n * @param {Array} searchMarker\n * @param {number} index\n * @param {number} len If insertion, len is positive. If deletion, len is negative.\n */\nconst updateMarkerChanges = (searchMarker, index, len) => {\n for (let i = searchMarker.length - 1; i >= 0; i--) {\n const m = searchMarker[i];\n if (len > 0) {\n /**\n * @type {Item|null}\n */\n let p = m.p;\n p.marker = false;\n // Ideally we just want to do a simple position comparison, but this will only work if\n // search markers don't point to deleted items for formats.\n // Iterate marker to prev undeleted countable position so we know what to do when updating a position\n while (p && (p.deleted || !p.countable)) {\n p = p.left;\n if (p && !p.deleted && p.countable) {\n // adjust position. the loop should break now\n m.index -= p.length;\n }\n }\n if (p === null || p.marker === true) {\n // remove search marker if updated position is null or if position is already marked\n searchMarker.splice(i, 1);\n continue\n }\n m.p = p;\n p.marker = true;\n }\n if (index < m.index || (len > 0 && index === m.index)) { // a simple index <= m.index check would actually suffice\n m.index = max(index, m.index + len);\n }\n }\n};\n\n/**\n * Accumulate all (list) children of a type and return them as an Array.\n *\n * @param {AbstractType} t\n * @return {Array}\n */\nconst getTypeChildren = t => {\n let s = t._start;\n const arr = [];\n while (s) {\n arr.push(s);\n s = s.right;\n }\n return arr\n};\n\n/**\n * Call event listeners with an event. This will also add an event to all\n * parents (for `.observeDeep` handlers).\n *\n * @template EventType\n * @param {AbstractType} type\n * @param {Transaction} transaction\n * @param {EventType} event\n */\nconst callTypeObservers = (type, transaction, event) => {\n const changedType = type;\n const changedParentTypes = transaction.changedParentTypes;\n while (true) {\n // @ts-ignore\n setIfUndefined(changedParentTypes, type, () => []).push(event);\n if (type._item === null) {\n break\n }\n type = /** @type {AbstractType} */ (type._item.parent);\n }\n callEventHandlerListeners(changedType._eH, event, transaction);\n};\n\n/**\n * @template EventType\n * Abstract Yjs Type class\n */\nclass AbstractType {\n constructor () {\n /**\n * @type {Item|null}\n */\n this._item = null;\n /**\n * @type {Map}\n */\n this._map = new Map();\n /**\n * @type {Item|null}\n */\n this._start = null;\n /**\n * @type {Doc|null}\n */\n this.doc = null;\n this._length = 0;\n /**\n * Event handlers\n * @type {EventHandler}\n */\n this._eH = createEventHandler();\n /**\n * Deep event handlers\n * @type {EventHandler,Transaction>}\n */\n this._dEH = createEventHandler();\n /**\n * @type {null | Array}\n */\n this._searchMarker = null;\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item|null} item\n */\n _integrate (y, item) {\n this.doc = y;\n this._item = item;\n }\n\n /**\n * @return {AbstractType}\n */\n _copy () {\n throw methodUnimplemented()\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n */\n _write (encoder) { }\n\n /**\n * The first non-deleted item\n */\n get _first () {\n let n = this._start;\n while (n !== null && n.deleted) {\n n = n.right;\n }\n return n\n }\n\n /**\n * Creates YEvent and calls all type observers.\n * Must be implemented by each type.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n if (!transaction.local && this._searchMarker) {\n this._searchMarker.length = 0;\n }\n }\n\n /**\n * Observe all events that are created on this type.\n *\n * @param {function(EventType, Transaction):void} f Observer function\n */\n observe (f) {\n addEventHandlerListener(this._eH, f);\n }\n\n /**\n * Observe all events that are created by this type and its children.\n *\n * @param {function(Array,Transaction):void} f Observer function\n */\n observeDeep (f) {\n addEventHandlerListener(this._dEH, f);\n }\n\n /**\n * Unregister an observer function.\n *\n * @param {function(EventType,Transaction):void} f Observer function\n */\n unobserve (f) {\n removeEventHandlerListener(this._eH, f);\n }\n\n /**\n * Unregister an observer function.\n *\n * @param {function(Array,Transaction):void} f Observer function\n */\n unobserveDeep (f) {\n removeEventHandlerListener(this._dEH, f);\n }\n\n /**\n * @abstract\n * @return {any}\n */\n toJSON () {}\n}\n\n/**\n * @param {AbstractType} type\n * @return {Array}\n *\n * @private\n * @function\n */\nconst typeListToArray = type => {\n const cs = [];\n let n = type._start;\n while (n !== null) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent();\n for (let i = 0; i < c.length; i++) {\n cs.push(c[i]);\n }\n }\n n = n.right;\n }\n return cs\n};\n\n/**\n * @param {AbstractType} type\n * @param {Snapshot} snapshot\n * @return {Array}\n *\n * @private\n * @function\n */\nconst typeListToArraySnapshot = (type, snapshot) => {\n const cs = [];\n let n = type._start;\n while (n !== null) {\n if (n.countable && isVisible(n, snapshot)) {\n const c = n.content.getContent();\n for (let i = 0; i < c.length; i++) {\n cs.push(c[i]);\n }\n }\n n = n.right;\n }\n return cs\n};\n\n/**\n * Executes a provided function on once on overy element of this YArray.\n *\n * @param {AbstractType} type\n * @param {function(any,number,any):void} f A function to execute on every element of this YArray.\n *\n * @private\n * @function\n */\nconst typeListForEach = (type, f) => {\n let index = 0;\n let n = type._start;\n while (n !== null) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent();\n for (let i = 0; i < c.length; i++) {\n f(c[i], index++, type);\n }\n }\n n = n.right;\n }\n};\n\n/**\n * @template C,R\n * @param {AbstractType} type\n * @param {function(C,number,AbstractType):R} f\n * @return {Array}\n *\n * @private\n * @function\n */\nconst typeListMap = (type, f) => {\n /**\n * @type {Array}\n */\n const result = [];\n typeListForEach(type, (c, i) => {\n result.push(f(c, i, type));\n });\n return result\n};\n\n/**\n * @param {AbstractType} type\n * @return {IterableIterator}\n *\n * @private\n * @function\n */\nconst typeListCreateIterator = type => {\n let n = type._start;\n /**\n * @type {Array|null}\n */\n let currentContent = null;\n let currentContentIndex = 0;\n return {\n [Symbol.iterator] () {\n return this\n },\n next: () => {\n // find some content\n if (currentContent === null) {\n while (n !== null && n.deleted) {\n n = n.right;\n }\n // check if we reached the end, no need to check currentContent, because it does not exist\n if (n === null) {\n return {\n done: true,\n value: undefined\n }\n }\n // we found n, so we can set currentContent\n currentContent = n.content.getContent();\n currentContentIndex = 0;\n n = n.right; // we used the content of n, now iterate to next\n }\n const value = currentContent[currentContentIndex++];\n // check if we need to empty currentContent\n if (currentContent.length <= currentContentIndex) {\n currentContent = null;\n }\n return {\n done: false,\n value\n }\n }\n }\n};\n\n/**\n * @param {AbstractType} type\n * @param {number} index\n * @return {any}\n *\n * @private\n * @function\n */\nconst typeListGet = (type, index) => {\n const marker = findMarker(type, index);\n let n = type._start;\n if (marker !== null) {\n n = marker.p;\n index -= marker.index;\n }\n for (; n !== null; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index < n.length) {\n return n.content.getContent()[index]\n }\n index -= n.length;\n }\n }\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {Item?} referenceItem\n * @param {Array|Array|boolean|number|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nconst typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => {\n let left = referenceItem;\n const doc = transaction.doc;\n const ownClientId = doc.clientID;\n const store = doc.store;\n const right = referenceItem === null ? parent._start : referenceItem.right;\n /**\n * @type {Array|number>}\n */\n let jsonContent = [];\n const packJsonContent = () => {\n if (jsonContent.length > 0) {\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent));\n left.integrate(transaction, 0);\n jsonContent = [];\n }\n };\n content.forEach(c => {\n switch (c.constructor) {\n case Number:\n case Object:\n case Boolean:\n case Array:\n case String:\n jsonContent.push(c);\n break\n default:\n packJsonContent();\n switch (c.constructor) {\n case Uint8Array:\n case ArrayBuffer:\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array(/** @type {Uint8Array} */ (c))));\n left.integrate(transaction, 0);\n break\n case Doc:\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc(/** @type {Doc} */ (c)));\n left.integrate(transaction, 0);\n break\n default:\n if (c instanceof AbstractType) {\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c));\n left.integrate(transaction, 0);\n } else {\n throw new Error('Unexpected content type in insert operation')\n }\n }\n }\n });\n packJsonContent();\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @param {Array|Array|number|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nconst typeListInsertGenerics = (transaction, parent, index, content) => {\n if (index === 0) {\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, index, content.length);\n }\n return typeListInsertGenericsAfter(transaction, parent, null, content)\n }\n const startIndex = index;\n const marker = findMarker(parent, index);\n let n = parent._start;\n if (marker !== null) {\n n = marker.p;\n index -= marker.index;\n // we need to iterate one to the left so that the algorithm works\n if (index === 0) {\n // @todo refactor this as it actually doesn't consider formats\n n = n.prev; // important! get the left undeleted item so that we can actually decrease index\n index += (n && n.countable && !n.deleted) ? n.length : 0;\n }\n }\n for (; n !== null; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index <= n.length) {\n if (index < n.length) {\n // insert in-between\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index));\n }\n break\n }\n index -= n.length;\n }\n }\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, startIndex, content.length);\n }\n return typeListInsertGenericsAfter(transaction, parent, n, content)\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @param {number} length\n *\n * @private\n * @function\n */\nconst typeListDelete = (transaction, parent, index, length) => {\n if (length === 0) { return }\n const startIndex = index;\n const startLength = length;\n const marker = findMarker(parent, index);\n let n = parent._start;\n if (marker !== null) {\n n = marker.p;\n index -= marker.index;\n }\n // compute the first item to be deleted\n for (; n !== null && index > 0; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index < n.length) {\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index));\n }\n index -= n.length;\n }\n }\n // delete all items until done\n while (length > 0 && n !== null) {\n if (!n.deleted) {\n if (length < n.length) {\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length));\n }\n n.delete(transaction);\n length -= n.length;\n }\n n = n.right;\n }\n if (length > 0) {\n throw create$1('array length exceeded')\n }\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, startIndex, -startLength + length /* in case we remove the above exception */);\n }\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {string} key\n *\n * @private\n * @function\n */\nconst typeMapDelete = (transaction, parent, key) => {\n const c = parent._map.get(key);\n if (c !== undefined) {\n c.delete(transaction);\n }\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {string} key\n * @param {Object|number|Array|string|Uint8Array|AbstractType} value\n *\n * @private\n * @function\n */\nconst typeMapSet = (transaction, parent, key, value) => {\n const left = parent._map.get(key) || null;\n const doc = transaction.doc;\n const ownClientId = doc.clientID;\n let content;\n if (value == null) {\n content = new ContentAny([value]);\n } else {\n switch (value.constructor) {\n case Number:\n case Object:\n case Boolean:\n case Array:\n case String:\n content = new ContentAny([value]);\n break\n case Uint8Array:\n content = new ContentBinary(/** @type {Uint8Array} */ (value));\n break\n case Doc:\n content = new ContentDoc(/** @type {Doc} */ (value));\n break\n default:\n if (value instanceof AbstractType) {\n content = new ContentType(value);\n } else {\n throw new Error('Unexpected content type')\n }\n }\n }\n new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0);\n};\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined}\n *\n * @private\n * @function\n */\nconst typeMapGet = (parent, key) => {\n const val = parent._map.get(key);\n return val !== undefined && !val.deleted ? val.content.getContent()[val.length - 1] : undefined\n};\n\n/**\n * @param {AbstractType} parent\n * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined>}\n *\n * @private\n * @function\n */\nconst typeMapGetAll = (parent) => {\n /**\n * @type {Object}\n */\n const res = {};\n parent._map.forEach((value, key) => {\n if (!value.deleted) {\n res[key] = value.content.getContent()[value.length - 1];\n }\n });\n return res\n};\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @return {boolean}\n *\n * @private\n * @function\n */\nconst typeMapHas = (parent, key) => {\n const val = parent._map.get(key);\n return val !== undefined && !val.deleted\n};\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @param {Snapshot} snapshot\n * @return {Object|number|Array|string|Uint8Array|AbstractType|undefined}\n *\n * @private\n * @function\n */\nconst typeMapGetSnapshot = (parent, key, snapshot) => {\n let v = parent._map.get(key) || null;\n while (v !== null && (!snapshot.sv.has(v.id.client) || v.id.clock >= (snapshot.sv.get(v.id.client) || 0))) {\n v = v.left;\n }\n return v !== null && isVisible(v, snapshot) ? v.content.getContent()[v.length - 1] : undefined\n};\n\n/**\n * @param {Map} map\n * @return {IterableIterator>}\n *\n * @private\n * @function\n */\nconst createMapIterator = map => iteratorFilter(map.entries(), /** @param {any} entry */ entry => !entry[1].deleted);\n\n/**\n * @module YArray\n */\n\n/**\n * Event that describes the changes on a YArray\n * @template T\n */\nclass YArrayEvent extends YEvent {\n /**\n * @param {YArray} yarray The changed type\n * @param {Transaction} transaction The transaction object\n */\n constructor (yarray, transaction) {\n super(yarray, transaction);\n this._transaction = transaction;\n }\n}\n\n/**\n * A shared Array implementation.\n * @template T\n * @extends AbstractType>\n * @implements {Iterable}\n */\nclass YArray extends AbstractType {\n constructor () {\n super();\n /**\n * @type {Array?}\n * @private\n */\n this._prelimContent = [];\n /**\n * @type {Array}\n */\n this._searchMarker = [];\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item);\n this.insert(0, /** @type {Array} */ (this._prelimContent));\n this._prelimContent = null;\n }\n\n _copy () {\n return new YArray()\n }\n\n get length () {\n return this._prelimContent === null ? this._length : this._prelimContent.length\n }\n\n /**\n * Creates YArrayEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n super._callObserver(transaction, parentSubs);\n callTypeObservers(this, transaction, new YArrayEvent(this, transaction));\n }\n\n /**\n * Inserts new content at an index.\n *\n * Important: This function expects an array of content. Not just a content\n * object. The reason for this \"weirdness\" is that inserting several elements\n * is very efficient when it is done as a single operation.\n *\n * @example\n * // Insert character 'a' at position 0\n * yarray.insert(0, ['a'])\n * // Insert numbers 1, 2 at position 1\n * yarray.insert(1, [1, 2])\n *\n * @param {number} index The index to insert content at.\n * @param {Array} content The array of content\n */\n insert (index, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListInsertGenerics(transaction, this, index, content);\n });\n } else {\n /** @type {Array} */ (this._prelimContent).splice(index, 0, ...content);\n }\n }\n\n /**\n * Appends content to this YArray.\n *\n * @param {Array} content Array of content to append.\n */\n push (content) {\n this.insert(this.length, content);\n }\n\n /**\n * Preppends content to this YArray.\n *\n * @param {Array} content Array of content to preppend.\n */\n unshift (content) {\n this.insert(0, content);\n }\n\n /**\n * Deletes elements starting from an index.\n *\n * @param {number} index Index at which to start deleting elements\n * @param {number} length The number of elements to remove. Defaults to 1.\n */\n delete (index, length = 1) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListDelete(transaction, this, index, length);\n });\n } else {\n /** @type {Array} */ (this._prelimContent).splice(index, length);\n }\n }\n\n /**\n * Returns the i-th element from a YArray.\n *\n * @param {number} index The index of the element to return from the YArray\n * @return {T}\n */\n get (index) {\n return typeListGet(this, index)\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @return {Array}\n */\n toArray () {\n return typeListToArray(this)\n }\n\n /**\n * Transforms this Shared Type to a JSON object.\n *\n * @return {Array}\n */\n toJSON () {\n return this.map(c => c instanceof AbstractType ? c.toJSON() : c)\n }\n\n /**\n * Returns an Array with the result of calling a provided function on every\n * element of this YArray.\n *\n * @template T,M\n * @param {function(T,number,YArray):M} f Function that produces an element of the new Array\n * @return {Array} A new array with each element being the result of the\n * callback function\n */\n map (f) {\n return typeListMap(this, /** @type {any} */ (f))\n }\n\n /**\n * Executes a provided function on once on overy element of this YArray.\n *\n * @param {function(T,number,YArray):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n typeListForEach(this, f);\n }\n\n /**\n * @return {IterableIterator}\n */\n [Symbol.iterator] () {\n return typeListCreateIterator(this)\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YArrayRefID);\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n *\n * @private\n * @function\n */\nconst readYArray = decoder => new YArray();\n\n/**\n * @template T\n * Event that describes the changes on a YMap.\n */\nclass YMapEvent extends YEvent {\n /**\n * @param {YMap} ymap The YArray that changed.\n * @param {Transaction} transaction\n * @param {Set} subs The keys that changed.\n */\n constructor (ymap, transaction, subs) {\n super(ymap, transaction);\n this.keysChanged = subs;\n }\n}\n\n/**\n * @template T number|string|Object|Array|Uint8Array\n * A shared Map implementation.\n *\n * @extends AbstractType>\n * @implements {Iterable}\n */\nclass YMap extends AbstractType {\n /**\n *\n * @param {Iterable=} entries - an optional iterable to initialize the YMap\n */\n constructor (entries) {\n super();\n /**\n * @type {Map?}\n * @private\n */\n this._prelimContent = null;\n\n if (entries === undefined) {\n this._prelimContent = new Map();\n } else {\n this._prelimContent = new Map(entries);\n }\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n ;/** @type {Map} */ (this._prelimContent).forEach((value, key) => {\n this.set(key, value);\n });\n this._prelimContent = null;\n }\n\n _copy () {\n return new YMap()\n }\n\n /**\n * Creates YMapEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs));\n }\n\n /**\n * Transforms this Shared Type to a JSON object.\n *\n * @return {Object}\n */\n toJSON () {\n /**\n * @type {Object}\n */\n const map = {};\n this._map.forEach((item, key) => {\n if (!item.deleted) {\n const v = item.content.getContent()[item.length - 1];\n map[key] = v instanceof AbstractType ? v.toJSON() : v;\n }\n });\n return map\n }\n\n /**\n * Returns the size of the YMap (count of key/value pairs)\n *\n * @return {number}\n */\n get size () {\n return [...createMapIterator(this._map)].length\n }\n\n /**\n * Returns the keys for each element in the YMap Type.\n *\n * @return {IterableIterator}\n */\n keys () {\n return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[0])\n }\n\n /**\n * Returns the values for each element in the YMap Type.\n *\n * @return {IterableIterator}\n */\n values () {\n return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[1].content.getContent()[v[1].length - 1])\n }\n\n /**\n * Returns an Iterator of [key, value] pairs\n *\n * @return {IterableIterator}\n */\n entries () {\n return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => [v[0], v[1].content.getContent()[v[1].length - 1]])\n }\n\n /**\n * Executes a provided function on once on every key-value pair.\n *\n * @param {function(T,string,YMap):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n /**\n * @type {Object}\n */\n const map = {};\n this._map.forEach((item, key) => {\n if (!item.deleted) {\n f(item.content.getContent()[item.length - 1], key, this);\n }\n });\n return map\n }\n\n /**\n * @return {IterableIterator}\n */\n [Symbol.iterator] () {\n return this.entries()\n }\n\n /**\n * Remove a specified element from this YMap.\n *\n * @param {string} key The key of the element to remove.\n */\n delete (key) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, key);\n });\n } else {\n /** @type {Map} */ (this._prelimContent).delete(key);\n }\n }\n\n /**\n * Adds or updates an element with a specified key and value.\n *\n * @param {string} key The key of the element to add to this YMap\n * @param {T} value The value of the element to add\n */\n set (key, value) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, key, value);\n });\n } else {\n /** @type {Map} */ (this._prelimContent).set(key, value);\n }\n return value\n }\n\n /**\n * Returns a specified element from this YMap.\n *\n * @param {string} key\n * @return {T|undefined}\n */\n get (key) {\n return /** @type {any} */ (typeMapGet(this, key))\n }\n\n /**\n * Returns a boolean indicating whether the specified key exists or not.\n *\n * @param {string} key The key to test.\n * @return {boolean}\n */\n has (key) {\n return typeMapHas(this, key)\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YMapRefID);\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n *\n * @private\n * @function\n */\nconst readYMap = decoder => new YMap();\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nconst equalAttrs = (a, b) => a === b || (typeof a === 'object' && typeof b === 'object' && a && b && equalFlat(a, b));\n\nclass ItemTextListPosition {\n /**\n * @param {Item|null} left\n * @param {Item|null} right\n * @param {number} index\n * @param {Map} currentAttributes\n */\n constructor (left, right, index, currentAttributes) {\n this.left = left;\n this.right = right;\n this.index = index;\n this.currentAttributes = currentAttributes;\n }\n\n /**\n * Only call this if you know that this.right is defined\n */\n forward () {\n if (this.right === null) {\n unexpectedCase();\n }\n switch (this.right.content.constructor) {\n case ContentEmbed:\n case ContentString:\n if (!this.right.deleted) {\n this.index += this.right.length;\n }\n break\n case ContentFormat:\n if (!this.right.deleted) {\n updateCurrentAttributes(this.currentAttributes, /** @type {ContentFormat} */ (this.right.content));\n }\n break\n }\n this.left = this.right;\n this.right = this.right.right;\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {ItemTextListPosition} pos\n * @param {number} count steps to move forward\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst findNextPosition = (transaction, pos, count) => {\n while (pos.right !== null && count > 0) {\n switch (pos.right.content.constructor) {\n case ContentEmbed:\n case ContentString:\n if (!pos.right.deleted) {\n if (count < pos.right.length) {\n // split right\n getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count));\n }\n pos.index += pos.right.length;\n count -= pos.right.length;\n }\n break\n case ContentFormat:\n if (!pos.right.deleted) {\n updateCurrentAttributes(pos.currentAttributes, /** @type {ContentFormat} */ (pos.right.content));\n }\n break\n }\n pos.left = pos.right;\n pos.right = pos.right.right;\n // pos.forward() - we don't forward because that would halve the performance because we already do the checks above\n }\n return pos\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst findPosition = (transaction, parent, index) => {\n const currentAttributes = new Map();\n const marker = findMarker(parent, index);\n if (marker) {\n const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes);\n return findNextPosition(transaction, pos, index - marker.index)\n } else {\n const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes);\n return findNextPosition(transaction, pos, index)\n }\n};\n\n/**\n * Negate applied formats\n *\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {Map} negatedAttributes\n *\n * @private\n * @function\n */\nconst insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => {\n // check if we really need to remove attributes\n while (\n currPos.right !== null && (\n currPos.right.deleted === true || (\n currPos.right.content.constructor === ContentFormat &&\n equalAttrs(negatedAttributes.get(/** @type {ContentFormat} */ (currPos.right.content).key), /** @type {ContentFormat} */ (currPos.right.content).value)\n )\n )\n ) {\n if (!currPos.right.deleted) {\n negatedAttributes.delete(/** @type {ContentFormat} */ (currPos.right.content).key);\n }\n currPos.forward();\n }\n const doc = transaction.doc;\n const ownClientId = doc.clientID;\n let left = currPos.left;\n const right = currPos.right;\n negatedAttributes.forEach((val, key) => {\n left = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val));\n left.integrate(transaction, 0);\n });\n};\n\n/**\n * @param {Map} currentAttributes\n * @param {ContentFormat} format\n *\n * @private\n * @function\n */\nconst updateCurrentAttributes = (currentAttributes, format) => {\n const { key, value } = format;\n if (value === null) {\n currentAttributes.delete(key);\n } else {\n currentAttributes.set(key, value);\n }\n};\n\n/**\n * @param {ItemTextListPosition} currPos\n * @param {Object} attributes\n *\n * @private\n * @function\n */\nconst minimizeAttributeChanges = (currPos, attributes) => {\n // go right while attributes[right.key] === right.value (or right is deleted)\n while (true) {\n if (currPos.right === null) {\n break\n } else if (currPos.right.deleted || (currPos.right.content.constructor === ContentFormat && equalAttrs(attributes[(/** @type {ContentFormat} */ (currPos.right.content)).key] || null, /** @type {ContentFormat} */ (currPos.right.content).value))) ; else {\n break\n }\n currPos.forward();\n }\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {Object} attributes\n * @return {Map}\n *\n * @private\n * @function\n **/\nconst insertAttributes = (transaction, parent, currPos, attributes) => {\n const doc = transaction.doc;\n const ownClientId = doc.clientID;\n const negatedAttributes = new Map();\n // insert format-start items\n for (const key in attributes) {\n const val = attributes[key];\n const currentVal = currPos.currentAttributes.get(key) || null;\n if (!equalAttrs(currentVal, val)) {\n // save negated attribute (set null if currentVal undefined)\n negatedAttributes.set(key, currentVal);\n const { left, right } = currPos;\n currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val));\n currPos.right.integrate(transaction, 0);\n currPos.forward();\n }\n }\n return negatedAttributes\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {string|object} text\n * @param {Object} attributes\n *\n * @private\n * @function\n **/\nconst insertText = (transaction, parent, currPos, text, attributes) => {\n currPos.currentAttributes.forEach((val, key) => {\n if (attributes[key] === undefined) {\n attributes[key] = null;\n }\n });\n const doc = transaction.doc;\n const ownClientId = doc.clientID;\n minimizeAttributeChanges(currPos, attributes);\n const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes);\n // insert content\n const content = text.constructor === String ? new ContentString(/** @type {string} */ (text)) : new ContentEmbed(text);\n let { left, right, index } = currPos;\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength());\n }\n right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content);\n right.integrate(transaction, 0);\n currPos.right = right;\n currPos.index = index;\n currPos.forward();\n insertNegatedAttributes(transaction, parent, currPos, negatedAttributes);\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {number} length\n * @param {Object} attributes\n *\n * @private\n * @function\n */\nconst formatText = (transaction, parent, currPos, length, attributes) => {\n const doc = transaction.doc;\n const ownClientId = doc.clientID;\n minimizeAttributeChanges(currPos, attributes);\n const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes);\n // iterate until first non-format or null is found\n // delete all formats with attributes[format.key] != null\n while (length > 0 && currPos.right !== null) {\n if (!currPos.right.deleted) {\n switch (currPos.right.content.constructor) {\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (currPos.right.content);\n const attr = attributes[key];\n if (attr !== undefined) {\n if (equalAttrs(attr, value)) {\n negatedAttributes.delete(key);\n } else {\n negatedAttributes.set(key, value);\n }\n currPos.right.delete(transaction);\n }\n break\n }\n case ContentEmbed:\n case ContentString:\n if (length < currPos.right.length) {\n getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length));\n }\n length -= currPos.right.length;\n break\n }\n }\n currPos.forward();\n }\n // Quill just assumes that the editor starts with a newline and that it always\n // ends with a newline. We only insert that newline when a new newline is\n // inserted - i.e when length is bigger than type.length\n if (length > 0) {\n let newlines = '';\n for (; length > 0; length--) {\n newlines += '\\n';\n }\n currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines));\n currPos.right.integrate(transaction, 0);\n currPos.forward();\n }\n insertNegatedAttributes(transaction, parent, currPos, negatedAttributes);\n};\n\n/**\n * Call this function after string content has been deleted in order to\n * clean up formatting Items.\n *\n * @param {Transaction} transaction\n * @param {Item} start\n * @param {Item|null} end exclusive end, automatically iterates to the next Content Item\n * @param {Map} startAttributes\n * @param {Map} endAttributes This attribute is modified!\n * @return {number} The amount of formatting Items deleted.\n *\n * @function\n */\nconst cleanupFormattingGap = (transaction, start, end, startAttributes, endAttributes) => {\n while (end && end.content.constructor !== ContentString && end.content.constructor !== ContentEmbed) {\n if (!end.deleted && end.content.constructor === ContentFormat) {\n updateCurrentAttributes(endAttributes, /** @type {ContentFormat} */ (end.content));\n }\n end = end.right;\n }\n let cleanups = 0;\n while (start !== end) {\n if (!start.deleted) {\n const content = start.content;\n switch (content.constructor) {\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (content);\n if ((endAttributes.get(key) || null) !== value || (startAttributes.get(key) || null) === value) {\n // Either this format is overwritten or it is not necessary because the attribute already existed.\n start.delete(transaction);\n cleanups++;\n }\n break\n }\n }\n }\n start = /** @type {Item} */ (start.right);\n }\n return cleanups\n};\n\n/**\n * @param {Transaction} transaction\n * @param {Item | null} item\n */\nconst cleanupContextlessFormattingGap = (transaction, item) => {\n // iterate until item.right is null or content\n while (item && item.right && (item.right.deleted || (item.right.content.constructor !== ContentString && item.right.content.constructor !== ContentEmbed))) {\n item = item.right;\n }\n const attrs = new Set();\n // iterate back until a content item is found\n while (item && (item.deleted || (item.content.constructor !== ContentString && item.content.constructor !== ContentEmbed))) {\n if (!item.deleted && item.content.constructor === ContentFormat) {\n const key = /** @type {ContentFormat} */ (item.content).key;\n if (attrs.has(key)) {\n item.delete(transaction);\n } else {\n attrs.add(key);\n }\n }\n item = item.left;\n }\n};\n\n/**\n * This function is experimental and subject to change / be removed.\n *\n * Ideally, we don't need this function at all. Formatting attributes should be cleaned up\n * automatically after each change. This function iterates twice over the complete YText type\n * and removes unnecessary formatting attributes. This is also helpful for testing.\n *\n * This function won't be exported anymore as soon as there is confidence that the YText type works as intended.\n *\n * @param {YText} type\n * @return {number} How many formatting attributes have been cleaned up.\n */\nconst cleanupYTextFormatting = type => {\n let res = 0;\n transact(/** @type {Doc} */ (type.doc), transaction => {\n let start = /** @type {Item} */ (type._start);\n let end = type._start;\n let startAttributes = create$2();\n const currentAttributes = copy(startAttributes);\n while (end) {\n if (end.deleted === false) {\n switch (end.content.constructor) {\n case ContentFormat:\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (end.content));\n break\n case ContentEmbed:\n case ContentString:\n res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes);\n startAttributes = copy(currentAttributes);\n start = end;\n break\n }\n }\n end = end.right;\n }\n });\n return res\n};\n\n/**\n * @param {Transaction} transaction\n * @param {ItemTextListPosition} currPos\n * @param {number} length\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst deleteText = (transaction, currPos, length) => {\n const startLength = length;\n const startAttrs = copy(currPos.currentAttributes);\n const start = currPos.right;\n while (length > 0 && currPos.right !== null) {\n if (currPos.right.deleted === false) {\n switch (currPos.right.content.constructor) {\n case ContentEmbed:\n case ContentString:\n if (length < currPos.right.length) {\n getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length));\n }\n length -= currPos.right.length;\n currPos.right.delete(transaction);\n break\n }\n }\n currPos.forward();\n }\n if (start) {\n cleanupFormattingGap(transaction, start, currPos.right, startAttrs, copy(currPos.currentAttributes));\n }\n const parent = /** @type {AbstractType} */ (/** @type {Item} */ (currPos.left || currPos.right).parent);\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length);\n }\n return currPos\n};\n\n/**\n * The Quill Delta format represents changes on a text document with\n * formatting information. For mor information visit {@link https://quilljs.com/docs/delta/|Quill Delta}\n *\n * @example\n * {\n * ops: [\n * { insert: 'Gandalf', attributes: { bold: true } },\n * { insert: ' the ' },\n * { insert: 'Grey', attributes: { color: '#cccccc' } }\n * ]\n * }\n *\n */\n\n/**\n * Attributes that can be assigned to a selection of text.\n *\n * @example\n * {\n * bold: true,\n * font-size: '40px'\n * }\n *\n * @typedef {Object} TextAttributes\n */\n\n/**\n * @typedef {Object} DeltaItem\n * @property {number|undefined} DeltaItem.delete\n * @property {number|undefined} DeltaItem.retain\n * @property {string|undefined} DeltaItem.insert\n * @property {Object} DeltaItem.attributes\n */\n\n/**\n * Event that describes the changes on a YText type.\n */\nclass YTextEvent extends YEvent {\n /**\n * @param {YText} ytext\n * @param {Transaction} transaction\n */\n constructor (ytext, transaction) {\n super(ytext, transaction);\n /**\n * @type {Array|null}\n */\n this._delta = null;\n }\n\n /**\n * Compute the changes in the delta format.\n * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document.\n *\n * @type {Array}\n *\n * @public\n */\n get delta () {\n if (this._delta === null) {\n const y = /** @type {Doc} */ (this.target.doc);\n this._delta = [];\n transact(y, transaction => {\n const delta = /** @type {Array} */ (this._delta);\n const currentAttributes = new Map(); // saves all current attributes for insert\n const oldAttributes = new Map();\n let item = this.target._start;\n /**\n * @type {string?}\n */\n let action = null;\n /**\n * @type {Object}\n */\n const attributes = {}; // counts added or removed new attributes for retain\n /**\n * @type {string|object}\n */\n let insert = '';\n let retain = 0;\n let deleteLen = 0;\n const addOp = () => {\n if (action !== null) {\n /**\n * @type {any}\n */\n let op;\n switch (action) {\n case 'delete':\n op = { delete: deleteLen };\n deleteLen = 0;\n break\n case 'insert':\n op = { insert };\n if (currentAttributes.size > 0) {\n op.attributes = {};\n currentAttributes.forEach((value, key) => {\n if (value !== null) {\n op.attributes[key] = value;\n }\n });\n }\n insert = '';\n break\n case 'retain':\n op = { retain };\n if (Object.keys(attributes).length > 0) {\n op.attributes = {};\n for (const key in attributes) {\n op.attributes[key] = attributes[key];\n }\n }\n retain = 0;\n break\n }\n delta.push(op);\n action = null;\n }\n };\n while (item !== null) {\n switch (item.content.constructor) {\n case ContentEmbed:\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n addOp();\n action = 'insert';\n insert = /** @type {ContentEmbed} */ (item.content).embed;\n addOp();\n }\n } else if (this.deletes(item)) {\n if (action !== 'delete') {\n addOp();\n action = 'delete';\n }\n deleteLen += 1;\n } else if (!item.deleted) {\n if (action !== 'retain') {\n addOp();\n action = 'retain';\n }\n retain += 1;\n }\n break\n case ContentString:\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n if (action !== 'insert') {\n addOp();\n action = 'insert';\n }\n insert += /** @type {ContentString} */ (item.content).str;\n }\n } else if (this.deletes(item)) {\n if (action !== 'delete') {\n addOp();\n action = 'delete';\n }\n deleteLen += item.length;\n } else if (!item.deleted) {\n if (action !== 'retain') {\n addOp();\n action = 'retain';\n }\n retain += item.length;\n }\n break\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (item.content);\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n const curVal = currentAttributes.get(key) || null;\n if (!equalAttrs(curVal, value)) {\n if (action === 'retain') {\n addOp();\n }\n if (equalAttrs(value, (oldAttributes.get(key) || null))) {\n delete attributes[key];\n } else {\n attributes[key] = value;\n }\n } else {\n item.delete(transaction);\n }\n }\n } else if (this.deletes(item)) {\n oldAttributes.set(key, value);\n const curVal = currentAttributes.get(key) || null;\n if (!equalAttrs(curVal, value)) {\n if (action === 'retain') {\n addOp();\n }\n attributes[key] = curVal;\n }\n } else if (!item.deleted) {\n oldAttributes.set(key, value);\n const attr = attributes[key];\n if (attr !== undefined) {\n if (!equalAttrs(attr, value)) {\n if (action === 'retain') {\n addOp();\n }\n if (value === null) {\n attributes[key] = value;\n } else {\n delete attributes[key];\n }\n } else {\n item.delete(transaction);\n }\n }\n }\n if (!item.deleted) {\n if (action === 'insert') {\n addOp();\n }\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (item.content));\n }\n break\n }\n }\n item = item.right;\n }\n addOp();\n while (delta.length > 0) {\n const lastOp = delta[delta.length - 1];\n if (lastOp.retain !== undefined && lastOp.attributes === undefined) {\n // retain delta's if they don't assign attributes\n delta.pop();\n } else {\n break\n }\n }\n });\n }\n return this._delta\n }\n}\n\n/**\n * Type that represents text with formatting information.\n *\n * This type replaces y-richtext as this implementation is able to handle\n * block formats (format information on a paragraph), embeds (complex elements\n * like pictures and videos), and text formats (**bold**, *italic*).\n *\n * @extends AbstractType\n */\nclass YText extends AbstractType {\n /**\n * @param {String} [string] The initial value of the YText.\n */\n constructor (string) {\n super();\n /**\n * Array of pending operations on this type\n * @type {Array?}\n */\n this._pending = string !== undefined ? [() => this.insert(0, string)] : [];\n /**\n * @type {Array}\n */\n this._searchMarker = [];\n }\n\n /**\n * Number of characters of this text type.\n *\n * @type {number}\n */\n get length () {\n return this._length\n }\n\n /**\n * @param {Doc} y\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item);\n try {\n /** @type {Array} */ (this._pending).forEach(f => f());\n } catch (e) {\n console.error(e);\n }\n this._pending = null;\n }\n\n _copy () {\n return new YText()\n }\n\n /**\n * Creates YTextEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n super._callObserver(transaction, parentSubs);\n const event = new YTextEvent(this, transaction);\n const doc = transaction.doc;\n // If a remote change happened, we try to cleanup potential formatting duplicates.\n if (!transaction.local) {\n // check if another formatting item was inserted\n let foundFormattingItem = false;\n for (const [client, afterClock] of transaction.afterState.entries()) {\n const clock = transaction.beforeState.get(client) || 0;\n if (afterClock === clock) {\n continue\n }\n iterateStructs(transaction, /** @type {Array} */ (doc.store.clients.get(client)), clock, afterClock, item => {\n if (!item.deleted && /** @type {Item} */ (item).content.constructor === ContentFormat) {\n foundFormattingItem = true;\n }\n });\n if (foundFormattingItem) {\n break\n }\n }\n if (!foundFormattingItem) {\n iterateDeletedStructs(transaction, transaction.deleteSet, item => {\n if (item instanceof GC || foundFormattingItem) {\n return\n }\n if (item.parent === this && item.content.constructor === ContentFormat) {\n foundFormattingItem = true;\n }\n });\n }\n transact(doc, (t) => {\n if (foundFormattingItem) {\n // If a formatting item was inserted, we simply clean the whole type.\n // We need to compute currentAttributes for the current position anyway.\n cleanupYTextFormatting(this);\n } else {\n // If no formatting attribute was inserted, we can make due with contextless\n // formatting cleanups.\n // Contextless: it is not necessary to compute currentAttributes for the affected position.\n iterateDeletedStructs(t, t.deleteSet, item => {\n if (item instanceof GC) {\n return\n }\n if (item.parent === this) {\n cleanupContextlessFormattingGap(t, item);\n }\n });\n }\n });\n }\n callTypeObservers(this, transaction, event);\n }\n\n /**\n * Returns the unformatted string representation of this YText type.\n *\n * @public\n */\n toString () {\n let str = '';\n /**\n * @type {Item|null}\n */\n let n = this._start;\n while (n !== null) {\n if (!n.deleted && n.countable && n.content.constructor === ContentString) {\n str += /** @type {ContentString} */ (n.content).str;\n }\n n = n.right;\n }\n return str\n }\n\n /**\n * Returns the unformatted string representation of this YText type.\n *\n * @return {string}\n * @public\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * Apply a {@link Delta} on this shared YText type.\n *\n * @param {any} delta The changes to apply on this element.\n * @param {object} [opts]\n * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true.\n *\n *\n * @public\n */\n applyDelta (delta, { sanitize = true } = {}) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n const currPos = new ItemTextListPosition(null, this._start, 0, new Map());\n for (let i = 0; i < delta.length; i++) {\n const op = delta[i];\n if (op.insert !== undefined) {\n // Quill assumes that the content starts with an empty paragraph.\n // Yjs/Y.Text assumes that it starts empty. We always hide that\n // there is a newline at the end of the content.\n // If we omit this step, clients will see a different number of\n // paragraphs, but nothing bad will happen.\n const ins = (!sanitize && typeof op.insert === 'string' && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === '\\n') ? op.insert.slice(0, -1) : op.insert;\n if (typeof ins !== 'string' || ins.length > 0) {\n insertText(transaction, this, currPos, ins, op.attributes || {});\n }\n } else if (op.retain !== undefined) {\n formatText(transaction, this, currPos, op.retain, op.attributes || {});\n } else if (op.delete !== undefined) {\n deleteText(transaction, currPos, op.delete);\n }\n }\n });\n } else {\n /** @type {Array} */ (this._pending).push(() => this.applyDelta(delta));\n }\n }\n\n /**\n * Returns the Delta representation of this YText type.\n *\n * @param {Snapshot} [snapshot]\n * @param {Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', ID):any} [computeYChange]\n * @return {any} The Delta representation of this type.\n *\n * @public\n */\n toDelta (snapshot, prevSnapshot, computeYChange) {\n /**\n * @type{Array}\n */\n const ops = [];\n const currentAttributes = new Map();\n const doc = /** @type {Doc} */ (this.doc);\n let str = '';\n let n = this._start;\n function packStr () {\n if (str.length > 0) {\n // pack str with attributes to ops\n /**\n * @type {Object}\n */\n const attributes = {};\n let addAttributes = false;\n currentAttributes.forEach((value, key) => {\n addAttributes = true;\n attributes[key] = value;\n });\n /**\n * @type {Object}\n */\n const op = { insert: str };\n if (addAttributes) {\n op.attributes = attributes;\n }\n ops.push(op);\n str = '';\n }\n }\n // snapshots are merged again after the transaction, so we need to keep the\n // transalive until we are done\n transact(doc, transaction => {\n if (snapshot) {\n splitSnapshotAffectedStructs(transaction, snapshot);\n }\n if (prevSnapshot) {\n splitSnapshotAffectedStructs(transaction, prevSnapshot);\n }\n while (n !== null) {\n if (isVisible(n, snapshot) || (prevSnapshot !== undefined && isVisible(n, prevSnapshot))) {\n switch (n.content.constructor) {\n case ContentString: {\n const cur = currentAttributes.get('ychange');\n if (snapshot !== undefined && !isVisible(n, snapshot)) {\n if (cur === undefined || cur.user !== n.id.client || cur.state !== 'removed') {\n packStr();\n currentAttributes.set('ychange', computeYChange ? computeYChange('removed', n.id) : { type: 'removed' });\n }\n } else if (prevSnapshot !== undefined && !isVisible(n, prevSnapshot)) {\n if (cur === undefined || cur.user !== n.id.client || cur.state !== 'added') {\n packStr();\n currentAttributes.set('ychange', computeYChange ? computeYChange('added', n.id) : { type: 'added' });\n }\n } else if (cur !== undefined) {\n packStr();\n currentAttributes.delete('ychange');\n }\n str += /** @type {ContentString} */ (n.content).str;\n break\n }\n case ContentEmbed: {\n packStr();\n /**\n * @type {Object}\n */\n const op = {\n insert: /** @type {ContentEmbed} */ (n.content).embed\n };\n if (currentAttributes.size > 0) {\n const attrs = /** @type {Object} */ ({});\n op.attributes = attrs;\n currentAttributes.forEach((value, key) => {\n attrs[key] = value;\n });\n }\n ops.push(op);\n break\n }\n case ContentFormat:\n if (isVisible(n, snapshot)) {\n packStr();\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (n.content));\n }\n break\n }\n }\n n = n.right;\n }\n packStr();\n }, splitSnapshotAffectedStructs);\n return ops\n }\n\n /**\n * Insert text at a given index.\n *\n * @param {number} index The index at which to start inserting.\n * @param {String} text The text to insert at the specified position.\n * @param {TextAttributes} [attributes] Optionally define some formatting\n * information to apply on the inserted\n * Text.\n * @public\n */\n insert (index, text, attributes) {\n if (text.length <= 0) {\n return\n }\n const y = this.doc;\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index);\n if (!attributes) {\n attributes = {};\n // @ts-ignore\n pos.currentAttributes.forEach((v, k) => { attributes[k] = v; });\n }\n insertText(transaction, this, pos, text, attributes);\n });\n } else {\n /** @type {Array} */ (this._pending).push(() => this.insert(index, text, attributes));\n }\n }\n\n /**\n * Inserts an embed at a index.\n *\n * @param {number} index The index to insert the embed at.\n * @param {Object} embed The Object that represents the embed.\n * @param {TextAttributes} attributes Attribute information to apply on the\n * embed\n *\n * @public\n */\n insertEmbed (index, embed, attributes = {}) {\n if (embed.constructor !== Object) {\n throw new Error('Embed must be an Object')\n }\n const y = this.doc;\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index);\n insertText(transaction, this, pos, embed, attributes);\n });\n } else {\n /** @type {Array} */ (this._pending).push(() => this.insertEmbed(index, embed, attributes));\n }\n }\n\n /**\n * Deletes text starting from an index.\n *\n * @param {number} index Index at which to start deleting.\n * @param {number} length The number of characters to remove. Defaults to 1.\n *\n * @public\n */\n delete (index, length) {\n if (length === 0) {\n return\n }\n const y = this.doc;\n if (y !== null) {\n transact(y, transaction => {\n deleteText(transaction, findPosition(transaction, this, index), length);\n });\n } else {\n /** @type {Array} */ (this._pending).push(() => this.delete(index, length));\n }\n }\n\n /**\n * Assigns properties to a range of text.\n *\n * @param {number} index The position where to start formatting.\n * @param {number} length The amount of characters to assign properties to.\n * @param {TextAttributes} attributes Attribute information to apply on the\n * text.\n *\n * @public\n */\n format (index, length, attributes) {\n if (length === 0) {\n return\n }\n const y = this.doc;\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index);\n if (pos.right === null) {\n return\n }\n formatText(transaction, this, pos, length, attributes);\n });\n } else {\n /** @type {Array} */ (this._pending).push(() => this.format(index, length, attributes));\n }\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YTextRefID);\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {YText}\n *\n * @private\n * @function\n */\nconst readYText = decoder => new YText();\n\n/**\n * @module YXml\n */\n\n/**\n * Define the elements to which a set of CSS queries apply.\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors|CSS_Selectors}\n *\n * @example\n * query = '.classSelector'\n * query = 'nodeSelector'\n * query = '#idSelector'\n *\n * @typedef {string} CSS_Selector\n */\n\n/**\n * Dom filter function.\n *\n * @callback domFilter\n * @param {string} nodeName The nodeName of the element\n * @param {Map} attributes The map of attributes.\n * @return {boolean} Whether to include the Dom node in the YXmlElement.\n */\n\n/**\n * Represents a subset of the nodes of a YXmlElement / YXmlFragment and a\n * position within them.\n *\n * Can be created with {@link YXmlFragment#createTreeWalker}\n *\n * @public\n * @implements {Iterable}\n */\nclass YXmlTreeWalker {\n /**\n * @param {YXmlFragment | YXmlElement} root\n * @param {function(AbstractType):boolean} [f]\n */\n constructor (root, f = () => true) {\n this._filter = f;\n this._root = root;\n /**\n * @type {Item}\n */\n this._currentNode = /** @type {Item} */ (root._start);\n this._firstCall = true;\n }\n\n [Symbol.iterator] () {\n return this\n }\n\n /**\n * Get the next node.\n *\n * @return {IteratorResult} The next node.\n *\n * @public\n */\n next () {\n /**\n * @type {Item|null}\n */\n let n = this._currentNode;\n let type = /** @type {any} */ (n.content).type;\n if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { // if first call, we check if we can use the first item\n do {\n type = /** @type {any} */ (n.content).type;\n if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) {\n // walk down in the tree\n n = type._start;\n } else {\n // walk right or up in the tree\n while (n !== null) {\n if (n.right !== null) {\n n = n.right;\n break\n } else if (n.parent === this._root) {\n n = null;\n } else {\n n = /** @type {AbstractType} */ (n.parent)._item;\n }\n }\n }\n } while (n !== null && (n.deleted || !this._filter(/** @type {ContentType} */ (n.content).type)))\n }\n this._firstCall = false;\n if (n === null) {\n // @ts-ignore\n return { value: undefined, done: true }\n }\n this._currentNode = n;\n return { value: /** @type {any} */ (n.content).type, done: false }\n }\n}\n\n/**\n * Represents a list of {@link YXmlElement}.and {@link YXmlText} types.\n * A YxmlFragment is similar to a {@link YXmlElement}, but it does not have a\n * nodeName and it does not have attributes. Though it can be bound to a DOM\n * element - in this case the attributes and the nodeName are not shared.\n *\n * @public\n * @extends AbstractType\n */\nclass YXmlFragment extends AbstractType {\n constructor () {\n super();\n /**\n * @type {Array|null}\n */\n this._prelimContent = [];\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item);\n this.insert(0, /** @type {Array} */ (this._prelimContent));\n this._prelimContent = null;\n }\n\n _copy () {\n return new YXmlFragment()\n }\n\n get length () {\n return this._prelimContent === null ? this._length : this._prelimContent.length\n }\n\n /**\n * Create a subtree of childNodes.\n *\n * @example\n * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div')\n * for (let node in walker) {\n * // `node` is a div node\n * nop(node)\n * }\n *\n * @param {function(AbstractType):boolean} filter Function that is called on each child element and\n * returns a Boolean indicating whether the child\n * is to be included in the subtree.\n * @return {YXmlTreeWalker} A subtree and a position within it.\n *\n * @public\n */\n createTreeWalker (filter) {\n return new YXmlTreeWalker(this, filter)\n }\n\n /**\n * Returns the first YXmlElement that matches the query.\n * Similar to DOM's {@link querySelector}.\n *\n * Query support:\n * - tagname\n * TODO:\n * - id\n * - attribute\n *\n * @param {CSS_Selector} query The query on the children.\n * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null.\n *\n * @public\n */\n querySelector (query) {\n query = query.toUpperCase();\n // @ts-ignore\n const iterator = new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query);\n const next = iterator.next();\n if (next.done) {\n return null\n } else {\n return next.value\n }\n }\n\n /**\n * Returns all YXmlElements that match the query.\n * Similar to Dom's {@link querySelectorAll}.\n *\n * @todo Does not yet support all queries. Currently only query by tagName.\n *\n * @param {CSS_Selector} query The query on the children\n * @return {Array} The elements that match this query.\n *\n * @public\n */\n querySelectorAll (query) {\n query = query.toUpperCase();\n // @ts-ignore\n return Array.from(new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query))\n }\n\n /**\n * Creates YXmlEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction));\n }\n\n /**\n * Get the string representation of all the children of this YXmlFragment.\n *\n * @return {string} The string representation of all children.\n */\n toString () {\n return typeListMap(this, xml => xml.toString()).join('')\n }\n\n /**\n * @return {string}\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks={}] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const fragment = _document.createDocumentFragment();\n if (binding !== undefined) {\n binding._createAssociation(fragment, this);\n }\n typeListForEach(this, xmlType => {\n fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null);\n });\n return fragment\n }\n\n /**\n * Inserts new content at an index.\n *\n * @example\n * // Insert character 'a' at position 0\n * xml.insert(0, [new Y.XmlText('text')])\n *\n * @param {number} index The index to insert content at\n * @param {Array} content The array of content\n */\n insert (index, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListInsertGenerics(transaction, this, index, content);\n });\n } else {\n // @ts-ignore _prelimContent is defined because this is not yet integrated\n this._prelimContent.splice(index, 0, ...content);\n }\n }\n\n /**\n * Deletes elements starting from an index.\n *\n * @param {number} index Index at which to start deleting elements\n * @param {number} [length=1] The number of elements to remove. Defaults to 1.\n */\n delete (index, length = 1) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListDelete(transaction, this, index, length);\n });\n } else {\n // @ts-ignore _prelimContent is defined because this is not yet integrated\n this._prelimContent.splice(index, length);\n }\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @return {Array}\n */\n toArray () {\n return typeListToArray(this)\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {AbstractUpdateEncoder} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlFragmentRefID);\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {YXmlFragment}\n *\n * @private\n * @function\n */\nconst readYXmlFragment = decoder => new YXmlFragment();\n\n/**\n * An YXmlElement imitates the behavior of a\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}.\n *\n * * An YXmlElement has attributes (key value pairs)\n * * An YXmlElement has childElements that must inherit from YXmlElement\n */\nclass YXmlElement extends YXmlFragment {\n constructor (nodeName = 'UNDEFINED') {\n super();\n this.nodeName = nodeName;\n /**\n * @type {Map|null}\n */\n this._prelimAttrs = new Map();\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n ;(/** @type {Map} */ (this._prelimAttrs)).forEach((value, key) => {\n this.setAttribute(key, value);\n });\n this._prelimAttrs = null;\n }\n\n /**\n * Creates an Item with the same effect as this Item (without position effect)\n *\n * @return {YXmlElement}\n */\n _copy () {\n return new YXmlElement(this.nodeName)\n }\n\n /**\n * Returns the XML serialization of this YXmlElement.\n * The attributes are ordered by attribute-name, so you can easily use this\n * method to compare YXmlElements\n *\n * @return {string} The string representation of this type.\n *\n * @public\n */\n toString () {\n const attrs = this.getAttributes();\n const stringBuilder = [];\n const keys = [];\n for (const key in attrs) {\n keys.push(key);\n }\n keys.sort();\n const keysLen = keys.length;\n for (let i = 0; i < keysLen; i++) {\n const key = keys[i];\n stringBuilder.push(key + '=\"' + attrs[key] + '\"');\n }\n const nodeName = this.nodeName.toLocaleLowerCase();\n const attrsString = stringBuilder.length > 0 ? ' ' + stringBuilder.join(' ') : '';\n return `<${nodeName}${attrsString}>${super.toString()}`\n }\n\n /**\n * Removes an attribute from this YXmlElement.\n *\n * @param {String} attributeName The attribute name that is to be removed.\n *\n * @public\n */\n removeAttribute (attributeName) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, attributeName);\n });\n } else {\n /** @type {Map} */ (this._prelimAttrs).delete(attributeName);\n }\n }\n\n /**\n * Sets or updates an attribute.\n *\n * @param {String} attributeName The attribute name that is to be set.\n * @param {String} attributeValue The attribute value that is to be set.\n *\n * @public\n */\n setAttribute (attributeName, attributeValue) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, attributeName, attributeValue);\n });\n } else {\n /** @type {Map} */ (this._prelimAttrs).set(attributeName, attributeValue);\n }\n }\n\n /**\n * Returns an attribute value that belongs to the attribute name.\n *\n * @param {String} attributeName The attribute name that identifies the\n * queried value.\n * @return {String} The queried attribute value.\n *\n * @public\n */\n getAttribute (attributeName) {\n return /** @type {any} */ (typeMapGet(this, attributeName))\n }\n\n /**\n * Returns all attribute name/value pairs in a JSON Object.\n *\n * @param {Snapshot} [snapshot]\n * @return {Object} A JSON Object that describes the attributes.\n *\n * @public\n */\n getAttributes (snapshot) {\n return typeMapGetAll(this)\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks={}] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const dom = _document.createElement(this.nodeName);\n const attrs = this.getAttributes();\n for (const key in attrs) {\n dom.setAttribute(key, attrs[key]);\n }\n typeListForEach(this, yxml => {\n dom.appendChild(yxml.toDOM(_document, hooks, binding));\n });\n if (binding !== undefined) {\n binding._createAssociation(dom, this);\n }\n return dom\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {AbstractUpdateEncoder} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlElementRefID);\n encoder.writeKey(this.nodeName);\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {YXmlElement}\n *\n * @function\n */\nconst readYXmlElement = decoder => new YXmlElement(decoder.readKey());\n\n/**\n * An Event that describes changes on a YXml Element or Yxml Fragment\n */\nclass YXmlEvent extends YEvent {\n /**\n * @param {YXmlElement|YXmlFragment} target The target on which the event is created.\n * @param {Set} subs The set of changed attributes. `null` is included if the\n * child list changed.\n * @param {Transaction} transaction The transaction instance with wich the\n * change was created.\n */\n constructor (target, subs, transaction) {\n super(target, transaction);\n /**\n * Whether the children changed.\n * @type {Boolean}\n * @private\n */\n this.childListChanged = false;\n /**\n * Set of all changed attributes.\n * @type {Set}\n */\n this.attributesChanged = new Set();\n subs.forEach((sub) => {\n if (sub === null) {\n this.childListChanged = true;\n } else {\n this.attributesChanged.add(sub);\n }\n });\n }\n}\n\n/**\n * You can manage binding to a custom type with YXmlHook.\n *\n * @extends {YMap}\n */\nclass YXmlHook extends YMap {\n /**\n * @param {string} hookName nodeName of the Dom Node.\n */\n constructor (hookName) {\n super();\n /**\n * @type {string}\n */\n this.hookName = hookName;\n }\n\n /**\n * Creates an Item with the same effect as this Item (without position effect)\n */\n _copy () {\n return new YXmlHook(this.hookName)\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object.} [hooks] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type\n * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const hook = hooks[this.hookName];\n let dom;\n if (hook !== undefined) {\n dom = hook.createDom(this);\n } else {\n dom = document.createElement(this.hookName);\n }\n dom.setAttribute('data-yjs-hook', this.hookName);\n if (binding !== undefined) {\n binding._createAssociation(dom, this);\n }\n return dom\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {AbstractUpdateEncoder} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlHookRefID);\n encoder.writeKey(this.hookName);\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {YXmlHook}\n *\n * @private\n * @function\n */\nconst readYXmlHook = decoder =>\n new YXmlHook(decoder.readKey());\n\n/**\n * Represents text in a Dom Element. In the future this type will also handle\n * simple formatting information like bold and italic.\n */\nclass YXmlText extends YText {\n _copy () {\n return new YXmlText()\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlText.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks, binding) {\n const dom = _document.createTextNode(this.toString());\n if (binding !== undefined) {\n binding._createAssociation(dom, this);\n }\n return dom\n }\n\n toString () {\n // @ts-ignore\n return this.toDelta().map(delta => {\n const nestedNodes = [];\n for (const nodeName in delta.attributes) {\n const attrs = [];\n for (const key in delta.attributes[nodeName]) {\n attrs.push({ key, value: delta.attributes[nodeName][key] });\n }\n // sort attributes to get a unique order\n attrs.sort((a, b) => a.key < b.key ? -1 : 1);\n nestedNodes.push({ nodeName, attrs });\n }\n // sort node order to get a unique order\n nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1);\n // now convert to dom string\n let str = '';\n for (let i = 0; i < nestedNodes.length; i++) {\n const node = nestedNodes[i];\n str += `<${node.nodeName}`;\n for (let j = 0; j < node.attrs.length; j++) {\n const attr = node.attrs[j];\n str += ` ${attr.key}=\"${attr.value}\"`;\n }\n str += '>';\n }\n str += delta.insert;\n for (let i = nestedNodes.length - 1; i >= 0; i--) {\n str += ``;\n }\n return str\n }).join('')\n }\n\n /**\n * @return {string}\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlTextRefID);\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {YXmlText}\n *\n * @private\n * @function\n */\nconst readYXmlText = decoder => new YXmlText();\n\nclass AbstractStruct {\n /**\n * @param {ID} id\n * @param {number} length\n */\n constructor (id, length) {\n this.id = id;\n this.length = length;\n }\n\n /**\n * @type {boolean}\n */\n get deleted () {\n throw methodUnimplemented()\n }\n\n /**\n * Merge this struct with the item to the right.\n * This method is already assuming that `this.id.clock + this.length === this.id.clock`.\n * Also this method does *not* remove right from StructStore!\n * @param {AbstractStruct} right\n * @return {boolean} wether this merged with right\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder The encoder to write data to.\n * @param {number} offset\n * @param {number} encodingRef\n */\n write (encoder, offset, encodingRef) {\n throw methodUnimplemented()\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n throw methodUnimplemented()\n }\n}\n\nconst structGCRefNumber = 0;\n\n/**\n * @private\n */\nclass GC extends AbstractStruct {\n get deleted () {\n return true\n }\n\n delete () {}\n\n /**\n * @param {GC} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.length += right.length;\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n if (offset > 0) {\n this.id.clock += offset;\n this.length -= offset;\n }\n addStruct(transaction.doc.store, this);\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeInfo(structGCRefNumber);\n encoder.writeLen(this.length - offset);\n }\n\n /**\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n return null\n }\n}\n\nclass ContentBinary {\n /**\n * @param {Uint8Array} content\n */\n constructor (content) {\n this.content = content;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.content]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentBinary}\n */\n copy () {\n return new ContentBinary(this.content)\n }\n\n /**\n * @param {number} offset\n * @return {ContentBinary}\n */\n splice (offset) {\n throw methodUnimplemented()\n }\n\n /**\n * @param {ContentBinary} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeBuf(this.content);\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 3\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentBinary}\n */\nconst readContentBinary = decoder => new ContentBinary(decoder.readBuf());\n\nclass ContentDeleted {\n /**\n * @param {number} len\n */\n constructor (len) {\n this.len = len;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.len\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return []\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return false\n }\n\n /**\n * @return {ContentDeleted}\n */\n copy () {\n return new ContentDeleted(this.len)\n }\n\n /**\n * @param {number} offset\n * @return {ContentDeleted}\n */\n splice (offset) {\n const right = new ContentDeleted(this.len - offset);\n this.len = offset;\n return right\n }\n\n /**\n * @param {ContentDeleted} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.len += right.len;\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len);\n item.markDeleted();\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeLen(this.len - offset);\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 1\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentDeleted}\n */\nconst readContentDeleted = decoder => new ContentDeleted(decoder.readLen());\n\n/**\n * @private\n */\nclass ContentDoc {\n /**\n * @param {Doc} doc\n */\n constructor (doc) {\n if (doc._item) {\n console.error('This document was already integrated as a sub-document. You should create a second instance instead with the same guid.');\n }\n /**\n * @type {Doc}\n */\n this.doc = doc;\n /**\n * @type {any}\n */\n const opts = {};\n this.opts = opts;\n if (!doc.gc) {\n opts.gc = false;\n }\n if (doc.autoLoad) {\n opts.autoLoad = true;\n }\n if (doc.meta !== null) {\n opts.meta = doc.meta;\n }\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.doc]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentDoc}\n */\n copy () {\n return new ContentDoc(this.doc)\n }\n\n /**\n * @param {number} offset\n * @return {ContentDoc}\n */\n splice (offset) {\n throw methodUnimplemented()\n }\n\n /**\n * @param {ContentDoc} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n // this needs to be reflected in doc.destroy as well\n this.doc._item = item;\n transaction.subdocsAdded.add(this.doc);\n if (this.doc.shouldLoad) {\n transaction.subdocsLoaded.add(this.doc);\n }\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n if (transaction.subdocsAdded.has(this.doc)) {\n transaction.subdocsAdded.delete(this.doc);\n } else {\n transaction.subdocsRemoved.add(this.doc);\n }\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) { }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeString(this.doc.guid);\n encoder.writeAny(this.opts);\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 9\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentDoc}\n */\nconst readContentDoc = decoder => new ContentDoc(new Doc({ guid: decoder.readString(), ...decoder.readAny() }));\n\n/**\n * @private\n */\nclass ContentEmbed {\n /**\n * @param {Object} embed\n */\n constructor (embed) {\n this.embed = embed;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.embed]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentEmbed}\n */\n copy () {\n return new ContentEmbed(this.embed)\n }\n\n /**\n * @param {number} offset\n * @return {ContentEmbed}\n */\n splice (offset) {\n throw methodUnimplemented()\n }\n\n /**\n * @param {ContentEmbed} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeJSON(this.embed);\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 5\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentEmbed}\n */\nconst readContentEmbed = decoder => new ContentEmbed(decoder.readJSON());\n\n/**\n * @private\n */\nclass ContentFormat {\n /**\n * @param {string} key\n * @param {Object} value\n */\n constructor (key, value) {\n this.key = key;\n this.value = value;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return []\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return false\n }\n\n /**\n * @return {ContentFormat}\n */\n copy () {\n return new ContentFormat(this.key, this.value)\n }\n\n /**\n * @param {number} offset\n * @return {ContentFormat}\n */\n splice (offset) {\n throw methodUnimplemented()\n }\n\n /**\n * @param {ContentFormat} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n // @todo searchmarker are currently unsupported for rich text documents\n /** @type {AbstractType} */ (item.parent)._searchMarker = null;\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeKey(this.key);\n encoder.writeJSON(this.value);\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 6\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentFormat}\n */\nconst readContentFormat = decoder => new ContentFormat(decoder.readString(), decoder.readJSON());\n\n/**\n * @private\n */\nclass ContentJSON {\n /**\n * @param {Array} arr\n */\n constructor (arr) {\n /**\n * @type {Array}\n */\n this.arr = arr;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.arr.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.arr\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentJSON}\n */\n copy () {\n return new ContentJSON(this.arr)\n }\n\n /**\n * @param {number} offset\n * @return {ContentJSON}\n */\n splice (offset) {\n const right = new ContentJSON(this.arr.slice(offset));\n this.arr = this.arr.slice(0, offset);\n return right\n }\n\n /**\n * @param {ContentJSON} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.arr = this.arr.concat(right.arr);\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n const len = this.arr.length;\n encoder.writeLen(len - offset);\n for (let i = offset; i < len; i++) {\n const c = this.arr[i];\n encoder.writeString(c === undefined ? 'undefined' : JSON.stringify(c));\n }\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 2\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentJSON}\n */\nconst readContentJSON = decoder => {\n const len = decoder.readLen();\n const cs = [];\n for (let i = 0; i < len; i++) {\n const c = decoder.readString();\n if (c === 'undefined') {\n cs.push(undefined);\n } else {\n cs.push(JSON.parse(c));\n }\n }\n return new ContentJSON(cs)\n};\n\nclass ContentAny {\n /**\n * @param {Array} arr\n */\n constructor (arr) {\n /**\n * @type {Array}\n */\n this.arr = arr;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.arr.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.arr\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentAny}\n */\n copy () {\n return new ContentAny(this.arr)\n }\n\n /**\n * @param {number} offset\n * @return {ContentAny}\n */\n splice (offset) {\n const right = new ContentAny(this.arr.slice(offset));\n this.arr = this.arr.slice(0, offset);\n return right\n }\n\n /**\n * @param {ContentAny} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.arr = this.arr.concat(right.arr);\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n const len = this.arr.length;\n encoder.writeLen(len - offset);\n for (let i = offset; i < len; i++) {\n const c = this.arr[i];\n encoder.writeAny(c);\n }\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 8\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentAny}\n */\nconst readContentAny = decoder => {\n const len = decoder.readLen();\n const cs = [];\n for (let i = 0; i < len; i++) {\n cs.push(decoder.readAny());\n }\n return new ContentAny(cs)\n};\n\n/**\n * @private\n */\nclass ContentString {\n /**\n * @param {string} str\n */\n constructor (str) {\n /**\n * @type {string}\n */\n this.str = str;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.str.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.str.split('')\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentString}\n */\n copy () {\n return new ContentString(this.str)\n }\n\n /**\n * @param {number} offset\n * @return {ContentString}\n */\n splice (offset) {\n const right = new ContentString(this.str.slice(offset));\n this.str = this.str.slice(0, offset);\n\n // Prevent encoding invalid documents because of splitting of surrogate pairs: https://github.com/yjs/yjs/issues/248\n const firstCharCode = this.str.charCodeAt(offset - 1);\n if (firstCharCode >= 0xD800 && firstCharCode <= 0xDBFF) {\n // Last character of the left split is the start of a surrogate utf16/ucs2 pair.\n // We don't support splitting of surrogate pairs because this may lead to invalid documents.\n // Replace the invalid character with a unicode replacement character (� / U+FFFD)\n this.str = this.str.slice(0, offset - 1) + '�';\n // replace right as well\n right.str = '�' + right.str.slice(1);\n }\n return right\n }\n\n /**\n * @param {ContentString} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.str += right.str;\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeString(offset === 0 ? this.str : this.str.slice(offset));\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 4\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentString}\n */\nconst readContentString = decoder => new ContentString(decoder.readString());\n\n/**\n * @type {Array>}\n * @private\n */\nconst typeRefs = [\n readYArray,\n readYMap,\n readYText,\n readYXmlElement,\n readYXmlFragment,\n readYXmlHook,\n readYXmlText\n];\n\nconst YArrayRefID = 0;\nconst YMapRefID = 1;\nconst YTextRefID = 2;\nconst YXmlElementRefID = 3;\nconst YXmlFragmentRefID = 4;\nconst YXmlHookRefID = 5;\nconst YXmlTextRefID = 6;\n\n/**\n * @private\n */\nclass ContentType {\n /**\n * @param {AbstractType} type\n */\n constructor (type) {\n /**\n * @type {AbstractType}\n */\n this.type = type;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.type]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentType}\n */\n copy () {\n return new ContentType(this.type._copy())\n }\n\n /**\n * @param {number} offset\n * @return {ContentType}\n */\n splice (offset) {\n throw methodUnimplemented()\n }\n\n /**\n * @param {ContentType} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n this.type._integrate(transaction.doc, item);\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n let item = this.type._start;\n while (item !== null) {\n if (!item.deleted) {\n item.delete(transaction);\n } else {\n // Whis will be gc'd later and we want to merge it if possible\n // We try to merge all deleted items after each transaction,\n // but we have no knowledge about that this needs to be merged\n // since it is not in transaction.ds. Hence we add it to transaction._mergeStructs\n transaction._mergeStructs.push(item);\n }\n item = item.right;\n }\n this.type._map.forEach(item => {\n if (!item.deleted) {\n item.delete(transaction);\n } else {\n // same as above\n transaction._mergeStructs.push(item);\n }\n });\n transaction.changed.delete(this.type);\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) {\n let item = this.type._start;\n while (item !== null) {\n item.gc(store, true);\n item = item.right;\n }\n this.type._start = null;\n this.type._map.forEach(/** @param {Item | null} item */ (item) => {\n while (item !== null) {\n item.gc(store, true);\n item = item.left;\n }\n });\n this.type._map = new Map();\n }\n\n /**\n * @param {AbstractUpdateEncoder} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n this.type._write(encoder);\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 7\n }\n}\n\n/**\n * @private\n *\n * @param {AbstractUpdateDecoder} decoder\n * @return {ContentType}\n */\nconst readContentType = decoder => new ContentType(typeRefs[decoder.readTypeRef()](decoder));\n\n/**\n * @todo This should return several items\n *\n * @param {StructStore} store\n * @param {ID} id\n * @return {{item:Item, diff:number}}\n */\nconst followRedone = (store, id) => {\n /**\n * @type {ID|null}\n */\n let nextID = id;\n let diff = 0;\n let item;\n do {\n if (diff > 0) {\n nextID = createID(nextID.client, nextID.clock + diff);\n }\n item = getItem(store, nextID);\n diff = nextID.clock - item.id.clock;\n nextID = item.redone;\n } while (nextID !== null && item instanceof Item)\n return {\n item, diff\n }\n};\n\n/**\n * Make sure that neither item nor any of its parents is ever deleted.\n *\n * This property does not persist when storing it into a database or when\n * sending it to other peers\n *\n * @param {Item|null} item\n * @param {boolean} keep\n */\nconst keepItem = (item, keep) => {\n while (item !== null && item.keep !== keep) {\n item.keep = keep;\n item = /** @type {AbstractType} */ (item.parent)._item;\n }\n};\n\n/**\n * Split leftItem into two items\n * @param {Transaction} transaction\n * @param {Item} leftItem\n * @param {number} diff\n * @return {Item}\n *\n * @function\n * @private\n */\nconst splitItem = (transaction, leftItem, diff) => {\n // create rightItem\n const { client, clock } = leftItem.id;\n const rightItem = new Item(\n createID(client, clock + diff),\n leftItem,\n createID(client, clock + diff - 1),\n leftItem.right,\n leftItem.rightOrigin,\n leftItem.parent,\n leftItem.parentSub,\n leftItem.content.splice(diff)\n );\n if (leftItem.deleted) {\n rightItem.markDeleted();\n }\n if (leftItem.keep) {\n rightItem.keep = true;\n }\n if (leftItem.redone !== null) {\n rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff);\n }\n // update left (do not set leftItem.rightOrigin as it will lead to problems when syncing)\n leftItem.right = rightItem;\n // update right\n if (rightItem.right !== null) {\n rightItem.right.left = rightItem;\n }\n // right is more specific.\n transaction._mergeStructs.push(rightItem);\n // update parent._map\n if (rightItem.parentSub !== null && rightItem.right === null) {\n /** @type {AbstractType} */ (rightItem.parent)._map.set(rightItem.parentSub, rightItem);\n }\n leftItem.length = diff;\n return rightItem\n};\n\n/**\n * Redoes the effect of this operation.\n *\n * @param {Transaction} transaction The Yjs instance.\n * @param {Item} item\n * @param {Set} redoitems\n *\n * @return {Item|null}\n *\n * @private\n */\nconst redoItem = (transaction, item, redoitems) => {\n const doc = transaction.doc;\n const store = doc.store;\n const ownClientID = doc.clientID;\n const redone = item.redone;\n if (redone !== null) {\n return getItemCleanStart(transaction, redone)\n }\n let parentItem = /** @type {AbstractType} */ (item.parent)._item;\n /**\n * @type {Item|null}\n */\n let left;\n /**\n * @type {Item|null}\n */\n let right;\n if (item.parentSub === null) {\n // Is an array item. Insert at the old position\n left = item.left;\n right = item;\n } else {\n // Is a map item. Insert as current value\n left = item;\n while (left.right !== null) {\n left = left.right;\n if (left.id.client !== ownClientID) {\n // It is not possible to redo this item because it conflicts with a\n // change from another client\n return null\n }\n }\n if (left.right !== null) {\n left = /** @type {Item} */ (/** @type {AbstractType} */ (item.parent)._map.get(item.parentSub));\n }\n right = null;\n }\n // make sure that parent is redone\n if (parentItem !== null && parentItem.deleted === true && parentItem.redone === null) {\n // try to undo parent if it will be undone anyway\n if (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems) === null) {\n return null\n }\n }\n if (parentItem !== null && parentItem.redone !== null) {\n while (parentItem.redone !== null) {\n parentItem = getItemCleanStart(transaction, parentItem.redone);\n }\n // find next cloned_redo items\n while (left !== null) {\n /**\n * @type {Item|null}\n */\n let leftTrace = left;\n // trace redone until parent matches\n while (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item !== parentItem) {\n leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone);\n }\n if (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item === parentItem) {\n left = leftTrace;\n break\n }\n left = left.left;\n }\n while (right !== null) {\n /**\n * @type {Item|null}\n */\n let rightTrace = right;\n // trace redone until parent matches\n while (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item !== parentItem) {\n rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone);\n }\n if (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item === parentItem) {\n right = rightTrace;\n break\n }\n right = right.right;\n }\n }\n const nextClock = getState(store, ownClientID);\n const nextId = createID(ownClientID, nextClock);\n const redoneItem = new Item(\n nextId,\n left, left && left.lastId,\n right, right && right.id,\n parentItem === null ? item.parent : /** @type {ContentType} */ (parentItem.content).type,\n item.parentSub,\n item.content.copy()\n );\n item.redone = nextId;\n keepItem(redoneItem, true);\n redoneItem.integrate(transaction, 0);\n return redoneItem\n};\n\n/**\n * Abstract class that represents any content.\n */\nclass Item extends AbstractStruct {\n /**\n * @param {ID} id\n * @param {Item | null} left\n * @param {ID | null} origin\n * @param {Item | null} right\n * @param {ID | null} rightOrigin\n * @param {AbstractType|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it.\n * @param {string | null} parentSub\n * @param {AbstractContent} content\n */\n constructor (id, left, origin, right, rightOrigin, parent, parentSub, content) {\n super(id, content.getLength());\n /**\n * The item that was originally to the left of this item.\n * @type {ID | null}\n */\n this.origin = origin;\n /**\n * The item that is currently to the left of this item.\n * @type {Item | null}\n */\n this.left = left;\n /**\n * The item that is currently to the right of this item.\n * @type {Item | null}\n */\n this.right = right;\n /**\n * The item that was originally to the right of this item.\n * @type {ID | null}\n */\n this.rightOrigin = rightOrigin;\n /**\n * @type {AbstractType|ID|null}\n */\n this.parent = parent;\n /**\n * If the parent refers to this item with some kind of key (e.g. YMap, the\n * key is specified here. The key is then used to refer to the list in which\n * to insert this item. If `parentSub = null` type._start is the list in\n * which to insert to. Otherwise it is `parent._map`.\n * @type {String | null}\n */\n this.parentSub = parentSub;\n /**\n * If this type's effect is reundone this type refers to the type that undid\n * this operation.\n * @type {ID | null}\n */\n this.redone = null;\n /**\n * @type {AbstractContent}\n */\n this.content = content;\n /**\n * bit1: keep\n * bit2: countable\n * bit3: deleted\n * bit4: mark - mark node as fast-search-marker\n * @type {number} byte\n */\n this.info = this.content.isCountable() ? BIT2 : 0;\n }\n\n /**\n * This is used to mark the item as an indexed fast-search marker\n *\n * @type {boolean}\n */\n set marker (isMarked) {\n if (((this.info & BIT4) > 0) !== isMarked) {\n this.info ^= BIT4;\n }\n }\n\n get marker () {\n return (this.info & BIT4) > 0\n }\n\n /**\n * If true, do not garbage collect this Item.\n */\n get keep () {\n return (this.info & BIT1) > 0\n }\n\n set keep (doKeep) {\n if (this.keep !== doKeep) {\n this.info ^= BIT1;\n }\n }\n\n get countable () {\n return (this.info & BIT2) > 0\n }\n\n /**\n * Whether this item was deleted or not.\n * @type {Boolean}\n */\n get deleted () {\n return (this.info & BIT3) > 0\n }\n\n set deleted (doDelete) {\n if (this.deleted !== doDelete) {\n this.info ^= BIT3;\n }\n }\n\n markDeleted () {\n this.info |= BIT3;\n }\n\n /**\n * Return the creator clientID of the missing op or define missing items and return null.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) {\n return this.origin.client\n }\n if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) {\n return this.rightOrigin.client\n }\n if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) {\n return this.parent.client\n }\n\n // We have all missing ids, now find the items\n\n if (this.origin) {\n this.left = getItemCleanEnd(transaction, store, this.origin);\n this.origin = this.left.lastId;\n }\n if (this.rightOrigin) {\n this.right = getItemCleanStart(transaction, this.rightOrigin);\n this.rightOrigin = this.right.id;\n }\n if ((this.left && this.left.constructor === GC) || (this.right && this.right.constructor === GC)) {\n this.parent = null;\n }\n // only set parent if this shouldn't be garbage collected\n if (!this.parent) {\n if (this.left && this.left.constructor === Item) {\n this.parent = this.left.parent;\n this.parentSub = this.left.parentSub;\n }\n if (this.right && this.right.constructor === Item) {\n this.parent = this.right.parent;\n this.parentSub = this.right.parentSub;\n }\n } else if (this.parent.constructor === ID) {\n const parentItem = getItem(store, this.parent);\n if (parentItem.constructor === GC) {\n this.parent = null;\n } else {\n this.parent = /** @type {ContentType} */ (parentItem.content).type;\n }\n }\n return null\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n if (offset > 0) {\n this.id.clock += offset;\n this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1));\n this.origin = this.left.lastId;\n this.content = this.content.splice(offset);\n this.length -= offset;\n }\n\n if (this.parent) {\n if ((!this.left && (!this.right || this.right.left !== null)) || (this.left && this.left.right !== this.right)) {\n /**\n * @type {Item|null}\n */\n let left = this.left;\n\n /**\n * @type {Item|null}\n */\n let o;\n // set o to the first conflicting item\n if (left !== null) {\n o = left.right;\n } else if (this.parentSub !== null) {\n o = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null;\n while (o !== null && o.left !== null) {\n o = o.left;\n }\n } else {\n o = /** @type {AbstractType} */ (this.parent)._start;\n }\n // TODO: use something like DeleteSet here (a tree implementation would be best)\n // @todo use global set definitions\n /**\n * @type {Set}\n */\n const conflictingItems = new Set();\n /**\n * @type {Set}\n */\n const itemsBeforeOrigin = new Set();\n // Let c in conflictingItems, b in itemsBeforeOrigin\n // ***{origin}bbbb{this}{c,b}{c,b}{o}***\n // Note that conflictingItems is a subset of itemsBeforeOrigin\n while (o !== null && o !== this.right) {\n itemsBeforeOrigin.add(o);\n conflictingItems.add(o);\n if (compareIDs(this.origin, o.origin)) {\n // case 1\n if (o.id.client < this.id.client) {\n left = o;\n conflictingItems.clear();\n } else if (compareIDs(this.rightOrigin, o.rightOrigin)) {\n // this and o are conflicting and point to the same integration points. The id decides which item comes first.\n // Since this is to the left of o, we can break here\n break\n } // else, o might be integrated before an item that this conflicts with. If so, we will find it in the next iterations\n } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) { // use getItem instead of getItemCleanEnd because we don't want / need to split items.\n // case 2\n if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) {\n left = o;\n conflictingItems.clear();\n }\n } else {\n break\n }\n o = o.right;\n }\n this.left = left;\n }\n // reconnect left/right + update parent map/start if necessary\n if (this.left !== null) {\n const right = this.left.right;\n this.right = right;\n this.left.right = this;\n } else {\n let r;\n if (this.parentSub !== null) {\n r = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null;\n while (r !== null && r.left !== null) {\n r = r.left;\n }\n } else {\n r = /** @type {AbstractType} */ (this.parent)._start\n ;/** @type {AbstractType} */ (this.parent)._start = this;\n }\n this.right = r;\n }\n if (this.right !== null) {\n this.right.left = this;\n } else if (this.parentSub !== null) {\n // set as current parent value if right === null and this is parentSub\n /** @type {AbstractType} */ (this.parent)._map.set(this.parentSub, this);\n if (this.left !== null) {\n // this is the current attribute value of parent. delete right\n this.left.delete(transaction);\n }\n }\n // adjust length of parent\n if (this.parentSub === null && this.countable && !this.deleted) {\n /** @type {AbstractType} */ (this.parent)._length += this.length;\n }\n addStruct(transaction.doc.store, this);\n this.content.integrate(transaction, this);\n // add parent to transaction.changed\n addChangedTypeToTransaction(transaction, /** @type {AbstractType} */ (this.parent), this.parentSub);\n if ((/** @type {AbstractType} */ (this.parent)._item !== null && /** @type {AbstractType} */ (this.parent)._item.deleted) || (this.parentSub !== null && this.right !== null)) {\n // delete if parent is deleted or if this is not the current attribute value of parent\n this.delete(transaction);\n }\n } else {\n // parent is not defined. Integrate GC struct instead\n new GC(this.id, this.length).integrate(transaction, 0);\n }\n }\n\n /**\n * Returns the next non-deleted item\n */\n get next () {\n let n = this.right;\n while (n !== null && n.deleted) {\n n = n.right;\n }\n return n\n }\n\n /**\n * Returns the previous non-deleted item\n */\n get prev () {\n let n = this.left;\n while (n !== null && n.deleted) {\n n = n.left;\n }\n return n\n }\n\n /**\n * Computes the last content address of this Item.\n */\n get lastId () {\n // allocating ids is pretty costly because of the amount of ids created, so we try to reuse whenever possible\n return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1)\n }\n\n /**\n * Try to merge two items\n *\n * @param {Item} right\n * @return {boolean}\n */\n mergeWith (right) {\n if (\n compareIDs(right.origin, this.lastId) &&\n this.right === right &&\n compareIDs(this.rightOrigin, right.rightOrigin) &&\n this.id.client === right.id.client &&\n this.id.clock + this.length === right.id.clock &&\n this.deleted === right.deleted &&\n this.redone === null &&\n right.redone === null &&\n this.content.constructor === right.content.constructor &&\n this.content.mergeWith(right.content)\n ) {\n if (right.keep) {\n this.keep = true;\n }\n this.right = right.right;\n if (this.right !== null) {\n this.right.left = this;\n }\n this.length += right.length;\n return true\n }\n return false\n }\n\n /**\n * Mark this Item as deleted.\n *\n * @param {Transaction} transaction\n */\n delete (transaction) {\n if (!this.deleted) {\n const parent = /** @type {AbstractType} */ (this.parent);\n // adjust the length of parent\n if (this.countable && this.parentSub === null) {\n parent._length -= this.length;\n }\n this.markDeleted();\n addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length);\n addChangedTypeToTransaction(transaction, parent, this.parentSub);\n this.content.delete(transaction);\n }\n }\n\n /**\n * @param {StructStore} store\n * @param {boolean} parentGCd\n */\n gc (store, parentGCd) {\n if (!this.deleted) {\n throw unexpectedCase()\n }\n this.content.gc(store);\n if (parentGCd) {\n replaceStruct(store, this, new GC(this.id, this.length));\n } else {\n this.content = new ContentDeleted(this.length);\n }\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {AbstractUpdateEncoder} encoder The encoder to write data to.\n * @param {number} offset\n */\n write (encoder, offset) {\n const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin;\n const rightOrigin = this.rightOrigin;\n const parentSub = this.parentSub;\n const info = (this.content.getRef() & BITS5) |\n (origin === null ? 0 : BIT8) | // origin is defined\n (rightOrigin === null ? 0 : BIT7) | // right origin is defined\n (parentSub === null ? 0 : BIT6); // parentSub is non-null\n encoder.writeInfo(info);\n if (origin !== null) {\n encoder.writeLeftID(origin);\n }\n if (rightOrigin !== null) {\n encoder.writeRightID(rightOrigin);\n }\n if (origin === null && rightOrigin === null) {\n const parent = /** @type {AbstractType} */ (this.parent);\n const parentItem = parent._item;\n if (parentItem === null) {\n // parent type on y._map\n // find the correct key\n const ykey = findRootTypeKey(parent);\n encoder.writeParentInfo(true); // write parentYKey\n encoder.writeString(ykey);\n } else {\n encoder.writeParentInfo(false); // write parent id\n encoder.writeLeftID(parentItem.id);\n }\n if (parentSub !== null) {\n encoder.writeString(parentSub);\n }\n }\n this.content.write(encoder, offset);\n }\n}\n\n/**\n * @param {AbstractUpdateDecoder} decoder\n * @param {number} info\n */\nconst readItemContent = (decoder, info) => contentRefs[info & BITS5](decoder);\n\n/**\n * A lookup map for reading Item content.\n *\n * @type {Array}\n */\nconst contentRefs = [\n () => { throw unexpectedCase() }, // GC is not ItemContent\n readContentDeleted, // 1\n readContentJSON, // 2\n readContentBinary, // 3\n readContentString, // 4\n readContentEmbed, // 5\n readContentFormat, // 6\n readContentType, // 7\n readContentAny, // 8\n readContentDoc // 9\n];\n\nexport { AbstractConnector, AbstractStruct, AbstractType, YArray as Array, ContentAny, ContentBinary, ContentDeleted, ContentEmbed, ContentFormat, ContentJSON, ContentString, ContentType, Doc, GC, ID, Item, YMap as Map, PermanentUserData, RelativePosition, Snapshot, YText as Text, Transaction, UndoManager, YXmlElement as XmlElement, YXmlFragment as XmlFragment, YXmlHook as XmlHook, YXmlText as XmlText, YArrayEvent, YEvent, YMapEvent, YTextEvent, YXmlEvent, applyUpdate, applyUpdateV2, compareIDs, compareRelativePositions, createAbsolutePositionFromRelativePosition, createDeleteSet, createDeleteSetFromStructStore, createDocFromSnapshot, createID, createRelativePositionFromJSON, createRelativePositionFromTypeIndex, createSnapshot, decodeSnapshot, decodeSnapshotV2, decodeStateVector, decodeStateVectorV2, emptySnapshot, encodeSnapshot, encodeSnapshotV2, encodeStateAsUpdate, encodeStateAsUpdateV2, encodeStateVector, encodeStateVectorV2, equalSnapshots, findRootTypeKey, getState, getTypeChildren, isDeleted, isParentOf, iterateDeletedStructs, logType, readRelativePosition, readUpdate, readUpdateV2, snapshot, transact, tryGc, typeListToArraySnapshot, typeMapGetSnapshot, writeRelativePosition };\n//# sourceMappingURL=yjs.mjs.map\n","/* eslint-env browser */\n\n/**\n * Tiny websocket connection handler.\n *\n * Implements exponential backoff reconnects, ping/pong, and a nice event system using [lib0/observable].\n *\n * @module websocket\n */\n\nimport { Observable } from './observable.js'\nimport * as time from './time.js'\nimport * as math from './math.js'\n\nconst reconnectTimeoutBase = 1200\nconst maxReconnectTimeout = 2500\n// @todo - this should depend on awareness.outdatedTime\nconst messageReconnectTimeout = 30000\n\n/**\n * @param {WebsocketClient} wsclient\n */\nconst setupWS = (wsclient) => {\n if (wsclient.shouldConnect && wsclient.ws === null) {\n const websocket = new WebSocket(wsclient.url)\n const binaryType = wsclient.binaryType\n /**\n * @type {any}\n */\n let pingTimeout = null\n if (binaryType) {\n websocket.binaryType = binaryType\n }\n wsclient.ws = websocket\n wsclient.connecting = true\n wsclient.connected = false\n websocket.onmessage = event => {\n wsclient.lastMessageReceived = time.getUnixTime()\n const data = event.data\n const message = typeof data === 'string' ? JSON.parse(data) : data\n if (message && message.type === 'pong') {\n clearTimeout(pingTimeout)\n pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2)\n }\n wsclient.emit('message', [message, wsclient])\n }\n /**\n * @param {any} error\n */\n const onclose = error => {\n if (wsclient.ws !== null) {\n wsclient.ws = null\n wsclient.connecting = false\n if (wsclient.connected) {\n wsclient.connected = false\n wsclient.emit('disconnect', [{ type: 'disconnect', error }, wsclient])\n } else {\n wsclient.unsuccessfulReconnects++\n }\n // Start with no reconnect timeout and increase timeout by\n // log10(wsUnsuccessfulReconnects).\n // The idea is to increase reconnect timeout slowly and have no reconnect\n // timeout at the beginning (log(1) = 0)\n setTimeout(setupWS, math.min(math.log10(wsclient.unsuccessfulReconnects + 1) * reconnectTimeoutBase, maxReconnectTimeout), wsclient)\n }\n clearTimeout(pingTimeout)\n }\n const sendPing = () => {\n if (wsclient.ws === websocket) {\n wsclient.send({\n type: 'ping'\n })\n }\n }\n websocket.onclose = () => onclose(null)\n websocket.onerror = error => onclose(error)\n websocket.onopen = () => {\n wsclient.lastMessageReceived = time.getUnixTime()\n wsclient.connecting = false\n wsclient.connected = true\n wsclient.unsuccessfulReconnects = 0\n wsclient.emit('connect', [{ type: 'connect' }, wsclient])\n // set ping\n pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2)\n }\n }\n}\n\n/**\n * @extends Observable\n */\nexport class WebsocketClient extends Observable {\n /**\n * @param {string} url\n * @param {object} [opts]\n * @param {'arraybuffer' | 'blob' | null} [opts.binaryType] Set `ws.binaryType`\n */\n constructor (url, { binaryType } = {}) {\n super()\n this.url = url\n /**\n * @type {WebSocket?}\n */\n this.ws = null\n this.binaryType = binaryType || null\n this.connected = false\n this.connecting = false\n this.unsuccessfulReconnects = 0\n this.lastMessageReceived = 0\n /**\n * Whether to connect to other peers or not\n * @type {boolean}\n */\n this.shouldConnect = true\n this._checkInterval = setInterval(() => {\n if (this.connected && messageReconnectTimeout < time.getUnixTime() - this.lastMessageReceived) {\n // no message received in a long time - not even your own awareness\n // updates (which are updated every 15 seconds)\n /** @type {WebSocket} */ (this.ws).close()\n }\n }, messageReconnectTimeout / 2)\n setupWS(this)\n }\n\n /**\n * @param {any} message\n */\n send (message) {\n if (this.ws) {\n this.ws.send(JSON.stringify(message))\n }\n }\n\n destroy () {\n clearInterval(this._checkInterval)\n this.disconnect()\n super.destroy()\n }\n\n disconnect () {\n this.shouldConnect = false\n if (this.ws !== null) {\n this.ws.close()\n }\n }\n\n connect () {\n this.shouldConnect = true\n if (!this.connected && this.ws === null) {\n setupWS(this)\n }\n }\n}\n","/**\n * Utility helpers to work with promises.\n *\n * @module promise\n */\n\nimport * as time from './time.js'\n\n/**\n * @template T\n * @callback PromiseResolve\n * @param {T|PromiseLike} [result]\n */\n\n/**\n * @template T\n * @param {function(PromiseResolve,function(Error):void):any} f\n * @return {Promise}\n */\nexport const create = f => new Promise(f)\n\n/**\n * @param {function(function():void,function(Error):void):void} f\n * @return {Promise}\n */\nexport const createEmpty = f => new Promise(f)\n\n/**\n * `Promise.all` wait for all promises in the array to resolve and return the result\n * @template T\n * @param {Array>} arrp\n * @return {Promise>}\n */\nexport const all = arrp => Promise.all(arrp)\n\n/**\n * @param {Error} [reason]\n * @return {Promise}\n */\nexport const reject = reason => Promise.reject(reason)\n\n/**\n * @template T\n * @param {T|void} res\n * @return {Promise}\n */\nexport const resolve = res => Promise.resolve(res)\n\n/**\n * @todo Next version, reorder parameters: check, [timeout, [intervalResolution]]\n *\n * @param {number} timeout\n * @param {function():boolean} check\n * @param {number} [intervalResolution]\n * @return {Promise}\n */\nexport const until = (timeout, check, intervalResolution = 10) => create((resolve, reject) => {\n const startTime = time.getUnixTime()\n const hasTimeout = timeout > 0\n const untilInterval = () => {\n if (check()) {\n clearInterval(intervalHandle)\n resolve()\n } else if (hasTimeout) {\n /* istanbul ignore else */\n if (time.getUnixTime() - startTime > timeout) {\n clearInterval(intervalHandle)\n reject(new Error('Timeout'))\n }\n }\n }\n const intervalHandle = setInterval(untilInterval, intervalResolution)\n})\n\n/**\n * @param {number} timeout\n * @return {Promise}\n */\nexport const wait = timeout => create((resolve, reject) => setTimeout(resolve, timeout))\n\n/**\n * Checks if an object is a promise using ducktyping.\n *\n * Promises are often polyfilled, so it makes sense to add some additional guarantees if the user of this\n * library has some insane environment where global Promise objects are overwritten.\n *\n * @param {any} p\n * @return {boolean}\n */\nexport const isPromise = p => p instanceof Promise || (p && p.then && p.catch && p.finally)\n","/* eslint-env browser */\n\n/**\n * Helpers for cross-tab communication using broadcastchannel with LocalStorage fallback.\n *\n * ```js\n * // In browser window A:\n * broadcastchannel.subscribe('my events', data => console.log(data))\n * broadcastchannel.publish('my events', 'Hello world!') // => A: 'Hello world!' fires synchronously in same tab\n *\n * // In browser window B:\n * broadcastchannel.publish('my events', 'hello from tab B') // => A: 'hello from tab B'\n * ```\n *\n * @module broadcastchannel\n */\n\n// @todo before next major: use Uint8Array instead as buffer object\n\nimport * as map from './map.js'\nimport * as buffer from './buffer.js'\nimport * as storage from './storage.js'\n\n/**\n * @typedef {Object} Channel\n * @property {Set} Channel.subs\n * @property {any} Channel.bc\n */\n\n/**\n * @type {Map}\n */\nconst channels = new Map()\n\nclass LocalStoragePolyfill {\n /**\n * @param {string} room\n */\n constructor (room) {\n this.room = room\n /**\n * @type {null|function({data:ArrayBuffer}):void}\n */\n this.onmessage = null\n addEventListener('storage', e => e.key === room && this.onmessage !== null && this.onmessage({ data: buffer.fromBase64(e.newValue || '') }))\n }\n\n /**\n * @param {ArrayBuffer} buf\n */\n postMessage (buf) {\n storage.varStorage.setItem(this.room, buffer.toBase64(buffer.createUint8ArrayFromArrayBuffer(buf)))\n }\n}\n\n// Use BroadcastChannel or Polyfill\nconst BC = typeof BroadcastChannel === 'undefined' ? LocalStoragePolyfill : BroadcastChannel\n\n/**\n * @param {string} room\n * @return {Channel}\n */\nconst getChannel = room =>\n map.setIfUndefined(channels, room, () => {\n const subs = new Set()\n const bc = new BC(room)\n /**\n * @param {{data:ArrayBuffer}} e\n */\n bc.onmessage = e => subs.forEach(sub => sub(e.data))\n return {\n bc, subs\n }\n })\n\n/**\n * Subscribe to global `publish` events.\n *\n * @function\n * @param {string} room\n * @param {function(any):any} f\n */\nexport const subscribe = (room, f) => getChannel(room).subs.add(f)\n\n/**\n * Unsubscribe from `publish` global events.\n *\n * @function\n * @param {string} room\n * @param {function(any):any} f\n */\nexport const unsubscribe = (room, f) => getChannel(room).subs.delete(f)\n\n/**\n * Publish data to all subscribers (including subscribers on this tab)\n *\n * @function\n * @param {string} room\n * @param {any} data\n */\nexport const publish = (room, data) => {\n const c = getChannel(room)\n c.bc.postMessage(data)\n c.subs.forEach(sub => sub(data))\n}\n","/**\n * Mutual exclude for JavaScript.\n *\n * @module mutex\n */\n\n/**\n * @callback mutex\n * @param {function():void} cb Only executed when this mutex is not in the current stack\n * @param {function():void} [elseCb] Executed when this mutex is in the current stack\n */\n\n/**\n * Creates a mutual exclude function with the following property:\n *\n * ```js\n * const mutex = createMutex()\n * mutex(() => {\n * // This function is immediately executed\n * mutex(() => {\n * // This function is not executed, as the mutex is already active.\n * })\n * })\n * ```\n *\n * @return {mutex} A mutual exclude function\n * @public\n */\nexport const createMutex = () => {\n let token = true\n return (f, g) => {\n if (token) {\n token = false\n try {\n f()\n } finally {\n token = true\n }\n } else if (g !== undefined) {\n g()\n }\n }\n}\n","(function(e){if(\"object\"==typeof exports&&\"undefined\"!=typeof module)module.exports=e();else if(\"function\"==typeof define&&define.amd)define([],e);else{var t;t=\"undefined\"==typeof window?\"undefined\"==typeof global?\"undefined\"==typeof self?this:self:global:window,t.SimplePeer=e()}})(function(){var t=Math.floor,n=Math.abs,r=Math.pow;return function(){function d(s,e,n){function t(o,i){if(!e[o]){if(!s[o]){var l=\"function\"==typeof require&&require;if(!i&&l)return l(o,!0);if(r)return r(o,!0);var c=new Error(\"Cannot find module '\"+o+\"'\");throw c.code=\"MODULE_NOT_FOUND\",c}var a=e[o]={exports:{}};s[o][0].call(a.exports,function(e){var r=s[o][1][e];return t(r||e)},a,a.exports,d,s,e,n)}return e[o].exports}for(var r=\"function\"==typeof require&&require,a=0;a>16,l[c++]=255&t>>8,l[c++]=255&t;return 2===s&&(t=u[e.charCodeAt(n)]<<2|u[e.charCodeAt(n+1)]>>4,l[c++]=255&t),1===s&&(t=u[e.charCodeAt(n)]<<10|u[e.charCodeAt(n+1)]<<4|u[e.charCodeAt(n+2)]>>2,l[c++]=255&t>>8,l[c++]=255&t),l}function d(e){return c[63&e>>18]+c[63&e>>12]+c[63&e>>6]+c[63&e]}function s(e,t,n){for(var r,a=[],o=t;ol?l:d+o));return 1===r?(t=e[n-1],a.push(c[t>>2]+c[63&t<<4]+\"==\")):2===r&&(t=(e[n-2]<<8)+e[n-1],a.push(c[t>>10]+c[63&t>>4]+c[63&t<<2]+\"=\")),a.join(\"\")}n.byteLength=function(e){var t=r(e),n=t[0],a=t[1];return 3*(n+a)/4-a},n.toByteArray=o,n.fromByteArray=l;for(var c=[],u=[],p=\"undefined\"==typeof Uint8Array?Array:Uint8Array,f=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\",g=0,h=f.length;g\n * @license MIT\n */'use strict';var z=String.fromCharCode,K=Math.min;function a(e){if(2147483647e)throw new RangeError(\"The value \\\"\"+e+\"\\\" is invalid for option \\\"size\\\"\")}function d(e,t,n){return i(e),0>=e?a(e):void 0===t?a(e):\"string\"==typeof n?a(e).fill(t,n):a(e).fill(t)}function s(e){return i(e),a(0>e?0:0|f(e))}function l(e,n){if((\"string\"!=typeof n||\"\"===n)&&(n=\"utf8\"),!t.isEncoding(n))throw new TypeError(\"Unknown encoding: \"+n);var r=0|h(e,n),o=a(r),i=o.write(e,n);return i!==r&&(o=o.slice(0,i)),o}function c(e){for(var t=0>e.length?0:0|f(e.length),n=a(t),r=0;rn||e.byteLength=2147483647)throw new RangeError(\"Attempt to allocate Buffer larger than maximum size: 0x\"+2147483647 .toString(16)+\" bytes\");return 0|e}function g(e){return+e!=e&&(e=0),t.alloc(+e)}function h(e,n){if(t.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||G(e,ArrayBuffer))return e.byteLength;if(\"string\"!=typeof e)throw new TypeError(\"The \\\"string\\\" argument must be one of type string, Buffer, or ArrayBuffer. Received type \"+typeof e);var r=e.length,a=2>>1;case\"base64\":return H(e).length;default:if(o)return a?-1:j(e).length;n=(\"\"+n).toLowerCase(),o=!0;}}function _(e,t,n){var r=!1;if((void 0===t||0>t)&&(t=0),t>this.length)return\"\";if((void 0===n||n>this.length)&&(n=this.length),0>=n)return\"\";if(n>>>=0,t>>>=0,n<=t)return\"\";for(e||(e=\"utf8\");;)switch(e){case\"hex\":return N(this,t,n);case\"utf8\":case\"utf-8\":return v(this,t,n);case\"ascii\":return A(this,t,n);case\"latin1\":case\"binary\":return x(this,t,n);case\"base64\":return T(this,t,n);case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return I(this,t,n);default:if(r)throw new TypeError(\"Unknown encoding: \"+e);e=(e+\"\").toLowerCase(),r=!0;}}function m(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function b(e,n,r,a,o){if(0===e.length)return-1;if(\"string\"==typeof r?(a=r,r=0):2147483647r&&(r=-2147483648),r=+r,Y(r)&&(r=o?0:e.length-1),0>r&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(0>r)if(o)r=0;else return-1;if(\"string\"==typeof n&&(n=t.from(n,a)),t.isBuffer(n))return 0===n.length?-1:y(e,n,r,a,o);if(\"number\"==typeof n)return n&=255,\"function\"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,n,r):Uint8Array.prototype.lastIndexOf.call(e,n,r):y(e,[n],r,a,o);throw new TypeError(\"val must be string, number or Buffer\")}function y(e,t,n,r,a){function o(e,t){return 1===d?e[t]:e.readUInt16BE(t*d)}var d=1,s=e.length,l=t.length;if(void 0!==r&&(r=(r+\"\").toLowerCase(),\"ucs2\"===r||\"ucs-2\"===r||\"utf16le\"===r||\"utf-16le\"===r)){if(2>e.length||2>t.length)return-1;d=2,s/=2,l/=2,n/=2}var c;if(a){var u=-1;for(c=n;cs&&(n=s-l),c=n;0<=c;c--){for(var p=!0,f=0;fa&&(r=a)):r=a;var o=t.length;r>o/2&&(r=o/2);for(var d,s=0;so&&(d=o):2===s?(l=e[a+1],128==(192&l)&&(p=(31&o)<<6|63&l,127p||57343p&&(d=p))):void 0}null===d?(d=65533,s=1):65535>>10),d=56320|1023&d),r.push(d),a+=s}return L(r)}function L(e){var t=e.length;if(t<=4096)return z.apply(String,e);for(var n=\"\",r=0;rt)&&(t=0),(!n||0>n||n>r)&&(n=r);for(var a=\"\",o=t;oe)throw new RangeError(\"offset is not uint\");if(e+t>n)throw new RangeError(\"Trying to access beyond buffer length\")}function P(e,n,r,a,o,i){if(!t.isBuffer(e))throw new TypeError(\"\\\"buffer\\\" argument must be a Buffer instance\");if(n>o||ne.length)throw new RangeError(\"Index out of range\")}function D(e,t,n,r){if(n+r>e.length)throw new RangeError(\"Index out of range\");if(0>n)throw new RangeError(\"Index out of range\")}function F(e,t,n,r,a){return t=+t,n>>>=0,a||D(e,t,n,4,34028234663852886e22,-34028234663852886e22),$.write(e,t,n,r,23,4),n+4}function B(e,t,n,r,a){return t=+t,n>>>=0,a||D(e,t,n,8,17976931348623157e292,-17976931348623157e292),$.write(e,t,n,r,52,8),n+8}function O(e){if(e=e.split(\"=\")[0],e=e.trim().replace(J,\"\"),2>e.length)return\"\";for(;0!=e.length%4;)e+=\"=\";return e}function U(e){return 16>e?\"0\"+e.toString(16):e.toString(16)}function j(e,t){t=t||1/0;for(var n,r=e.length,a=null,o=[],d=0;dn){if(!a){if(56319n){-1<(t-=3)&&o.push(239,191,189),a=n;continue}n=(a-55296<<10|n-56320)+65536}else a&&-1<(t-=3)&&o.push(239,191,189);if(a=null,128>n){if(0>(t-=1))break;o.push(n)}else if(2048>n){if(0>(t-=2))break;o.push(192|n>>6,128|63&n)}else if(65536>n){if(0>(t-=3))break;o.push(224|n>>12,128|63&n>>6,128|63&n)}else if(1114112>n){if(0>(t-=4))break;o.push(240|n>>18,128|63&n>>12,128|63&n>>6,128|63&n)}else throw new Error(\"Invalid code point\")}return o}function q(e){for(var t=[],n=0;n(t-=2));++d)n=e.charCodeAt(d),r=n>>8,a=n%256,o.push(a),o.push(r);return o}function H(e){return X.toByteArray(O(e))}function V(e,t,n,r){for(var a=0;a=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function G(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!==e}var X=e(\"base64-js\"),$=e(\"ieee754\");n.Buffer=t,n.SlowBuffer=g,n.INSPECT_MAX_BYTES=50;n.kMaxLength=2147483647,t.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(t){return!1}}(),t.TYPED_ARRAY_SUPPORT||\"undefined\"==typeof console||\"function\"!=typeof console.error||console.error(\"This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.\"),Object.defineProperty(t.prototype,\"parent\",{enumerable:!0,get:function(){return t.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(t.prototype,\"offset\",{enumerable:!0,get:function(){return t.isBuffer(this)?this.byteOffset:void 0}}),\"undefined\"!=typeof Symbol&&null!=Symbol.species&&t[Symbol.species]===t&&Object.defineProperty(t,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),t.poolSize=8192,t.from=function(e,t,n){return o(e,t,n)},t.prototype.__proto__=Uint8Array.prototype,t.__proto__=Uint8Array,t.alloc=function(e,t,n){return d(e,t,n)},t.allocUnsafe=function(e){return s(e)},t.allocUnsafeSlow=function(e){return s(e)},t.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==t.prototype},t.compare=function(e,n){if(G(e,Uint8Array)&&(e=t.from(e,e.offset,e.byteLength)),G(n,Uint8Array)&&(n=t.from(n,n.offset,n.byteLength)),!t.isBuffer(e)||!t.isBuffer(n))throw new TypeError(\"The \\\"buf1\\\", \\\"buf2\\\" arguments must be one of type Buffer or Uint8Array\");if(e===n)return 0;for(var r=e.length,o=n.length,d=0,s=K(r,o);dt&&(e+=\" ... \"),\"\"},t.prototype.compare=function(e,n,r,a,o){if(G(e,Uint8Array)&&(e=t.from(e,e.offset,e.byteLength)),!t.isBuffer(e))throw new TypeError(\"The \\\"target\\\" argument must be one of type Buffer or Uint8Array. Received type \"+typeof e);if(void 0===n&&(n=0),void 0===r&&(r=e?e.length:0),void 0===a&&(a=0),void 0===o&&(o=this.length),0>n||r>e.length||0>a||o>this.length)throw new RangeError(\"out of range index\");if(a>=o&&n>=r)return 0;if(a>=o)return-1;if(n>=r)return 1;if(n>>>=0,r>>>=0,a>>>=0,o>>>=0,this===e)return 0;for(var d=o-a,s=r-n,l=K(d,s),c=this.slice(a,o),u=e.slice(n,r),p=0;p>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r=\"utf8\")):(r=n,n=void 0);else throw new Error(\"Buffer.write(string, encoding, offset[, length]) is no longer supported\");var a=this.length-t;if((void 0===n||n>a)&&(n=a),0n||0>t)||t>this.length)throw new RangeError(\"Attempt to write outside buffer bounds\");r||(r=\"utf8\");for(var o=!1;;)switch(r){case\"hex\":return C(this,e,t,n);case\"utf8\":case\"utf-8\":return w(this,e,t,n);case\"ascii\":return R(this,e,t,n);case\"latin1\":case\"binary\":return E(this,e,t,n);case\"base64\":return S(this,e,t,n);case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return k(this,e,t,n);default:if(o)throw new TypeError(\"Unknown encoding: \"+r);r=(\"\"+r).toLowerCase(),o=!0;}},t.prototype.toJSON=function(){return{type:\"Buffer\",data:Array.prototype.slice.call(this._arr||this,0)}};t.prototype.slice=function(e,n){var r=this.length;e=~~e,n=void 0===n?r:~~n,0>e?(e+=r,0>e&&(e=0)):e>r&&(e=r),0>n?(n+=r,0>n&&(n=0)):n>r&&(n=r),n>>=0,t>>>=0,n||M(e,t,this.length);for(var r=this[e],a=1,o=0;++o>>=0,t>>>=0,n||M(e,t,this.length);for(var r=this[e+--t],a=1;0>>=0,t||M(e,1,this.length),this[e]},t.prototype.readUInt16LE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]|this[e+1]<<8},t.prototype.readUInt16BE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]<<8|this[e+1]},t.prototype.readUInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},t.prototype.readUInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},t.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);for(var a=this[e],o=1,d=0;++d=o&&(a-=r(2,8*t)),a},t.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);for(var a=t,o=1,d=this[e+--a];0=o&&(d-=r(2,8*t)),d},t.prototype.readInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},t.prototype.readInt16LE=function(e,t){e>>>=0,t||M(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt16BE=function(e,t){e>>>=0,t||M(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},t.prototype.readInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},t.prototype.readFloatLE=function(e,t){return e>>>=0,t||M(e,4,this.length),$.read(this,e,!0,23,4)},t.prototype.readFloatBE=function(e,t){return e>>>=0,t||M(e,4,this.length),$.read(this,e,!1,23,4)},t.prototype.readDoubleLE=function(e,t){return e>>>=0,t||M(e,8,this.length),$.read(this,e,!0,52,8)},t.prototype.readDoubleBE=function(e,t){return e>>>=0,t||M(e,8,this.length),$.read(this,e,!1,52,8)},t.prototype.writeUIntLE=function(e,t,n,a){if(e=+e,t>>>=0,n>>>=0,!a){var o=r(2,8*n)-1;P(this,e,t,n,o,0)}var d=1,s=0;for(this[t]=255&e;++s>>=0,n>>>=0,!a){var o=r(2,8*n)-1;P(this,e,t,n,o,0)}var d=n-1,s=1;for(this[t+d]=255&e;0<=--d&&(s*=256);)this[t+d]=255&e/s;return t+n},t.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,1,255,0),this[t]=255&e,t+1},t.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},t.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeIntLE=function(e,t,n,a){if(e=+e,t>>>=0,!a){var o=r(2,8*n-1);P(this,e,t,n,o-1,-o)}var d=0,s=1,l=0;for(this[t]=255&e;++de&&0===l&&0!==this[t+d-1]&&(l=1),this[t+d]=255&(e/s>>0)-l;return t+n},t.prototype.writeIntBE=function(e,t,n,a){if(e=+e,t>>>=0,!a){var o=r(2,8*n-1);P(this,e,t,n,o-1,-o)}var d=n-1,s=1,l=0;for(this[t+d]=255&e;0<=--d&&(s*=256);)0>e&&0===l&&0!==this[t+d+1]&&(l=1),this[t+d]=255&(e/s>>0)-l;return t+n},t.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,1,127,-128),0>e&&(e=255+e+1),this[t]=255&e,t+1},t.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},t.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,2147483647,-2147483648),0>e&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeFloatLE=function(e,t,n){return F(this,e,t,!0,n)},t.prototype.writeFloatBE=function(e,t,n){return F(this,e,t,!1,n)},t.prototype.writeDoubleLE=function(e,t,n){return B(this,e,t,!0,n)},t.prototype.writeDoubleBE=function(e,t,n){return B(this,e,t,!1,n)},t.prototype.copy=function(e,n,r,a){if(!t.isBuffer(e))throw new TypeError(\"argument should be a Buffer\");if(r||(r=0),a||0===a||(a=this.length),n>=e.length&&(n=e.length),n||(n=0),0n)throw new RangeError(\"targetStart out of bounds\");if(0>r||r>=this.length)throw new RangeError(\"Index out of range\");if(0>a)throw new RangeError(\"sourceEnd out of bounds\");a>this.length&&(a=this.length),e.length-no||\"latin1\"===a)&&(e=o)}}else\"number\"==typeof e&&(e&=255);if(0>n||this.length>>=0,r=r===void 0?this.length:r>>>0,e||(e=0);var d;if(\"number\"==typeof e)for(d=n;d{\"%%\"===e||(r++,\"%c\"===e&&(a=r))}),e.splice(a,0,n)},n.save=function(e){try{e?n.storage.setItem(\"debug\",e):n.storage.removeItem(\"debug\")}catch(e){}},n.load=o,n.useColors=function(){return!!(\"undefined\"!=typeof window&&window.process&&(\"renderer\"===window.process.type||window.process.__nwjs))||!(\"undefined\"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/))&&(\"undefined\"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||\"undefined\"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||\"undefined\"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)&&31<=parseInt(RegExp.$1,10)||\"undefined\"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/))},n.storage=function(){try{return localStorage}catch(e){}}(),n.colors=[\"#0000CC\",\"#0000FF\",\"#0033CC\",\"#0033FF\",\"#0066CC\",\"#0066FF\",\"#0099CC\",\"#0099FF\",\"#00CC00\",\"#00CC33\",\"#00CC66\",\"#00CC99\",\"#00CCCC\",\"#00CCFF\",\"#3300CC\",\"#3300FF\",\"#3333CC\",\"#3333FF\",\"#3366CC\",\"#3366FF\",\"#3399CC\",\"#3399FF\",\"#33CC00\",\"#33CC33\",\"#33CC66\",\"#33CC99\",\"#33CCCC\",\"#33CCFF\",\"#6600CC\",\"#6600FF\",\"#6633CC\",\"#6633FF\",\"#66CC00\",\"#66CC33\",\"#9900CC\",\"#9900FF\",\"#9933CC\",\"#9933FF\",\"#99CC00\",\"#99CC33\",\"#CC0000\",\"#CC0033\",\"#CC0066\",\"#CC0099\",\"#CC00CC\",\"#CC00FF\",\"#CC3300\",\"#CC3333\",\"#CC3366\",\"#CC3399\",\"#CC33CC\",\"#CC33FF\",\"#CC6600\",\"#CC6633\",\"#CC9900\",\"#CC9933\",\"#CCCC00\",\"#CCCC33\",\"#FF0000\",\"#FF0033\",\"#FF0066\",\"#FF0099\",\"#FF00CC\",\"#FF00FF\",\"#FF3300\",\"#FF3333\",\"#FF3366\",\"#FF3399\",\"#FF33CC\",\"#FF33FF\",\"#FF6600\",\"#FF6633\",\"#FF9900\",\"#FF9933\",\"#FFCC00\",\"#FFCC33\"],t.exports=e(\"./common\")(n);const{formatters:i}=t.exports;i.j=function(e){try{return JSON.stringify(e)}catch(e){return\"[UnexpectedJSONParseError]: \"+e.message}}}).call(this,e(\"_process\"))},{\"./common\":5,_process:11}],5:[function(e,t){t.exports=function(t){function r(e){let t=0;for(let n=0;n{if(\"%%\"===t)return t;d++;const o=a.formatters[n];if(\"function\"==typeof o){const n=e[d];t=o.call(r,n),e.splice(d,1),d--}return t}),a.formatArgs.call(r,e);const s=r.log||a.log;s.apply(r,e)}let n;return t.namespace=e,t.enabled=a.enabled(e),t.useColors=a.useColors(),t.color=r(e),t.destroy=o,t.extend=i,\"function\"==typeof a.init&&a.init(t),a.instances.push(t),t}function o(){const e=a.instances.indexOf(this);return-1!==e&&(a.instances.splice(e,1),!0)}function i(e,t){const n=a(this.namespace+(\"undefined\"==typeof t?\":\":t)+e);return n.log=this.log,n}function d(e){return e.toString().substring(2,e.toString().length-2).replace(/\\.\\*\\?$/,\"*\")}return a.debug=a,a.default=a,a.coerce=function(e){return e instanceof Error?e.stack||e.message:e},a.disable=function(){const e=[...a.names.map(d),...a.skips.map(d).map(e=>\"-\"+e)].join(\",\");return a.enable(\"\"),e},a.enable=function(e){a.save(e),a.names=[],a.skips=[];let t;const n=(\"string\"==typeof e?e:\"\").split(/[\\s,]+/),r=n.length;for(t=0;t{a[e]=t[e]}),a.instances=[],a.names=[],a.skips=[],a.formatters={},a.selectColor=r,a.enable(a.load()),a}},{ms:10}],6:[function(e,t){function n(){this._events&&Object.prototype.hasOwnProperty.call(this,\"_events\")||(this._events=y(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}function r(e){return void 0===e._maxListeners?n.defaultMaxListeners:e._maxListeners}function a(e,t,n){if(t)e.call(n);else for(var r=e.length,a=m(e,r),o=0;oo)){d.warned=!0;var s=new Error(\"Possible EventEmitter memory leak detected. \"+d.length+\" \\\"\"+(t+\"\\\" listeners added. Use emitter.setMaxListeners() to increase limit.\"));s.name=\"MaxListenersExceededWarning\",s.emitter=e,s.type=t,s.count=d.length,\"object\"==typeof console&&console.warn&&console.warn(\"%s: %s\",s.name,s.message)}return e}function p(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=Array(arguments.length),t=0;te||e!==e)throw new TypeError(\"\\\"defaultMaxListeners\\\" must be a positive number\");E=e}}):n.defaultMaxListeners=E,n.prototype.setMaxListeners=function(e){if(\"number\"!=typeof e||0>e||isNaN(e))throw new TypeError(\"\\\"n\\\" argument must be a positive number\");return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return r(this)},n.prototype.emit=function(e){var t,n,r,o,u,p,f=\"error\"===e;if(p=this._events,p)f=f&&null==p.error;else if(!f)return!1;if(f){if(1a)return this;0===a?n.shift():_(n,a),1===n.length&&(r[e]=n[0]),r.removeListener&&this.emit(\"removeListener\",e,d||t)}return this},n.prototype.removeAllListeners=function(e){var t,n,r;if(n=this._events,!n)return this;if(!n.removeListener)return 0===arguments.length?(this._events=y(null),this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=y(null):delete n[e]),this;if(0===arguments.length){var a,o=C(n);for(r=0;r>1,h=-7,_=a?l-1:0,b=a?-1:1,d=t[n+_];for(_+=b,c=d&(1<<-h)-1,d>>=-h,h+=p;0>=-h,h+=o;0>1,E=23===p?r(2,-24)-r(2,-77):0,S=u?0:f-1,k=u?1:-1,d=0>o||0===o&&0>1/o?1:0;for(o=n(o),isNaN(o)||o===1/0?(b=isNaN(o)?1:0,_=w):(_=t(h(o)/g),1>o*(y=r(2,-_))&&(_--,y*=2),o+=1<=_+R?E/y:E*r(2,1-R),2<=o*y&&(_++,y/=2),_+R>=w?(b=0,_=w):1<=_+R?(b=(o*y-1)*r(2,p),_+=R):(b=o*r(2,R-1)*r(2,p),_=0));8<=p;a[l+S]=255&b,S+=k,b/=256,p-=8);for(_=_<=1.5*r?\"s\":\"\")}var l=24*(60*60000);t.exports=function(e,t){t=t||{};var n=typeof e;if(\"string\"==n&&0(n||(n=Promise.resolve())).then(e).catch(e=>setTimeout(()=>{throw e},0))},{}],13:[function(e,t){(function(n,r){'use strict';var a=e(\"safe-buffer\").Buffer,o=r.crypto||r.msCrypto;t.exports=o&&o.getRandomValues?function(e,t){if(e>4294967295)throw new RangeError(\"requested too many random bytes\");var r=a.allocUnsafe(e);if(0n?0:+n,t.length)===t}function i(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function d(e,t,n){return\"number\"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}var s={};r(\"ERR_INVALID_OPT_VALUE\",function(e,t){return\"The value \\\"\"+t+\"\\\" is invalid for option \\\"\"+e+\"\\\"\"},TypeError),r(\"ERR_INVALID_ARG_TYPE\",function(e,t,n){var r;\"string\"==typeof t&&o(t,\"not \")?(r=\"must not be\",t=t.replace(/^not /,\"\")):r=\"must be\";var s;if(i(e,\" argument\"))s=\"The \".concat(e,\" \").concat(r,\" \").concat(a(t,\"type\"));else{var l=d(e,\".\")?\"property\":\"argument\";s=\"The \\\"\".concat(e,\"\\\" \").concat(l,\" \").concat(r,\" \").concat(a(t,\"type\"))}return s+=\". Received type \".concat(typeof n),s},TypeError),r(\"ERR_STREAM_PUSH_AFTER_EOF\",\"stream.push() after EOF\"),r(\"ERR_METHOD_NOT_IMPLEMENTED\",function(e){return\"The \"+e+\" method is not implemented\"}),r(\"ERR_STREAM_PREMATURE_CLOSE\",\"Premature close\"),r(\"ERR_STREAM_DESTROYED\",function(e){return\"Cannot call \"+e+\" after a stream was destroyed\"}),r(\"ERR_MULTIPLE_CALLBACK\",\"Callback called multiple times\"),r(\"ERR_STREAM_CANNOT_PIPE\",\"Cannot pipe, not readable\"),r(\"ERR_STREAM_WRITE_AFTER_END\",\"write after end\"),r(\"ERR_STREAM_NULL_VALUES\",\"May not write null values to stream\",TypeError),r(\"ERR_UNKNOWN_ENCODING\",function(e){return\"Unknown encoding: \"+e},TypeError),r(\"ERR_STREAM_UNSHIFT_AFTER_END_EVENT\",\"stream.unshift() after end event\"),t.exports.codes=s},{}],15:[function(e,t){(function(n){'use strict';function r(e){return this instanceof r?void(d.call(this,e),s.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once(\"end\",a)))):new r(e)}function a(){this._writableState.ended||n.nextTick(o,this)}function o(e){e.end()}var i=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=r;var d=e(\"./_stream_readable\"),s=e(\"./_stream_writable\");e(\"inherits\")(r,d);for(var l,c=i(s.prototype),u=0;u>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function f(e,t){return 0>=e||0===t.length&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=p(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}function g(e,t){if(x(\"onEofChunk\"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?h(e):(t.needReadable=!1,!t.emittedReadable&&(t.emittedReadable=!0,_(e)))}}function h(e){var t=e._readableState;x(\"emitReadable\",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(x(\"emitReadable\",t.flowing),t.emittedReadable=!0,n.nextTick(_,e))}function _(e){var t=e._readableState;x(\"emitReadable_\",t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit(\"readable\"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,S(e)}function m(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(b,e,t))}function b(e,t){for(;!t.reading&&!t.ended&&(t.length=t.length?(n=t.decoder?t.buffer.join(\"\"):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function T(e){var t=e._readableState;x(\"endReadable\",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(v,t,e))}function v(e,t){if(x(\"endReadableNT\",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit(\"end\"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function L(e,t){for(var n=0,r=e.length;n=t.highWaterMark)||t.ended))return x(\"read: emitReadable\",t.length,t.ended),0===t.length&&t.ended?T(this):h(this),null;if(e=f(e,t),0===e&&t.ended)return 0===t.length&&T(this),null;var a=t.needReadable;x(\"need readable\",a),(0===t.length||t.length-e>>0),n=this.head,r=0;n;)s(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:\"consume\",value:function(e,t){var n;return eo.length?o.length:e;if(a+=i===o.length?o:o.slice(0,e),e-=i,0===e){i===o.length?(++r,this.head=t.next?t.next:this.tail=null):(this.head=t,t.data=o.slice(i));break}++r}return this.length-=r,a}},{key:\"_getBuffer\",value:function(e){var t=u.allocUnsafe(e),r=this.head,a=1;for(r.data.copy(t),e-=r.data.length;r=r.next;){var o=r.data,i=e>o.length?o.length:e;if(o.copy(t,t.length-e,0,i),e-=i,0===e){i===o.length?(++a,this.head=r.next?r.next:this.tail=null):(this.head=r,r.data=o.slice(i));break}++a}return this.length-=a,t}},{key:g,value:function(e,t){return f(this,r({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:3,util:2}],22:[function(e,t){(function(e){'use strict';function n(e,t){a(e,t),r(e)}function r(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit(\"close\")}function a(e,t){e.emit(\"error\",t)}t.exports={destroy:function(t,o){var i=this,d=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return d||s?(o?o(t):t&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,e.nextTick(a,this,t)):e.nextTick(a,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!o&&t?i._writableState?i._writableState.errorEmitted?e.nextTick(r,i):(i._writableState.errorEmitted=!0,e.nextTick(n,i,t)):e.nextTick(n,i,t):o?(e.nextTick(r,i),o(t)):e.nextTick(r,i)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit(\"error\",t)}}}).call(this,e(\"_process\"))},{_process:11}],23:[function(e,t){'use strict';function n(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=Array(n),a=0;at.length)throw new u(\"streams\");var a,l=t.map(function(e,n){var d=nd){var s=i?o:\"highWaterMark\";throw new a(s,d)}return t(d)}return e.objectMode?16:16384}}},{\"../../../errors\":14}],27:[function(e,t){t.exports=e(\"events\").EventEmitter},{events:6}],28:[function(e,t,n){n=t.exports=e(\"./lib/_stream_readable.js\"),n.Stream=n,n.Readable=n,n.Writable=e(\"./lib/_stream_writable.js\"),n.Duplex=e(\"./lib/_stream_duplex.js\"),n.Transform=e(\"./lib/_stream_transform.js\"),n.PassThrough=e(\"./lib/_stream_passthrough.js\"),n.finished=e(\"./lib/internal/streams/end-of-stream.js\"),n.pipeline=e(\"./lib/internal/streams/pipeline.js\")},{\"./lib/_stream_duplex.js\":15,\"./lib/_stream_passthrough.js\":16,\"./lib/_stream_readable.js\":17,\"./lib/_stream_transform.js\":18,\"./lib/_stream_writable.js\":19,\"./lib/internal/streams/end-of-stream.js\":23,\"./lib/internal/streams/pipeline.js\":25}],29:[function(e,t,n){function r(e,t){for(var n in e)t[n]=e[n]}function a(e,t,n){return i(e,t,n)}/*! safe-buffer. MIT License. Feross Aboukhadijeh */var o=e(\"buffer\"),i=o.Buffer;i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=o:(r(o,n),n.Buffer=a),a.prototype=Object.create(i.prototype),r(i,a),a.from=function(e,t,n){if(\"number\"==typeof e)throw new TypeError(\"Argument must not be a number\");return i(e,t,n)},a.alloc=function(e,t,n){if(\"number\"!=typeof e)throw new TypeError(\"Argument must be a number\");var r=i(e);return void 0===t?r.fill(0):\"string\"==typeof n?r.fill(t,n):r.fill(t),r},a.allocUnsafe=function(e){if(\"number\"!=typeof e)throw new TypeError(\"Argument must be a number\");return i(e)},a.allocUnsafeSlow=function(e){if(\"number\"!=typeof e)throw new TypeError(\"Argument must be a number\");return o.SlowBuffer(e)}},{buffer:3}],30:[function(e,t,n){'use strict';function r(e){if(!e)return\"utf8\";for(var t;;)switch(e){case\"utf8\":case\"utf-8\":return\"utf8\";case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return\"utf16le\";case\"latin1\":case\"binary\":return\"latin1\";case\"base64\":case\"ascii\":case\"hex\":return e;default:if(t)return;e=(\"\"+e).toLowerCase(),t=!0;}}function a(e){var t=r(e);if(\"string\"!=typeof t&&(m.isEncoding===b||!b(e)))throw new Error(\"Unknown encoding: \"+e);return t||e}function o(e){this.encoding=a(e);var t;switch(this.encoding){case\"utf16le\":this.text=u,this.end=p,t=4;break;case\"utf8\":this.fillLast=c,t=4;break;case\"base64\":this.text=f,this.end=g,t=3;break;default:return this.write=h,void(this.end=_);}this.lastNeed=0,this.lastTotal=0,this.lastChar=m.allocUnsafe(t)}function d(e){if(127>=e)return 0;return 6==e>>5?2:14==e>>4?3:30==e>>3?4:2==e>>6?-1:-2}function s(e,t,n){var r=t.length-1;if(r=r)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString(\"utf16le\",t,e.length-1)}function p(e){var t=e&&e.length?this.write(e):\"\";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString(\"utf16le\",0,n)}return t}function f(e,t){var r=(e.length-t)%3;return 0==r?e.toString(\"base64\",t):(this.lastNeed=3-r,this.lastTotal=3,1==r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString(\"base64\",t,e.length-r))}function g(e){var t=e&&e.length?this.write(e):\"\";return this.lastNeed?t+this.lastChar.toString(\"base64\",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function _(e){return e&&e.length?this.write(e):\"\"}var m=e(\"safe-buffer\").Buffer,b=m.isEncoding||function(e){switch(e=\"\"+e,e&&e.toLowerCase()){case\"hex\":case\"utf8\":case\"utf-8\":case\"ascii\":case\"binary\":case\"base64\":case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":case\"raw\":return!0;default:return!1;}};n.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return\"\";var t,n;if(this.lastNeed){if(t=this.fillLast(e),void 0===t)return\"\";n=this.lastNeed,this.lastNeed=0}else n=0;return n */var i=e(\"debug\")(\"simple-peer\"),d=e(\"get-browser-rtc\"),s=e(\"randombytes\"),l=e(\"readable-stream\"),c=e(\"queue-microtask\"),u=65536;class p extends l.Duplex{constructor(e){if(e=Object.assign({allowHalfOpen:!1},e),super(e),this._id=s(4).toString(\"hex\").slice(0,7),this._debug(\"new peer %o\",e),this.channelName=e.initiator?e.channelName||s(20).toString(\"hex\"):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||p.channelConfig,this.negotiated=this.channelConfig.negotiated,this.config=Object.assign({},p.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.streams=e.streams||(e.stream?[e.stream]:[]),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5000,this.destroyed=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&\"object\"==typeof e.wrtc?e.wrtc:d(),!this._wrtc)if(\"undefined\"==typeof window)throw a(\"No WebRTC support: Specify `opts.wrtc` option in this environment\",\"ERR_WEBRTC_SUPPORT\");else throw a(\"No WebRTC support: Not a supported browser\",\"ERR_WEBRTC_SUPPORT\");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!this.negotiated&&!this.initiator,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._firstStable=!0,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void c(()=>this.destroy(a(e,\"ERR_PC_CONSTRUCTOR\")))}this._isReactNativeWebrtc=\"number\"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},this.initiator||this.negotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this.streams&&this.streams.forEach(e=>{this.addStream(e)}),this._pc.ontrack=e=>{this._onTrack(e)},this.initiator&&this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once(\"finish\",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&\"open\"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(this.destroyed)throw a(\"cannot signal after peer is destroyed\",\"ERR_SIGNALING\");if(\"string\"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}this._debug(\"signal()\"),e.renegotiate&&this.initiator&&(this._debug(\"got request to renegotiate\"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug(\"got request for transceiver\"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(e=>{this._addIceCandidate(e)}),this._pendingCandidates=[],\"offer\"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(e=>{this.destroy(a(e,\"ERR_SET_REMOTE_DESCRIPTION\"))}),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(a(\"signal() called with invalid signal data\",\"ERR_SIGNALING\"))}_addIceCandidate(e){var t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch(e=>{!t.address||t.address.endsWith(\".local\")?o(\"Ignoring unsupported ICE candidate.\"):this.destroy(a(e,\"ERR_ADD_ICE_CANDIDATE\"))})}send(e){this._channel.send(e)}addTransceiver(e,t){if(this._debug(\"addTransceiver()\"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(a(e,\"ERR_ADD_TRANSCEIVER\"))}else this.emit(\"signal\",{transceiverRequest:{kind:e,init:t}})}addStream(e){this._debug(\"addStream()\"),e.getTracks().forEach(t=>{this.addTrack(t,e)})}addTrack(e,t){this._debug(\"addTrack()\");var n=this._senderMap.get(e)||new Map,r=n.get(t);if(!r)r=this._pc.addTrack(e,t),n.set(t,r),this._senderMap.set(e,n),this._needsNegotiation();else if(r.removed)throw a(\"Track has been removed. You should enable/disable tracks that you want to re-add.\",\"ERR_SENDER_REMOVED\");else throw a(\"Track has already been added to that stream.\",\"ERR_SENDER_ALREADY_ADDED\")}replaceTrack(e,t,n){this._debug(\"replaceTrack()\");var r=this._senderMap.get(e),o=r?r.get(n):null;if(!o)throw a(\"Cannot replace track that was never added.\",\"ERR_TRACK_NOT_ADDED\");t&&this._senderMap.set(t,r),null==o.replaceTrack?this.destroy(a(\"replaceTrack is not supported in this browser\",\"ERR_UNSUPPORTED_REPLACETRACK\")):o.replaceTrack(t)}removeTrack(e,t){this._debug(\"removeSender()\");var n=this._senderMap.get(e),r=n?n.get(t):null;if(!r)throw a(\"Cannot remove track that was never added.\",\"ERR_TRACK_NOT_ADDED\");try{r.removed=!0,this._pc.removeTrack(r)}catch(e){\"NS_ERROR_UNEXPECTED\"===e.name?this._sendersAwaitingStable.push(r):this.destroy(a(e,\"ERR_REMOVE_TRACK\"))}this._needsNegotiation()}removeStream(e){this._debug(\"removeSenders()\"),e.getTracks().forEach(t=>{this.removeTrack(t,e)})}_needsNegotiation(){this._debug(\"_needsNegotiation\"),this._batchedNegotiation||(this._batchedNegotiation=!0,c(()=>{this._batchedNegotiation=!1,this._debug(\"starting batched negotiation\"),this.negotiate()}))}negotiate(){this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug(\"already negotiating, queueing\")):(this._debug(\"start negotiation\"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug(\"already negotiating, queueing\")):(this._debug(\"requesting negotiation from initiator\"),this.emit(\"signal\",{renegotiate:!0})),this._isNegotiating=!0}destroy(e){this._destroy(e,()=>{})}_destroy(e,t){if(!this.destroyed){if(this._debug(\"destroy (error: %s)\",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.destroyed=!0,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener(\"finish\",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit(\"error\",e),this.emit(\"close\"),t()}}_setupData(e){if(!e.channel)return this.destroy(a(\"Data channel event is missing `channel` property\",\"ERR_DATA_CHANNEL\"));this._channel=e.channel,this._channel.binaryType=\"arraybuffer\",\"number\"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=u),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{this.destroy(a(e,\"ERR_DATA_CHANNEL\"))};var t=!1;this._closingInterval=setInterval(()=>{this._channel&&\"closing\"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1},5000)}_read(){}_write(e,t,n){if(this.destroyed)return n(a(\"cannot write after peer is destroyed\",\"ERR_DATA_CHANNEL\"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(a(e,\"ERR_DATA_CHANNEL\"))}this._channel.bufferedAmount>u?(this._debug(\"start backpressure: bufferedAmount %d\",this._channel.bufferedAmount),this._cb=n):n(null)}else this._debug(\"write before connect\"),this._chunk=e,this._cb=n}_onFinish(){if(!this.destroyed){const e=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?e():this.once(\"connect\",e)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug(\"started iceComplete timeout\"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug(\"iceComplete timeout completed\"),this.emit(\"iceTimeout\"),this.emit(\"_iceComplete\"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=r(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){var t=this._pc.localDescription||e;this._debug(\"signal\"),this.emit(\"signal\",{type:t.type,sdp:t.sdp})}};this._pc.setLocalDescription(e).then(()=>{this._debug(\"createOffer success\"),this.destroyed||(this.trickle||this._iceComplete?t():this.once(\"_iceComplete\",t))}).catch(e=>{this.destroy(a(e,\"ERR_SET_LOCAL_DESCRIPTION\"))})}).catch(e=>{this.destroy(a(e,\"ERR_CREATE_OFFER\"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=r(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){var t=this._pc.localDescription||e;this._debug(\"signal\"),this.emit(\"signal\",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(e).then(()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once(\"_iceComplete\",t))}).catch(e=>{this.destroy(a(e,\"ERR_SET_LOCAL_DESCRIPTION\"))})}).catch(e=>{this.destroy(a(e,\"ERR_CREATE_ANSWER\"))})}_onConnectionStateChange(){this.destroyed||\"failed\"===this._pc.connectionState&&this.destroy(a(\"Connection failed.\",\"ERR_CONNECTION_FAILURE\"))}_onIceStateChange(){if(!this.destroyed){var e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug(\"iceStateChange (connection: %s) (gathering: %s)\",e,t),this.emit(\"iceStateChange\",e,t),(\"connected\"===e||\"completed\"===e)&&(this._pcReady=!0,this._maybeReady()),\"failed\"===e&&this.destroy(a(\"Ice connection failed.\",\"ERR_ICE_CONNECTION_FAILURE\")),\"closed\"===e&&this.destroy(a(\"Ice connection closed.\",\"ERR_ICE_CONNECTION_CLOSED\"))}}getStats(e){const t=e=>(\"[object Array]\"===Object.prototype.toString.call(e.values)&&e.values.forEach(t=>{Object.assign(e,t)}),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(n=>{var r=[];n.forEach(e=>{r.push(t(e))}),e(null,r)},t=>e(t)):0{if(!this.destroyed){var r=[];n.result().forEach(e=>{var n={};e.names().forEach(t=>{n[t]=e.stat(t)}),n.id=e.id,n.type=e.type,n.timestamp=e.timestamp,r.push(t(n))}),e(null,r)}},t=>e(t)):e(null,[])}_maybeReady(){if(this._debug(\"maybeReady pc %s channel %s\",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats((t,n)=>{if(this.destroyed)return;t&&(n=[]);var r={},o={},i={},d=!1;n.forEach(e=>{(\"remotecandidate\"===e.type||\"remote-candidate\"===e.type)&&(r[e.id]=e),(\"localcandidate\"===e.type||\"local-candidate\"===e.type)&&(o[e.id]=e),(\"candidatepair\"===e.type||\"candidate-pair\"===e.type)&&(i[e.id]=e)});const s=e=>{d=!0;var t=o[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=+t.port):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=+t.portNumber):\"string\"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(\":\"),this.localAddress=t[0],this.localPort=+t[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(\":\")?\"IPv6\":\"IPv4\");var n=r[e.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=+n.port):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=+n.portNumber):\"string\"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(\":\"),this.remoteAddress=n[0],this.remotePort=+n[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(\":\")?\"IPv6\":\"IPv4\"),this._debug(\"connect local: %s:%s remote: %s:%s\",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(n.forEach(e=>{\"transport\"===e.type&&e.selectedCandidatePairId&&s(i[e.selectedCandidatePairId]),(\"googCandidatePair\"===e.type&&\"true\"===e.googActiveConnection||(\"candidatepair\"===e.type||\"candidate-pair\"===e.type)&&e.selected)&&s(e)}),!d&&(!Object.keys(i).length||Object.keys(o).length))return void setTimeout(e,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(e){return this.destroy(a(e,\"ERR_DATA_CHANNEL\"))}this._chunk=null,this._debug(\"sent chunk from \\\"write before connect\\\"\");var l=this._cb;this._cb=null,l(null)}\"number\"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug(\"connect\"),this.emit(\"connect\")})};e()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>u)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(\"stable\"===this._pc.signalingState&&!this._firstStable&&(this._isNegotiating=!1,this._debug(\"flushing sender queue\",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation&&(this._debug(\"flushing negotiation queue\"),this._queuedNegotiation=!1,this._needsNegotiation()),this._debug(\"negotiate\"),this.emit(\"negotiate\")),this._firstStable=!1,this._debug(\"signalingStateChange %s\",this._pc.signalingState),this.emit(\"signalingStateChange\",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit(\"signal\",{candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):!e.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit(\"_iceComplete\")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(!this.destroyed){var t=e.data;t instanceof ArrayBuffer&&(t=n.from(t)),this.push(t)}}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug(\"ending backpressure: bufferedAmount %d\",this._channel.bufferedAmount);var e=this._cb;this._cb=null,e(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug(\"on channel open\"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug(\"on channel close\"),this.destroy())}_onTrack(e){this.destroyed||e.streams.forEach(t=>{this._debug(\"on track\"),this.emit(\"track\",e.track,t),this._remoteTracks.push({track:e.track,stream:t}),this._remoteStreams.some(e=>e.id===t.id)||(this._remoteStreams.push(t),c(()=>{this.emit(\"stream\",t)}))})}_debug(){var e=[].slice.call(arguments);e[0]=\"[\"+this._id+\"] \"+e[0],i.apply(null,e)}}p.WEBRTC_SUPPORT=!!d(),p.config={iceServers:[{urls:\"stun:stun.l.google.com:19302\"},{urls:\"stun:global.stun.twilio.com:3478?transport=udp\"}],sdpSemantics:\"unified-plan\"},p.channelConfig={},t.exports=p}).call(this,e(\"buffer\").Buffer)},{buffer:3,debug:4,\"get-browser-rtc\":7,\"queue-microtask\":12,randombytes:13,\"readable-stream\":28}]},{},[])(\"/\")});","/**\n * @module sync-protocol\n */\n\nimport * as encoding from 'lib0/encoding.js'\nimport * as decoding from 'lib0/decoding.js'\nimport * as Y from 'yjs'\n\n/**\n * @typedef {Map} StateMap\n */\n\n/**\n * Core Yjs defines three message types:\n * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.\n * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the the client is assured that\n * it received all information from the remote client.\n *\n * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection\n * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both\n * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.\n *\n * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.\n * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies\n * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the\n * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can\n * easily be implemented on top of http and websockets. 2. The server shoul only reply to requests, and not initiate them.\n * Therefore it is necesarry that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep1)\n const sv = Y.encodeStateVector(doc)\n encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep2)\n encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin) => {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n encoding.writeVarUint(encoder, messageYjsUpdate)\n encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Will not be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {\n const messageType = decoding.readVarUint(decoder)\n switch (messageType) {\n case messageYjsSyncStep1:\n readSyncStep1(decoder, encoder, doc)\n break\n case messageYjsSyncStep2:\n readSyncStep2(decoder, doc, transactionOrigin)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n","/**\n * @module awareness-protocol\n */\n\nimport * as encoding from 'lib0/encoding.js'\nimport * as decoding from 'lib0/decoding.js'\nimport * as time from 'lib0/time.js'\nimport * as math from 'lib0/math.js'\nimport { Observable } from 'lib0/observable.js'\nimport * as f from 'lib0/function.js'\nimport * as Y from 'yjs' // eslint-disable-line\n\nexport const outdatedTimeout = 30000\n\n/**\n * @typedef {Object} MetaClientState\n * @property {number} MetaClientState.clock\n * @property {number} MetaClientState.lastUpdated unix timestamp\n */\n\n/**\n * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information\n * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of\n * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.\n *\n * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override\n * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is\n * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that\n * a remote client is offline, it may propagate a message with\n * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a\n * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.\n *\n * Before a client disconnects, it should propagate a `null` state with an updated clock.\n *\n * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.\n *\n * @extends {Observable}\n */\nexport class Awareness extends Observable {\n /**\n * @param {Y.Doc} doc\n */\n constructor (doc) {\n super()\n this.doc = doc\n /**\n * Maps from client id to client state\n * @type {Map>}\n */\n this.states = new Map()\n /**\n * @type {Map}\n */\n this.meta = new Map()\n this._checkInterval = setInterval(() => {\n const now = time.getUnixTime()\n if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(doc.clientID)).lastUpdated)) {\n // renew local clock\n this.setLocalState(this.getLocalState())\n }\n /**\n * @type {Array}\n */\n const remove = []\n this.meta.forEach((meta, clientid) => {\n if (clientid !== doc.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {\n remove.push(clientid)\n }\n })\n if (remove.length > 0) {\n removeAwarenessStates(this, remove, 'timeout')\n }\n }, math.floor(outdatedTimeout / 10))\n doc.on('destroy', () => {\n this.destroy()\n })\n this.setLocalState({})\n }\n destroy () {\n super.destroy()\n clearInterval(this._checkInterval)\n }\n /**\n * @return {Object|null}\n */\n getLocalState () {\n return this.states.get(this.doc.clientID) || null\n }\n /**\n * @param {Object|null} state\n */\n setLocalState (state) {\n const clientID = this.doc.clientID\n const currLocalMeta = this.meta.get(clientID)\n const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1\n const prevState = this.states.get(clientID)\n if (state === null) {\n this.states.delete(clientID)\n } else {\n this.states.set(clientID, state)\n }\n this.meta.set(clientID, {\n clock,\n lastUpdated: time.getUnixTime()\n })\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n if (state === null) {\n removed.push(clientID)\n } else if (prevState == null) {\n if (state != null) {\n added.push(clientID)\n }\n } else {\n updated.push(clientID)\n if (!f.equalityDeep(prevState, state)) {\n filteredUpdated.push(clientID)\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local'])\n }\n this.emit('update', [{ added, updated, removed }, 'local'])\n }\n /**\n * @param {string} field\n * @param {any} value\n */\n setLocalStateField (field, value) {\n const state = this.getLocalState()\n if (state !== null) {\n state[field] = value\n this.setLocalState(state)\n }\n }\n /**\n * @return {Map>}\n */\n getStates () {\n return this.states\n }\n}\n\n/**\n * Mark (remote) clients as inactive and remove them from the list of active peers.\n * This change will be propagated to remote clients.\n *\n * @param {Awareness} awareness\n * @param {Array} clients\n * @param {any} origin\n */\nexport const removeAwarenessStates = (awareness, clients, origin) => {\n const removed = []\n for (let i = 0; i < clients.length; i++) {\n const clientID = clients[i]\n if (awareness.states.has(clientID)) {\n awareness.states.delete(clientID)\n if (clientID === awareness.doc.clientID) {\n const curMeta = /** @type {MetaClientState} */ (awareness.meta.get(clientID))\n awareness.meta.set(clientID, {\n clock: curMeta.clock + 1,\n lastUpdated: time.getUnixTime()\n })\n }\n removed.push(clientID)\n }\n }\n if (removed.length > 0) {\n awareness.emit('change', [{ added: [], updated: [], removed }, origin])\n awareness.emit('update', [{ added: [], updated: [], removed }, origin])\n }\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Array} clients\n * @return {Uint8Array}\n */\nexport const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {\n const len = clients.length\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = clients[i]\n const state = states.get(clientID) || null\n const clock = /** @type {MetaClientState} */ (awareness.meta.get(clientID)).clock\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(state))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Modify the content of an awareness update before re-encoding it to an awareness update.\n *\n * This might be useful when you have a central server that wants to ensure that clients\n * cant hijack somebody elses identity.\n *\n * @param {Uint8Array} update\n * @param {function(any):any} modify\n * @return {Uint8Array}\n */\nexport const modifyAwarenessUpdate = (update, modify) => {\n const decoder = decoding.createDecoder(update)\n const encoder = encoding.createEncoder()\n const len = decoding.readVarUint(decoder)\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n const clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const modifiedState = modify(state)\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(modifiedState))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Uint8Array} update\n * @param {any} origin This will be added to the emitted change event\n */\nexport const applyAwarenessUpdate = (awareness, update, origin) => {\n const decoder = decoding.createDecoder(update)\n const timestamp = time.getUnixTime()\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n const len = decoding.readVarUint(decoder)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n let clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const clientMeta = awareness.meta.get(clientID)\n const prevState = awareness.states.get(clientID)\n const currClock = clientMeta === undefined ? 0 : clientMeta.clock\n if (currClock < clock || (currClock === clock && state === null && awareness.states.has(clientID))) {\n if (state === null) {\n // never let a remote client remove this local state\n if (clientID === awareness.doc.clientID && awareness.getLocalState() != null) {\n // remote client removed the local state. Do not remote state. Broadcast a message indicating\n // that this client still exists by increasing the clock\n clock++\n } else {\n awareness.states.delete(clientID)\n }\n } else {\n awareness.states.set(clientID, state)\n }\n awareness.meta.set(clientID, {\n clock,\n lastUpdated: timestamp\n })\n if (clientMeta === undefined && state !== null) {\n added.push(clientID)\n } else if (clientMeta !== undefined && state === null) {\n removed.push(clientID)\n } else if (state !== null) {\n if (!f.equalityDeep(state, prevState)) {\n filteredUpdated.push(clientID)\n }\n updated.push(clientID)\n }\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n awareness.emit('change', [{\n added, updated: filteredUpdated, removed\n }, origin])\n }\n if (added.length > 0 || updated.length > 0 || removed.length > 0) {\n awareness.emit('update', [{\n added, updated, removed\n }, origin])\n }\n}\n","/* eslint-env browser */\n\nimport * as encoding from 'lib0/encoding.js'\nimport * as decoding from 'lib0/decoding.js'\nimport * as promise from 'lib0/promise.js'\nimport * as error from 'lib0/error.js'\nimport * as string from 'lib0/string.js'\n\n/**\n * @param {string} secret\n * @param {string} roomName\n * @return {PromiseLike}\n */\nexport const deriveKey = (secret, roomName) => {\n const secretBuffer = string.encodeUtf8(secret).buffer\n const salt = string.encodeUtf8(roomName).buffer\n return crypto.subtle.importKey(\n 'raw',\n secretBuffer,\n 'PBKDF2',\n false,\n ['deriveKey']\n ).then(keyMaterial =>\n crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt,\n iterations: 100000,\n hash: 'SHA-256'\n },\n keyMaterial,\n {\n name: 'AES-GCM',\n length: 256\n },\n true,\n ['encrypt', 'decrypt']\n )\n )\n}\n\n/**\n * @param {Uint8Array} data data to be encrypted\n * @param {CryptoKey?} key\n * @return {PromiseLike} encrypted, base64 encoded message\n */\nexport const encrypt = (data, key) => {\n if (!key) {\n return /** @type {PromiseLike} */ (promise.resolve(data))\n }\n const iv = crypto.getRandomValues(new Uint8Array(12))\n return crypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv\n },\n key,\n data\n ).then(cipher => {\n const encryptedDataEncoder = encoding.createEncoder()\n encoding.writeVarString(encryptedDataEncoder, 'AES-GCM')\n encoding.writeVarUint8Array(encryptedDataEncoder, iv)\n encoding.writeVarUint8Array(encryptedDataEncoder, new Uint8Array(cipher))\n return encoding.toUint8Array(encryptedDataEncoder)\n })\n}\n\n/**\n * @param {Object} data data to be encrypted\n * @param {CryptoKey?} key\n * @return {PromiseLike} encrypted data, if key is provided\n */\nexport const encryptJson = (data, key) => {\n const dataEncoder = encoding.createEncoder()\n encoding.writeAny(dataEncoder, data)\n return encrypt(encoding.toUint8Array(dataEncoder), key)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {CryptoKey?} key\n * @return {PromiseLike} decrypted buffer\n */\nexport const decrypt = (data, key) => {\n if (!key) {\n return /** @type {PromiseLike} */ (promise.resolve(data))\n }\n const dataDecoder = decoding.createDecoder(data)\n const algorithm = decoding.readVarString(dataDecoder)\n if (algorithm !== 'AES-GCM') {\n promise.reject(error.create('Unknown encryption algorithm'))\n }\n const iv = decoding.readVarUint8Array(dataDecoder)\n const cipher = decoding.readVarUint8Array(dataDecoder)\n return crypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv\n },\n key,\n cipher\n ).then(data => new Uint8Array(data))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {CryptoKey?} key\n * @return {PromiseLike} decrypted object\n */\nexport const decryptJson = (data, key) =>\n decrypt(data, key).then(decryptedValue =>\n decoding.readAny(decoding.createDecoder(new Uint8Array(decryptedValue)))\n )\n","import * as ws from 'lib0/websocket.js'\nimport * as map from 'lib0/map.js'\nimport * as error from 'lib0/error.js'\nimport * as random from 'lib0/random.js'\nimport * as encoding from 'lib0/encoding.js'\nimport * as decoding from 'lib0/decoding.js'\nimport { Observable } from 'lib0/observable.js'\nimport * as logging from 'lib0/logging.js'\nimport * as promise from 'lib0/promise.js'\nimport * as bc from 'lib0/broadcastchannel.js'\nimport * as buffer from 'lib0/buffer.js'\nimport * as math from 'lib0/math.js'\nimport { createMutex } from 'lib0/mutex.js'\n\nimport * as Y from 'yjs' // eslint-disable-line\nimport Peer from 'simple-peer/simplepeer.min.js'\n\nimport * as syncProtocol from 'y-protocols/sync.js'\nimport * as awarenessProtocol from 'y-protocols/awareness.js'\n\nimport * as cryptoutils from './crypto.js'\n\nconst log = logging.createModuleLogger('y-webrtc')\n\nconst messageSync = 0\nconst messageQueryAwareness = 3\nconst messageAwareness = 1\nconst messageBcPeerId = 4\n\n/**\n * @type {Map}\n */\nconst signalingConns = new Map()\n\n/**\n * @type {Map}\n */\nconst rooms = new Map()\n\n/**\n * @param {Room} room\n */\nconst checkIsSynced = room => {\n let synced = true\n room.webrtcConns.forEach(peer => {\n if (!peer.synced) {\n synced = false\n }\n })\n if ((!synced && room.synced) || (synced && !room.synced)) {\n room.synced = synced\n room.provider.emit('synced', [{ synced }])\n log('synced ', logging.BOLD, room.name, logging.UNBOLD, ' with all peers')\n }\n}\n\n/**\n * @param {Room} room\n * @param {Uint8Array} buf\n * @param {function} syncedCallback\n * @return {encoding.Encoder?}\n */\nconst readMessage = (room, buf, syncedCallback) => {\n const decoder = decoding.createDecoder(buf)\n const encoder = encoding.createEncoder()\n const messageType = decoding.readVarUint(decoder)\n if (room === undefined) {\n return null\n }\n const awareness = room.awareness\n const doc = room.doc\n let sendReply = false\n switch (messageType) {\n case messageSync: {\n encoding.writeVarUint(encoder, messageSync)\n const syncMessageType = syncProtocol.readSyncMessage(decoder, encoder, doc, room)\n if (syncMessageType === syncProtocol.messageYjsSyncStep2 && !room.synced) {\n syncedCallback()\n }\n if (syncMessageType === syncProtocol.messageYjsSyncStep1) {\n sendReply = true\n }\n break\n }\n case messageQueryAwareness:\n encoding.writeVarUint(encoder, messageAwareness)\n encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(awareness, Array.from(awareness.getStates().keys())))\n sendReply = true\n break\n case messageAwareness:\n awarenessProtocol.applyAwarenessUpdate(awareness, decoding.readVarUint8Array(decoder), room)\n break\n case messageBcPeerId: {\n const add = decoding.readUint8(decoder) === 1\n const peerName = decoding.readVarString(decoder)\n if (peerName !== room.peerId && ((room.bcConns.has(peerName) && !add) || (!room.bcConns.has(peerName) && add))) {\n const removed = []\n const added = []\n if (add) {\n room.bcConns.add(peerName)\n added.push(peerName)\n } else {\n room.bcConns.delete(peerName)\n removed.push(peerName)\n }\n room.provider.emit('peers', [{\n added,\n removed,\n webrtcPeers: Array.from(room.webrtcConns.keys()),\n bcPeers: Array.from(room.bcConns)\n }])\n broadcastBcPeerId(room)\n }\n break\n }\n default:\n console.error('Unable to compute message')\n return encoder\n }\n if (!sendReply) {\n // nothing has been written, no answer created\n return null\n }\n return encoder\n}\n\n/**\n * @param {WebrtcConn} peerConn\n * @param {Uint8Array} buf\n * @return {encoding.Encoder?}\n */\nconst readPeerMessage = (peerConn, buf) => {\n const room = peerConn.room\n log('received message from ', logging.BOLD, peerConn.remotePeerId, logging.GREY, ' (', room.name, ')', logging.UNBOLD, logging.UNCOLOR)\n return readMessage(room, buf, () => {\n peerConn.synced = true\n log('synced ', logging.BOLD, room.name, logging.UNBOLD, ' with ', logging.BOLD, peerConn.remotePeerId)\n checkIsSynced(room)\n })\n}\n\n/**\n * @param {WebrtcConn} webrtcConn\n * @param {encoding.Encoder} encoder\n */\nconst sendWebrtcConn = (webrtcConn, encoder) => {\n log('send message to ', logging.BOLD, webrtcConn.remotePeerId, logging.UNBOLD, logging.GREY, ' (', webrtcConn.room.name, ')', logging.UNCOLOR)\n try {\n webrtcConn.peer.send(encoding.toUint8Array(encoder))\n } catch (e) {}\n}\n\n/**\n * @param {Room} room\n * @param {Uint8Array} m\n */\nconst broadcastWebrtcConn = (room, m) => {\n log('broadcast message in ', logging.BOLD, room.name, logging.UNBOLD)\n room.webrtcConns.forEach(conn => {\n try {\n conn.peer.send(m)\n } catch (e) {}\n })\n}\n\nexport class WebrtcConn {\n /**\n * @param {SignalingConn} signalingConn\n * @param {boolean} initiator\n * @param {string} remotePeerId\n * @param {Room} room\n */\n constructor (signalingConn, initiator, remotePeerId, room) {\n log('establishing connection to ', logging.BOLD, remotePeerId)\n this.room = room\n this.remotePeerId = remotePeerId\n this.closed = false\n this.connected = false\n this.synced = false\n /**\n * @type {any}\n */\n this.peer = new Peer({ initiator, ...room.provider.peerOpts })\n this.peer.on('signal', signal => {\n publishSignalingMessage(signalingConn, room, { to: remotePeerId, from: room.peerId, type: 'signal', signal })\n })\n this.peer.on('connect', () => {\n log('connected to ', logging.BOLD, remotePeerId)\n this.connected = true\n // send sync step 1\n const provider = room.provider\n const doc = provider.doc\n const awareness = room.awareness\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, messageSync)\n syncProtocol.writeSyncStep1(encoder, doc)\n sendWebrtcConn(this, encoder)\n const awarenessStates = awareness.getStates()\n if (awarenessStates.size > 0) {\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, messageAwareness)\n encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(awareness, Array.from(awarenessStates.keys())))\n sendWebrtcConn(this, encoder)\n }\n })\n this.peer.on('close', () => {\n this.connected = false\n this.closed = true\n if (room.webrtcConns.has(this.remotePeerId)) {\n room.webrtcConns.delete(this.remotePeerId)\n room.provider.emit('peers', [{\n removed: [this.remotePeerId],\n added: [],\n webrtcPeers: Array.from(room.webrtcConns.keys()),\n bcPeers: Array.from(room.bcConns)\n }])\n }\n checkIsSynced(room)\n this.peer.destroy()\n log('closed connection to ', logging.BOLD, remotePeerId)\n })\n this.peer.on('close', () => {\n log('Connection to remote peer ', logging.BOLD, remotePeerId, logging.UNBOLD, ' has been closed')\n announceSignalingInfo(room)\n })\n this.peer.on('error', err => {\n log('Error in connection to ', logging.BOLD, remotePeerId, ': ', err)\n announceSignalingInfo(room)\n })\n this.peer.on('data', data => {\n const answer = readPeerMessage(this, data)\n if (answer !== null) {\n sendWebrtcConn(this, answer)\n }\n })\n }\n\n destroy () {\n this.peer.destroy()\n }\n}\n\n/**\n * @param {Room} room\n * @param {Uint8Array} m\n */\nconst broadcastBcMessage = (room, m) => cryptoutils.encrypt(m, room.key).then(data =>\n room.mux(() =>\n bc.publish(room.name, data)\n )\n)\n\n/**\n * @param {Room} room\n * @param {Uint8Array} m\n */\nconst broadcastRoomMessage = (room, m) => {\n if (room.bcconnected) {\n broadcastBcMessage(room, m)\n }\n broadcastWebrtcConn(room, m)\n}\n\n/**\n * @param {Room} room\n */\nconst announceSignalingInfo = room => {\n signalingConns.forEach(conn => {\n // only subcribe if connection is established, otherwise the conn automatically subscribes to all rooms\n if (conn.connected) {\n conn.send({ type: 'subscribe', topics: [room.name] })\n if (room.webrtcConns.size < room.provider.maxConns) {\n publishSignalingMessage(conn, room, { type: 'announce', from: room.peerId })\n }\n }\n })\n}\n\n/**\n * @param {Room} room\n */\nconst broadcastBcPeerId = room => {\n if (room.provider.filterBcConns) {\n // broadcast peerId via broadcastchannel\n const encoderPeerIdBc = encoding.createEncoder()\n encoding.writeVarUint(encoderPeerIdBc, messageBcPeerId)\n encoding.writeUint8(encoderPeerIdBc, 1)\n encoding.writeVarString(encoderPeerIdBc, room.peerId)\n broadcastBcMessage(room, encoding.toUint8Array(encoderPeerIdBc))\n }\n}\n\nexport class Room {\n /**\n * @param {Y.Doc} doc\n * @param {WebrtcProvider} provider\n * @param {string} name\n * @param {CryptoKey|null} key\n */\n constructor (doc, provider, name, key) {\n /**\n * Do not assume that peerId is unique. This is only meant for sending signaling messages.\n *\n * @type {string}\n */\n this.peerId = random.uuidv4()\n this.doc = doc\n /**\n * @type {awarenessProtocol.Awareness}\n */\n this.awareness = provider.awareness\n this.provider = provider\n this.synced = false\n this.name = name\n // @todo make key secret by scoping\n this.key = key\n /**\n * @type {Map}\n */\n this.webrtcConns = new Map()\n /**\n * @type {Set}\n */\n this.bcConns = new Set()\n this.mux = createMutex()\n this.bcconnected = false\n /**\n * @param {ArrayBuffer} data\n */\n this._bcSubscriber = data =>\n cryptoutils.decrypt(new Uint8Array(data), key).then(m =>\n this.mux(() => {\n const reply = readMessage(this, m, () => {})\n if (reply) {\n broadcastBcMessage(this, encoding.toUint8Array(reply))\n }\n })\n )\n /**\n * Listens to Yjs updates and sends them to remote peers\n *\n * @param {Uint8Array} update\n * @param {any} origin\n */\n this._docUpdateHandler = (update, origin) => {\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, messageSync)\n syncProtocol.writeUpdate(encoder, update)\n broadcastRoomMessage(this, encoding.toUint8Array(encoder))\n }\n /**\n * Listens to Awareness updates and sends them to remote peers\n *\n * @param {any} changed\n * @param {any} origin\n */\n this._awarenessUpdateHandler = ({ added, updated, removed }, origin) => {\n const changedClients = added.concat(updated).concat(removed)\n const encoderAwareness = encoding.createEncoder()\n encoding.writeVarUint(encoderAwareness, messageAwareness)\n encoding.writeVarUint8Array(encoderAwareness, awarenessProtocol.encodeAwarenessUpdate(this.awareness, changedClients))\n broadcastRoomMessage(this, encoding.toUint8Array(encoderAwareness))\n }\n this.doc.on('update', this._docUpdateHandler)\n this.awareness.on('update', this._awarenessUpdateHandler)\n window.addEventListener('beforeunload', () => {\n awarenessProtocol.removeAwarenessStates(this.awareness, [doc.clientID], 'window unload')\n rooms.forEach(room => {\n room.disconnect()\n })\n })\n }\n\n connect () {\n // signal through all available signaling connections\n announceSignalingInfo(this)\n const roomName = this.name\n bc.subscribe(roomName, this._bcSubscriber)\n this.bcconnected = true\n // broadcast peerId via broadcastchannel\n broadcastBcPeerId(this)\n // write sync step 1\n const encoderSync = encoding.createEncoder()\n encoding.writeVarUint(encoderSync, messageSync)\n syncProtocol.writeSyncStep1(encoderSync, this.doc)\n broadcastBcMessage(this, encoding.toUint8Array(encoderSync))\n // broadcast local state\n const encoderState = encoding.createEncoder()\n encoding.writeVarUint(encoderState, messageSync)\n syncProtocol.writeSyncStep2(encoderState, this.doc)\n broadcastBcMessage(this, encoding.toUint8Array(encoderState))\n // write queryAwareness\n const encoderAwarenessQuery = encoding.createEncoder()\n encoding.writeVarUint(encoderAwarenessQuery, messageQueryAwareness)\n broadcastBcMessage(this, encoding.toUint8Array(encoderAwarenessQuery))\n // broadcast local awareness state\n const encoderAwarenessState = encoding.createEncoder()\n encoding.writeVarUint(encoderAwarenessState, messageAwareness)\n encoding.writeVarUint8Array(encoderAwarenessState, awarenessProtocol.encodeAwarenessUpdate(this.awareness, [this.doc.clientID]))\n broadcastBcMessage(this, encoding.toUint8Array(encoderAwarenessState))\n }\n\n disconnect () {\n // signal through all available signaling connections\n signalingConns.forEach(conn => {\n if (conn.connected) {\n conn.send({ type: 'unsubscribe', topics: [this.name] })\n }\n })\n awarenessProtocol.removeAwarenessStates(this.awareness, [this.doc.clientID], 'disconnect')\n // broadcast peerId removal via broadcastchannel\n const encoderPeerIdBc = encoding.createEncoder()\n encoding.writeVarUint(encoderPeerIdBc, messageBcPeerId)\n encoding.writeUint8(encoderPeerIdBc, 0) // remove peerId from other bc peers\n encoding.writeVarString(encoderPeerIdBc, this.peerId)\n broadcastBcMessage(this, encoding.toUint8Array(encoderPeerIdBc))\n\n bc.unsubscribe(this.name, this._bcSubscriber)\n this.bcconnected = false\n this.doc.off('update', this._docUpdateHandler)\n this.awareness.off('update', this._awarenessUpdateHandler)\n this.webrtcConns.forEach(conn => conn.destroy())\n }\n\n destroy () {\n this.disconnect()\n }\n}\n\n/**\n * @param {Y.Doc} doc\n * @param {WebrtcProvider} provider\n * @param {string} name\n * @param {CryptoKey|null} key\n * @return {Room}\n */\nconst openRoom = (doc, provider, name, key) => {\n // there must only be one room\n if (rooms.has(name)) {\n throw error.create(`A Yjs Doc connected to room \"${name}\" already exists!`)\n }\n const room = new Room(doc, provider, name, key)\n rooms.set(name, /** @type {Room} */ (room))\n return room\n}\n\n/**\n * @param {SignalingConn} conn\n * @param {Room} room\n * @param {any} data\n */\nconst publishSignalingMessage = (conn, room, data) => {\n if (room.key) {\n cryptoutils.encryptJson(data, room.key).then(data => {\n conn.send({ type: 'publish', topic: room.name, data: buffer.toBase64(data) })\n })\n } else {\n conn.send({ type: 'publish', topic: room.name, data })\n }\n}\n\nexport class SignalingConn extends ws.WebsocketClient {\n constructor (url) {\n super(url)\n /**\n * @type {Set}\n */\n this.providers = new Set()\n this.on('connect', () => {\n log(`connected (${url})`)\n const topics = Array.from(rooms.keys())\n this.send({ type: 'subscribe', topics })\n rooms.forEach(room =>\n publishSignalingMessage(this, room, { type: 'announce', from: room.peerId })\n )\n })\n this.on('message', m => {\n switch (m.type) {\n case 'publish': {\n const roomName = m.topic\n const room = rooms.get(roomName)\n if (room == null || typeof roomName !== 'string') {\n return\n }\n const execMessage = data => {\n const webrtcConns = room.webrtcConns\n const peerId = room.peerId\n if (data == null || data.from === peerId || (data.to !== undefined && data.to !== peerId) || room.bcConns.has(data.from)) {\n // ignore messages that are not addressed to this conn, or from clients that are connected via broadcastchannel\n return\n }\n const emitPeerChange = webrtcConns.has(data.from) ? () => {} : () =>\n room.provider.emit('peers', [{\n removed: [],\n added: [data.from],\n webrtcPeers: Array.from(room.webrtcConns.keys()),\n bcPeers: Array.from(room.bcConns)\n }])\n switch (data.type) {\n case 'announce':\n if (webrtcConns.size < room.provider.maxConns) {\n map.setIfUndefined(webrtcConns, data.from, () => new WebrtcConn(this, true, data.from, room))\n emitPeerChange()\n }\n break\n case 'signal':\n if (data.to === peerId) {\n map.setIfUndefined(webrtcConns, data.from, () => new WebrtcConn(this, false, data.from, room)).peer.signal(data.signal)\n emitPeerChange()\n }\n break\n }\n }\n if (room.key) {\n if (typeof m.data === 'string') {\n cryptoutils.decryptJson(buffer.fromBase64(m.data), room.key).then(execMessage)\n }\n } else {\n execMessage(m.data)\n }\n }\n }\n })\n this.on('disconnect', () => log(`disconnect (${url})`))\n }\n}\n\n/**\n * @extends Observable\n */\nexport class WebrtcProvider extends Observable {\n /**\n * @param {string} roomName\n * @param {Y.Doc} doc\n * @param {Object} [opts]\n * @param {Array} [opts.signaling]\n * @param {string?} [opts.password]\n * @param {awarenessProtocol.Awareness} [opts.awareness]\n * @param {number} [opts.maxConns]\n * @param {boolean} [opts.filterBcConns]\n * @param {any} [opts.peerOpts]\n */\n constructor (\n roomName,\n doc,\n {\n signaling = ['wss://signaling.yjs.dev', 'wss://y-webrtc-signaling-eu.herokuapp.com', 'wss://y-webrtc-signaling-us.herokuapp.com'],\n password = null,\n awareness = new awarenessProtocol.Awareness(doc),\n maxConns = 20 + math.floor(random.rand() * 15), // the random factor reduces the chance that n clients form a cluster\n filterBcConns = true,\n peerOpts = {} // simple-peer options. See https://github.com/feross/simple-peer#peer--new-peeropts\n } = {}\n ) {\n super()\n this.roomName = roomName\n this.doc = doc\n this.filterBcConns = filterBcConns\n /**\n * @type {awarenessProtocol.Awareness}\n */\n this.awareness = awareness\n this.shouldConnect = false\n this.signalingUrls = signaling\n this.signalingConns = []\n this.maxConns = maxConns\n this.peerOpts = peerOpts\n /**\n * @type {PromiseLike}\n */\n this.key = password ? cryptoutils.deriveKey(password, roomName) : /** @type {PromiseLike} */ (promise.resolve(null))\n /**\n * @type {Room|null}\n */\n this.room = null\n this.key.then(key => {\n this.room = openRoom(doc, this, roomName, key)\n if (this.shouldConnect) {\n this.room.connect()\n } else {\n this.room.disconnect()\n }\n })\n this.connect()\n }\n\n /**\n * @type {boolean}\n */\n get connected () {\n return this.room !== null && this.shouldConnect\n }\n\n connect () {\n this.shouldConnect = true\n this.signalingUrls.forEach(url => {\n const signalingConn = map.setIfUndefined(signalingConns, url, () => new SignalingConn(url))\n this.signalingConns.push(signalingConn)\n signalingConn.providers.add(this)\n })\n if (this.room) {\n this.room.connect()\n }\n }\n\n disconnect () {\n this.shouldConnect = false\n this.signalingConns.forEach(conn => {\n conn.providers.delete(this)\n if (conn.providers.size === 0) {\n conn.destroy()\n signalingConns.delete(this.roomName)\n }\n })\n if (this.room) {\n this.room.disconnect()\n }\n }\n\n destroy () {\n // need to wait for key before deleting room\n this.key.then(() => {\n /** @type {Room} */ (this.room).destroy()\n rooms.delete(this.roomName)\n })\n super.destroy()\n }\n}\n","// ::- Persistent data structure representing an ordered mapping from\n// strings to values, with some convenient update methods.\nfunction OrderedMap(content) {\n this.content = content;\n}\n\nOrderedMap.prototype = {\n constructor: OrderedMap,\n\n find: function(key) {\n for (var i = 0; i < this.content.length; i += 2)\n if (this.content[i] === key) return i\n return -1\n },\n\n // :: (string) → ?any\n // Retrieve the value stored under `key`, or return undefined when\n // no such key exists.\n get: function(key) {\n var found = this.find(key);\n return found == -1 ? undefined : this.content[found + 1]\n },\n\n // :: (string, any, ?string) → OrderedMap\n // Create a new map by replacing the value of `key` with a new\n // value, or adding a binding to the end of the map. If `newKey` is\n // given, the key of the binding will be replaced with that key.\n update: function(key, value, newKey) {\n var self = newKey && newKey != key ? this.remove(newKey) : this;\n var found = self.find(key), content = self.content.slice();\n if (found == -1) {\n content.push(newKey || key, value);\n } else {\n content[found + 1] = value;\n if (newKey) content[found] = newKey;\n }\n return new OrderedMap(content)\n },\n\n // :: (string) → OrderedMap\n // Return a map with the given key removed, if it existed.\n remove: function(key) {\n var found = this.find(key);\n if (found == -1) return this\n var content = this.content.slice();\n content.splice(found, 2);\n return new OrderedMap(content)\n },\n\n // :: (string, any) → OrderedMap\n // Add a new key to the start of the map.\n addToStart: function(key, value) {\n return new OrderedMap([key, value].concat(this.remove(key).content))\n },\n\n // :: (string, any) → OrderedMap\n // Add a new key to the end of the map.\n addToEnd: function(key, value) {\n var content = this.remove(key).content.slice();\n content.push(key, value);\n return new OrderedMap(content)\n },\n\n // :: (string, string, any) → OrderedMap\n // Add a key after the given key. If `place` is not found, the new\n // key is added to the end.\n addBefore: function(place, key, value) {\n var without = this.remove(key), content = without.content.slice();\n var found = without.find(place);\n content.splice(found == -1 ? content.length : found, 0, key, value);\n return new OrderedMap(content)\n },\n\n // :: ((key: string, value: any))\n // Call the given function for each key/value pair in the map, in\n // order.\n forEach: function(f) {\n for (var i = 0; i < this.content.length; i += 2)\n f(this.content[i], this.content[i + 1]);\n },\n\n // :: (union) → OrderedMap\n // Create a new map by prepending the keys in this map that don't\n // appear in `map` before the keys in `map`.\n prepend: function(map) {\n map = OrderedMap.from(map);\n if (!map.size) return this\n return new OrderedMap(map.content.concat(this.subtract(map).content))\n },\n\n // :: (union) → OrderedMap\n // Create a new map by appending the keys in this map that don't\n // appear in `map` after the keys in `map`.\n append: function(map) {\n map = OrderedMap.from(map);\n if (!map.size) return this\n return new OrderedMap(this.subtract(map).content.concat(map.content))\n },\n\n // :: (union) → OrderedMap\n // Create a map containing all the keys in this map that don't\n // appear in `map`.\n subtract: function(map) {\n var result = this;\n map = OrderedMap.from(map);\n for (var i = 0; i < map.content.length; i += 2)\n result = result.remove(map.content[i]);\n return result\n },\n\n // :: number\n // The amount of keys in this map.\n get size() {\n return this.content.length >> 1\n }\n};\n\n// :: (?union) → OrderedMap\n// Return a map with the given content. If null, create an empty\n// map. If given an ordered map, return that map itself. If given an\n// object, create a map from the object's properties.\nOrderedMap.from = function(value) {\n if (value instanceof OrderedMap) return value\n var content = [];\n if (value) for (var prop in value) content.push(prop, value[prop]);\n return new OrderedMap(content)\n};\n\nvar orderedmap = OrderedMap;\n\nexport default orderedmap;\n","import OrderedMap from 'orderedmap';\n\nfunction findDiffStart(a, b, pos) {\n for (var i = 0;; i++) {\n if (i == a.childCount || i == b.childCount)\n { return a.childCount == b.childCount ? null : pos }\n\n var childA = a.child(i), childB = b.child(i);\n if (childA == childB) { pos += childA.nodeSize; continue }\n\n if (!childA.sameMarkup(childB)) { return pos }\n\n if (childA.isText && childA.text != childB.text) {\n for (var j = 0; childA.text[j] == childB.text[j]; j++)\n { pos++; }\n return pos\n }\n if (childA.content.size || childB.content.size) {\n var inner = findDiffStart(childA.content, childB.content, pos + 1);\n if (inner != null) { return inner }\n }\n pos += childA.nodeSize;\n }\n}\n\nfunction findDiffEnd(a, b, posA, posB) {\n for (var iA = a.childCount, iB = b.childCount;;) {\n if (iA == 0 || iB == 0)\n { return iA == iB ? null : {a: posA, b: posB} }\n\n var childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;\n if (childA == childB) {\n posA -= size; posB -= size;\n continue\n }\n\n if (!childA.sameMarkup(childB)) { return {a: posA, b: posB} }\n\n if (childA.isText && childA.text != childB.text) {\n var same = 0, minSize = Math.min(childA.text.length, childB.text.length);\n while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {\n same++; posA--; posB--;\n }\n return {a: posA, b: posB}\n }\n if (childA.content.size || childB.content.size) {\n var inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);\n if (inner) { return inner }\n }\n posA -= size; posB -= size;\n }\n}\n\n// ::- A fragment represents a node's collection of child nodes.\n//\n// Like nodes, fragments are persistent data structures, and you\n// should not mutate them or their content. Rather, you create new\n// instances whenever needed. The API tries to make this easy.\nvar Fragment = function Fragment(content, size) {\n this.content = content;\n // :: number\n // The size of the fragment, which is the total of the size of its\n // content nodes.\n this.size = size || 0;\n if (size == null) { for (var i = 0; i < content.length; i++)\n { this.size += content[i].nodeSize; } }\n};\n\nvar prototypeAccessors = { firstChild: { configurable: true },lastChild: { configurable: true },childCount: { configurable: true } };\n\n// :: (number, number, (node: Node, start: number, parent: Node, index: number) → ?bool, ?number)\n// Invoke a callback for all descendant nodes between the given two\n// positions (relative to start of this fragment). Doesn't descend\n// into a node when the callback returns `false`.\nFragment.prototype.nodesBetween = function nodesBetween (from, to, f, nodeStart, parent) {\n if ( nodeStart === void 0 ) nodeStart = 0;\n\n for (var i = 0, pos = 0; pos < to; i++) {\n var child = this.content[i], end = pos + child.nodeSize;\n if (end > from && f(child, nodeStart + pos, parent, i) !== false && child.content.size) {\n var start = pos + 1;\n child.nodesBetween(Math.max(0, from - start),\n Math.min(child.content.size, to - start),\n f, nodeStart + start);\n }\n pos = end;\n }\n};\n\n// :: ((node: Node, pos: number, parent: Node) → ?bool)\n// Call the given callback for every descendant node. The callback\n// may return `false` to prevent traversal of a given node's children.\nFragment.prototype.descendants = function descendants (f) {\n this.nodesBetween(0, this.size, f);\n};\n\n// : (number, number, ?string, ?string) → string\nFragment.prototype.textBetween = function textBetween (from, to, blockSeparator, leafText) {\n var text = \"\", separated = true;\n this.nodesBetween(from, to, function (node, pos) {\n if (node.isText) {\n text += node.text.slice(Math.max(from, pos) - pos, to - pos);\n separated = !blockSeparator;\n } else if (node.isLeaf && leafText) {\n text += leafText;\n separated = !blockSeparator;\n } else if (!separated && node.isBlock) {\n text += blockSeparator;\n separated = true;\n }\n }, 0);\n return text\n};\n\n// :: (Fragment) → Fragment\n// Create a new fragment containing the combined content of this\n// fragment and the other.\nFragment.prototype.append = function append (other) {\n if (!other.size) { return this }\n if (!this.size) { return other }\n var last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;\n if (last.isText && last.sameMarkup(first)) {\n content[content.length - 1] = last.withText(last.text + first.text);\n i = 1;\n }\n for (; i < other.content.length; i++) { content.push(other.content[i]); }\n return new Fragment(content, this.size + other.size)\n};\n\n// :: (number, ?number) → Fragment\n// Cut out the sub-fragment between the two given positions.\nFragment.prototype.cut = function cut (from, to) {\n if (to == null) { to = this.size; }\n if (from == 0 && to == this.size) { return this }\n var result = [], size = 0;\n if (to > from) { for (var i = 0, pos = 0; pos < to; i++) {\n var child = this.content[i], end = pos + child.nodeSize;\n if (end > from) {\n if (pos < from || end > to) {\n if (child.isText)\n { child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos)); }\n else\n { child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1)); }\n }\n result.push(child);\n size += child.nodeSize;\n }\n pos = end;\n } }\n return new Fragment(result, size)\n};\n\nFragment.prototype.cutByIndex = function cutByIndex (from, to) {\n if (from == to) { return Fragment.empty }\n if (from == 0 && to == this.content.length) { return this }\n return new Fragment(this.content.slice(from, to))\n};\n\n// :: (number, Node) → Fragment\n// Create a new fragment in which the node at the given index is\n// replaced by the given node.\nFragment.prototype.replaceChild = function replaceChild (index, node) {\n var current = this.content[index];\n if (current == node) { return this }\n var copy = this.content.slice();\n var size = this.size + node.nodeSize - current.nodeSize;\n copy[index] = node;\n return new Fragment(copy, size)\n};\n\n// : (Node) → Fragment\n// Create a new fragment by prepending the given node to this\n// fragment.\nFragment.prototype.addToStart = function addToStart (node) {\n return new Fragment([node].concat(this.content), this.size + node.nodeSize)\n};\n\n// : (Node) → Fragment\n// Create a new fragment by appending the given node to this\n// fragment.\nFragment.prototype.addToEnd = function addToEnd (node) {\n return new Fragment(this.content.concat(node), this.size + node.nodeSize)\n};\n\n// :: (Fragment) → bool\n// Compare this fragment to another one.\nFragment.prototype.eq = function eq (other) {\n if (this.content.length != other.content.length) { return false }\n for (var i = 0; i < this.content.length; i++)\n { if (!this.content[i].eq(other.content[i])) { return false } }\n return true\n};\n\n// :: ?Node\n// The first child of the fragment, or `null` if it is empty.\nprototypeAccessors.firstChild.get = function () { return this.content.length ? this.content[0] : null };\n\n// :: ?Node\n// The last child of the fragment, or `null` if it is empty.\nprototypeAccessors.lastChild.get = function () { return this.content.length ? this.content[this.content.length - 1] : null };\n\n// :: number\n// The number of child nodes in this fragment.\nprototypeAccessors.childCount.get = function () { return this.content.length };\n\n// :: (number) → Node\n// Get the child node at the given index. Raise an error when the\n// index is out of range.\nFragment.prototype.child = function child (index) {\n var found = this.content[index];\n if (!found) { throw new RangeError(\"Index \" + index + \" out of range for \" + this) }\n return found\n};\n\n// :: (number) → ?Node\n// Get the child node at the given index, if it exists.\nFragment.prototype.maybeChild = function maybeChild (index) {\n return this.content[index]\n};\n\n// :: ((node: Node, offset: number, index: number))\n// Call `f` for every child node, passing the node, its offset\n// into this parent node, and its index.\nFragment.prototype.forEach = function forEach (f) {\n for (var i = 0, p = 0; i < this.content.length; i++) {\n var child = this.content[i];\n f(child, p, i);\n p += child.nodeSize;\n }\n};\n\n// :: (Fragment) → ?number\n// Find the first position at which this fragment and another\n// fragment differ, or `null` if they are the same.\nFragment.prototype.findDiffStart = function findDiffStart$1 (other, pos) {\n if ( pos === void 0 ) pos = 0;\n\n return findDiffStart(this, other, pos)\n};\n\n// :: (Fragment) → ?{a: number, b: number}\n// Find the first position, searching from the end, at which this\n// fragment and the given fragment differ, or `null` if they are the\n// same. Since this position will not be the same in both nodes, an\n// object with two separate positions is returned.\nFragment.prototype.findDiffEnd = function findDiffEnd$1 (other, pos, otherPos) {\n if ( pos === void 0 ) pos = this.size;\n if ( otherPos === void 0 ) otherPos = other.size;\n\n return findDiffEnd(this, other, pos, otherPos)\n};\n\n// : (number, ?number) → {index: number, offset: number}\n// Find the index and inner offset corresponding to a given relative\n// position in this fragment. The result object will be reused\n// (overwritten) the next time the function is called. (Not public.)\nFragment.prototype.findIndex = function findIndex (pos, round) {\n if ( round === void 0 ) round = -1;\n\n if (pos == 0) { return retIndex(0, pos) }\n if (pos == this.size) { return retIndex(this.content.length, pos) }\n if (pos > this.size || pos < 0) { throw new RangeError((\"Position \" + pos + \" outside of fragment (\" + (this) + \")\")) }\n for (var i = 0, curPos = 0;; i++) {\n var cur = this.child(i), end = curPos + cur.nodeSize;\n if (end >= pos) {\n if (end == pos || round > 0) { return retIndex(i + 1, end) }\n return retIndex(i, curPos)\n }\n curPos = end;\n }\n};\n\n// :: () → string\n// Return a debugging string that describes this fragment.\nFragment.prototype.toString = function toString () { return \"<\" + this.toStringInner() + \">\" };\n\nFragment.prototype.toStringInner = function toStringInner () { return this.content.join(\", \") };\n\n// :: () → ?Object\n// Create a JSON-serializeable representation of this fragment.\nFragment.prototype.toJSON = function toJSON () {\n return this.content.length ? this.content.map(function (n) { return n.toJSON(); }) : null\n};\n\n// :: (Schema, ?Object) → Fragment\n// Deserialize a fragment from its JSON representation.\nFragment.fromJSON = function fromJSON (schema, value) {\n if (!value) { return Fragment.empty }\n if (!Array.isArray(value)) { throw new RangeError(\"Invalid input for Fragment.fromJSON\") }\n return new Fragment(value.map(schema.nodeFromJSON))\n};\n\n// :: ([Node]) → Fragment\n// Build a fragment from an array of nodes. Ensures that adjacent\n// text nodes with the same marks are joined together.\nFragment.fromArray = function fromArray (array) {\n if (!array.length) { return Fragment.empty }\n var joined, size = 0;\n for (var i = 0; i < array.length; i++) {\n var node = array[i];\n size += node.nodeSize;\n if (i && node.isText && array[i - 1].sameMarkup(node)) {\n if (!joined) { joined = array.slice(0, i); }\n joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text);\n } else if (joined) {\n joined.push(node);\n }\n }\n return new Fragment(joined || array, size)\n};\n\n// :: (?union) → Fragment\n// Create a fragment from something that can be interpreted as a set\n// of nodes. For `null`, it returns the empty fragment. For a\n// fragment, the fragment itself. For a node or array of nodes, a\n// fragment containing those nodes.\nFragment.from = function from (nodes) {\n if (!nodes) { return Fragment.empty }\n if (nodes instanceof Fragment) { return nodes }\n if (Array.isArray(nodes)) { return this.fromArray(nodes) }\n if (nodes.attrs) { return new Fragment([nodes], nodes.nodeSize) }\n throw new RangeError(\"Can not convert \" + nodes + \" to a Fragment\" +\n (nodes.nodesBetween ? \" (looks like multiple versions of prosemirror-model were loaded)\" : \"\"))\n};\n\nObject.defineProperties( Fragment.prototype, prototypeAccessors );\n\nvar found = {index: 0, offset: 0};\nfunction retIndex(index, offset) {\n found.index = index;\n found.offset = offset;\n return found\n}\n\n// :: Fragment\n// An empty fragment. Intended to be reused whenever a node doesn't\n// contain anything (rather than allocating a new empty fragment for\n// each leaf node).\nFragment.empty = new Fragment([], 0);\n\nfunction compareDeep(a, b) {\n if (a === b) { return true }\n if (!(a && typeof a == \"object\") ||\n !(b && typeof b == \"object\")) { return false }\n var array = Array.isArray(a);\n if (Array.isArray(b) != array) { return false }\n if (array) {\n if (a.length != b.length) { return false }\n for (var i = 0; i < a.length; i++) { if (!compareDeep(a[i], b[i])) { return false } }\n } else {\n for (var p in a) { if (!(p in b) || !compareDeep(a[p], b[p])) { return false } }\n for (var p$1 in b) { if (!(p$1 in a)) { return false } }\n }\n return true\n}\n\n// ::- A mark is a piece of information that can be attached to a node,\n// such as it being emphasized, in code font, or a link. It has a type\n// and optionally a set of attributes that provide further information\n// (such as the target of the link). Marks are created through a\n// `Schema`, which controls which types exist and which\n// attributes they have.\nvar Mark = function Mark(type, attrs) {\n // :: MarkType\n // The type of this mark.\n this.type = type;\n // :: Object\n // The attributes associated with this mark.\n this.attrs = attrs;\n};\n\n// :: ([Mark]) → [Mark]\n// Given a set of marks, create a new set which contains this one as\n// well, in the right position. If this mark is already in the set,\n// the set itself is returned. If any marks that are set to be\n// [exclusive](#model.MarkSpec.excludes) with this mark are present,\n// those are replaced by this one.\nMark.prototype.addToSet = function addToSet (set) {\n var copy, placed = false;\n for (var i = 0; i < set.length; i++) {\n var other = set[i];\n if (this.eq(other)) { return set }\n if (this.type.excludes(other.type)) {\n if (!copy) { copy = set.slice(0, i); }\n } else if (other.type.excludes(this.type)) {\n return set\n } else {\n if (!placed && other.type.rank > this.type.rank) {\n if (!copy) { copy = set.slice(0, i); }\n copy.push(this);\n placed = true;\n }\n if (copy) { copy.push(other); }\n }\n }\n if (!copy) { copy = set.slice(); }\n if (!placed) { copy.push(this); }\n return copy\n};\n\n// :: ([Mark]) → [Mark]\n// Remove this mark from the given set, returning a new set. If this\n// mark is not in the set, the set itself is returned.\nMark.prototype.removeFromSet = function removeFromSet (set) {\n for (var i = 0; i < set.length; i++)\n { if (this.eq(set[i]))\n { return set.slice(0, i).concat(set.slice(i + 1)) } }\n return set\n};\n\n// :: ([Mark]) → bool\n// Test whether this mark is in the given set of marks.\nMark.prototype.isInSet = function isInSet (set) {\n for (var i = 0; i < set.length; i++)\n { if (this.eq(set[i])) { return true } }\n return false\n};\n\n// :: (Mark) → bool\n// Test whether this mark has the same type and attributes as\n// another mark.\nMark.prototype.eq = function eq (other) {\n return this == other ||\n (this.type == other.type && compareDeep(this.attrs, other.attrs))\n};\n\n// :: () → Object\n// Convert this mark to a JSON-serializeable representation.\nMark.prototype.toJSON = function toJSON () {\n var obj = {type: this.type.name};\n for (var _ in this.attrs) {\n obj.attrs = this.attrs;\n break\n }\n return obj\n};\n\n// :: (Schema, Object) → Mark\nMark.fromJSON = function fromJSON (schema, json) {\n if (!json) { throw new RangeError(\"Invalid input for Mark.fromJSON\") }\n var type = schema.marks[json.type];\n if (!type) { throw new RangeError((\"There is no mark type \" + (json.type) + \" in this schema\")) }\n return type.create(json.attrs)\n};\n\n// :: ([Mark], [Mark]) → bool\n// Test whether two sets of marks are identical.\nMark.sameSet = function sameSet (a, b) {\n if (a == b) { return true }\n if (a.length != b.length) { return false }\n for (var i = 0; i < a.length; i++)\n { if (!a[i].eq(b[i])) { return false } }\n return true\n};\n\n// :: (?union) → [Mark]\n// Create a properly sorted mark set from null, a single mark, or an\n// unsorted array of marks.\nMark.setFrom = function setFrom (marks) {\n if (!marks || marks.length == 0) { return Mark.none }\n if (marks instanceof Mark) { return [marks] }\n var copy = marks.slice();\n copy.sort(function (a, b) { return a.type.rank - b.type.rank; });\n return copy\n};\n\n// :: [Mark] The empty set of marks.\nMark.none = [];\n\n// ReplaceError:: class extends Error\n// Error type raised by [`Node.replace`](#model.Node.replace) when\n// given an invalid replacement.\n\nfunction ReplaceError(message) {\n var err = Error.call(this, message);\n err.__proto__ = ReplaceError.prototype;\n return err\n}\n\nReplaceError.prototype = Object.create(Error.prototype);\nReplaceError.prototype.constructor = ReplaceError;\nReplaceError.prototype.name = \"ReplaceError\";\n\n// ::- A slice represents a piece cut out of a larger document. It\n// stores not only a fragment, but also the depth up to which nodes on\n// both side are ‘open’ (cut through).\nvar Slice = function Slice(content, openStart, openEnd) {\n // :: Fragment The slice's content.\n this.content = content;\n // :: number The open depth at the start.\n this.openStart = openStart;\n // :: number The open depth at the end.\n this.openEnd = openEnd;\n};\n\nvar prototypeAccessors$1 = { size: { configurable: true } };\n\n// :: number\n// The size this slice would add when inserted into a document.\nprototypeAccessors$1.size.get = function () {\n return this.content.size - this.openStart - this.openEnd\n};\n\nSlice.prototype.insertAt = function insertAt (pos, fragment) {\n var content = insertInto(this.content, pos + this.openStart, fragment, null);\n return content && new Slice(content, this.openStart, this.openEnd)\n};\n\nSlice.prototype.removeBetween = function removeBetween (from, to) {\n return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd)\n};\n\n// :: (Slice) → bool\n// Tests whether this slice is equal to another slice.\nSlice.prototype.eq = function eq (other) {\n return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd\n};\n\nSlice.prototype.toString = function toString () {\n return this.content + \"(\" + this.openStart + \",\" + this.openEnd + \")\"\n};\n\n// :: () → ?Object\n// Convert a slice to a JSON-serializable representation.\nSlice.prototype.toJSON = function toJSON () {\n if (!this.content.size) { return null }\n var json = {content: this.content.toJSON()};\n if (this.openStart > 0) { json.openStart = this.openStart; }\n if (this.openEnd > 0) { json.openEnd = this.openEnd; }\n return json\n};\n\n// :: (Schema, ?Object) → Slice\n// Deserialize a slice from its JSON representation.\nSlice.fromJSON = function fromJSON (schema, json) {\n if (!json) { return Slice.empty }\n var openStart = json.openStart || 0, openEnd = json.openEnd || 0;\n if (typeof openStart != \"number\" || typeof openEnd != \"number\")\n { throw new RangeError(\"Invalid input for Slice.fromJSON\") }\n return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd)\n};\n\n// :: (Fragment, ?bool) → Slice\n// Create a slice from a fragment by taking the maximum possible\n// open value on both side of the fragment.\nSlice.maxOpen = function maxOpen (fragment, openIsolating) {\n if ( openIsolating === void 0 ) openIsolating=true;\n\n var openStart = 0, openEnd = 0;\n for (var n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild) { openStart++; }\n for (var n$1 = fragment.lastChild; n$1 && !n$1.isLeaf && (openIsolating || !n$1.type.spec.isolating); n$1 = n$1.lastChild) { openEnd++; }\n return new Slice(fragment, openStart, openEnd)\n};\n\nObject.defineProperties( Slice.prototype, prototypeAccessors$1 );\n\nfunction removeRange(content, from, to) {\n var ref = content.findIndex(from);\n var index = ref.index;\n var offset = ref.offset;\n var child = content.maybeChild(index);\n var ref$1 = content.findIndex(to);\n var indexTo = ref$1.index;\n var offsetTo = ref$1.offset;\n if (offset == from || child.isText) {\n if (offsetTo != to && !content.child(indexTo).isText) { throw new RangeError(\"Removing non-flat range\") }\n return content.cut(0, from).append(content.cut(to))\n }\n if (index != indexTo) { throw new RangeError(\"Removing non-flat range\") }\n return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)))\n}\n\nfunction insertInto(content, dist, insert, parent) {\n var ref = content.findIndex(dist);\n var index = ref.index;\n var offset = ref.offset;\n var child = content.maybeChild(index);\n if (offset == dist || child.isText) {\n if (parent && !parent.canReplace(index, index, insert)) { return null }\n return content.cut(0, dist).append(insert).append(content.cut(dist))\n }\n var inner = insertInto(child.content, dist - offset - 1, insert);\n return inner && content.replaceChild(index, child.copy(inner))\n}\n\n// :: Slice\n// The empty slice.\nSlice.empty = new Slice(Fragment.empty, 0, 0);\n\nfunction replace($from, $to, slice) {\n if (slice.openStart > $from.depth)\n { throw new ReplaceError(\"Inserted content deeper than insertion position\") }\n if ($from.depth - slice.openStart != $to.depth - slice.openEnd)\n { throw new ReplaceError(\"Inconsistent open depths\") }\n return replaceOuter($from, $to, slice, 0)\n}\n\nfunction replaceOuter($from, $to, slice, depth) {\n var index = $from.index(depth), node = $from.node(depth);\n if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {\n var inner = replaceOuter($from, $to, slice, depth + 1);\n return node.copy(node.content.replaceChild(index, inner))\n } else if (!slice.content.size) {\n return close(node, replaceTwoWay($from, $to, depth))\n } else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case\n var parent = $from.parent, content = parent.content;\n return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)))\n } else {\n var ref = prepareSliceForReplace(slice, $from);\n var start = ref.start;\n var end = ref.end;\n return close(node, replaceThreeWay($from, start, end, $to, depth))\n }\n}\n\nfunction checkJoin(main, sub) {\n if (!sub.type.compatibleContent(main.type))\n { throw new ReplaceError(\"Cannot join \" + sub.type.name + \" onto \" + main.type.name) }\n}\n\nfunction joinable($before, $after, depth) {\n var node = $before.node(depth);\n checkJoin(node, $after.node(depth));\n return node\n}\n\nfunction addNode(child, target) {\n var last = target.length - 1;\n if (last >= 0 && child.isText && child.sameMarkup(target[last]))\n { target[last] = child.withText(target[last].text + child.text); }\n else\n { target.push(child); }\n}\n\nfunction addRange($start, $end, depth, target) {\n var node = ($end || $start).node(depth);\n var startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;\n if ($start) {\n startIndex = $start.index(depth);\n if ($start.depth > depth) {\n startIndex++;\n } else if ($start.textOffset) {\n addNode($start.nodeAfter, target);\n startIndex++;\n }\n }\n for (var i = startIndex; i < endIndex; i++) { addNode(node.child(i), target); }\n if ($end && $end.depth == depth && $end.textOffset)\n { addNode($end.nodeBefore, target); }\n}\n\nfunction close(node, content) {\n if (!node.type.validContent(content))\n { throw new ReplaceError(\"Invalid content for node \" + node.type.name) }\n return node.copy(content)\n}\n\nfunction replaceThreeWay($from, $start, $end, $to, depth) {\n var openStart = $from.depth > depth && joinable($from, $start, depth + 1);\n var openEnd = $to.depth > depth && joinable($end, $to, depth + 1);\n\n var content = [];\n addRange(null, $from, depth, content);\n if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {\n checkJoin(openStart, openEnd);\n addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);\n } else {\n if (openStart)\n { addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content); }\n addRange($start, $end, depth, content);\n if (openEnd)\n { addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content); }\n }\n addRange($to, null, depth, content);\n return new Fragment(content)\n}\n\nfunction replaceTwoWay($from, $to, depth) {\n var content = [];\n addRange(null, $from, depth, content);\n if ($from.depth > depth) {\n var type = joinable($from, $to, depth + 1);\n addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content)\n}\n\nfunction prepareSliceForReplace(slice, $along) {\n var extra = $along.depth - slice.openStart, parent = $along.node(extra);\n var node = parent.copy(slice.content);\n for (var i = extra - 1; i >= 0; i--)\n { node = $along.node(i).copy(Fragment.from(node)); }\n return {start: node.resolveNoCache(slice.openStart + extra),\n end: node.resolveNoCache(node.content.size - slice.openEnd - extra)}\n}\n\n// ::- You can [_resolve_](#model.Node.resolve) a position to get more\n// information about it. Objects of this class represent such a\n// resolved position, providing various pieces of context information,\n// and some helper methods.\n//\n// Throughout this interface, methods that take an optional `depth`\n// parameter will interpret undefined as `this.depth` and negative\n// numbers as `this.depth + value`.\nvar ResolvedPos = function ResolvedPos(pos, path, parentOffset) {\n // :: number The position that was resolved.\n this.pos = pos;\n this.path = path;\n // :: number\n // The number of levels the parent node is from the root. If this\n // position points directly into the root node, it is 0. If it\n // points into a top-level paragraph, 1, and so on.\n this.depth = path.length / 3 - 1;\n // :: number The offset this position has into its parent node.\n this.parentOffset = parentOffset;\n};\n\nvar prototypeAccessors$2 = { parent: { configurable: true },doc: { configurable: true },textOffset: { configurable: true },nodeAfter: { configurable: true },nodeBefore: { configurable: true } };\n\nResolvedPos.prototype.resolveDepth = function resolveDepth (val) {\n if (val == null) { return this.depth }\n if (val < 0) { return this.depth + val }\n return val\n};\n\n// :: Node\n// The parent node that the position points into. Note that even if\n// a position points into a text node, that node is not considered\n// the parent—text nodes are ‘flat’ in this model, and have no content.\nprototypeAccessors$2.parent.get = function () { return this.node(this.depth) };\n\n// :: Node\n// The root node in which the position was resolved.\nprototypeAccessors$2.doc.get = function () { return this.node(0) };\n\n// :: (?number) → Node\n// The ancestor node at the given level. `p.node(p.depth)` is the\n// same as `p.parent`.\nResolvedPos.prototype.node = function node (depth) { return this.path[this.resolveDepth(depth) * 3] };\n\n// :: (?number) → number\n// The index into the ancestor at the given level. If this points at\n// the 3rd node in the 2nd paragraph on the top level, for example,\n// `p.index(0)` is 1 and `p.index(1)` is 2.\nResolvedPos.prototype.index = function index (depth) { return this.path[this.resolveDepth(depth) * 3 + 1] };\n\n// :: (?number) → number\n// The index pointing after this position into the ancestor at the\n// given level.\nResolvedPos.prototype.indexAfter = function indexAfter (depth) {\n depth = this.resolveDepth(depth);\n return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1)\n};\n\n// :: (?number) → number\n// The (absolute) position at the start of the node at the given\n// level.\nResolvedPos.prototype.start = function start (depth) {\n depth = this.resolveDepth(depth);\n return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1\n};\n\n// :: (?number) → number\n// The (absolute) position at the end of the node at the given\n// level.\nResolvedPos.prototype.end = function end (depth) {\n depth = this.resolveDepth(depth);\n return this.start(depth) + this.node(depth).content.size\n};\n\n// :: (?number) → number\n// The (absolute) position directly before the wrapping node at the\n// given level, or, when `depth` is `this.depth + 1`, the original\n// position.\nResolvedPos.prototype.before = function before (depth) {\n depth = this.resolveDepth(depth);\n if (!depth) { throw new RangeError(\"There is no position before the top-level node\") }\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1]\n};\n\n// :: (?number) → number\n// The (absolute) position directly after the wrapping node at the\n// given level, or the original position when `depth` is `this.depth + 1`.\nResolvedPos.prototype.after = function after (depth) {\n depth = this.resolveDepth(depth);\n if (!depth) { throw new RangeError(\"There is no position after the top-level node\") }\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize\n};\n\n// :: number\n// When this position points into a text node, this returns the\n// distance between the position and the start of the text node.\n// Will be zero for positions that point between nodes.\nprototypeAccessors$2.textOffset.get = function () { return this.pos - this.path[this.path.length - 1] };\n\n// :: ?Node\n// Get the node directly after the position, if any. If the position\n// points into a text node, only the part of that node after the\n// position is returned.\nprototypeAccessors$2.nodeAfter.get = function () {\n var parent = this.parent, index = this.index(this.depth);\n if (index == parent.childCount) { return null }\n var dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);\n return dOff ? parent.child(index).cut(dOff) : child\n};\n\n// :: ?Node\n// Get the node directly before the position, if any. If the\n// position points into a text node, only the part of that node\n// before the position is returned.\nprototypeAccessors$2.nodeBefore.get = function () {\n var index = this.index(this.depth);\n var dOff = this.pos - this.path[this.path.length - 1];\n if (dOff) { return this.parent.child(index).cut(0, dOff) }\n return index == 0 ? null : this.parent.child(index - 1)\n};\n\n// :: (number, ?number) → number\n// Get the position at the given index in the parent node at the\n// given depth (which defaults to `this.depth`).\nResolvedPos.prototype.posAtIndex = function posAtIndex (index, depth) {\n depth = this.resolveDepth(depth);\n var node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n for (var i = 0; i < index; i++) { pos += node.child(i).nodeSize; }\n return pos\n};\n\n// :: () → [Mark]\n// Get the marks at this position, factoring in the surrounding\n// marks' [`inclusive`](#model.MarkSpec.inclusive) property. If the\n// position is at the start of a non-empty node, the marks of the\n// node after it (if any) are returned.\nResolvedPos.prototype.marks = function marks () {\n var parent = this.parent, index = this.index();\n\n // In an empty parent, return the empty array\n if (parent.content.size == 0) { return Mark.none }\n\n // When inside a text node, just return the text node's marks\n if (this.textOffset) { return parent.child(index).marks }\n\n var main = parent.maybeChild(index - 1), other = parent.maybeChild(index);\n // If the `after` flag is true of there is no node before, make\n // the node after this position the main reference.\n if (!main) { var tmp = main; main = other; other = tmp; }\n\n // Use all marks in the main node, except those that have\n // `inclusive` set to false and are not present in the other node.\n var marks = main.marks;\n for (var i = 0; i < marks.length; i++)\n { if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks)))\n { marks = marks[i--].removeFromSet(marks); } }\n\n return marks\n};\n\n// :: (ResolvedPos) → ?[Mark]\n// Get the marks after the current position, if any, except those\n// that are non-inclusive and not present at position `$end`. This\n// is mostly useful for getting the set of marks to preserve after a\n// deletion. Will return `null` if this position is at the end of\n// its parent node or its parent node isn't a textblock (in which\n// case no marks should be preserved).\nResolvedPos.prototype.marksAcross = function marksAcross ($end) {\n var after = this.parent.maybeChild(this.index());\n if (!after || !after.isInline) { return null }\n\n var marks = after.marks, next = $end.parent.maybeChild($end.index());\n for (var i = 0; i < marks.length; i++)\n { if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))\n { marks = marks[i--].removeFromSet(marks); } }\n return marks\n};\n\n// :: (number) → number\n// The depth up to which this position and the given (non-resolved)\n// position share the same parent nodes.\nResolvedPos.prototype.sharedDepth = function sharedDepth (pos) {\n for (var depth = this.depth; depth > 0; depth--)\n { if (this.start(depth) <= pos && this.end(depth) >= pos) { return depth } }\n return 0\n};\n\n// :: (?ResolvedPos, ?(Node) → bool) → ?NodeRange\n// Returns a range based on the place where this position and the\n// given position diverge around block content. If both point into\n// the same textblock, for example, a range around that textblock\n// will be returned. If they point into different blocks, the range\n// around those blocks in their shared ancestor is returned. You can\n// pass in an optional predicate that will be called with a parent\n// node to see if a range into that parent is acceptable.\nResolvedPos.prototype.blockRange = function blockRange (other, pred) {\n if ( other === void 0 ) other = this;\n\n if (other.pos < this.pos) { return other.blockRange(this) }\n for (var d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)\n { if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))\n { return new NodeRange(this, other, d) } }\n};\n\n// :: (ResolvedPos) → bool\n// Query whether the given position shares the same parent node.\nResolvedPos.prototype.sameParent = function sameParent (other) {\n return this.pos - this.parentOffset == other.pos - other.parentOffset\n};\n\n// :: (ResolvedPos) → ResolvedPos\n// Return the greater of this and the given position.\nResolvedPos.prototype.max = function max (other) {\n return other.pos > this.pos ? other : this\n};\n\n// :: (ResolvedPos) → ResolvedPos\n// Return the smaller of this and the given position.\nResolvedPos.prototype.min = function min (other) {\n return other.pos < this.pos ? other : this\n};\n\nResolvedPos.prototype.toString = function toString () {\n var str = \"\";\n for (var i = 1; i <= this.depth; i++)\n { str += (str ? \"/\" : \"\") + this.node(i).type.name + \"_\" + this.index(i - 1); }\n return str + \":\" + this.parentOffset\n};\n\nResolvedPos.resolve = function resolve (doc, pos) {\n if (!(pos >= 0 && pos <= doc.content.size)) { throw new RangeError(\"Position \" + pos + \" out of range\") }\n var path = [];\n var start = 0, parentOffset = pos;\n for (var node = doc;;) {\n var ref = node.content.findIndex(parentOffset);\n var index = ref.index;\n var offset = ref.offset;\n var rem = parentOffset - offset;\n path.push(node, index, start + offset);\n if (!rem) { break }\n node = node.child(index);\n if (node.isText) { break }\n parentOffset = rem - 1;\n start += offset + 1;\n }\n return new ResolvedPos(pos, path, parentOffset)\n};\n\nResolvedPos.resolveCached = function resolveCached (doc, pos) {\n for (var i = 0; i < resolveCache.length; i++) {\n var cached = resolveCache[i];\n if (cached.pos == pos && cached.doc == doc) { return cached }\n }\n var result = resolveCache[resolveCachePos] = ResolvedPos.resolve(doc, pos);\n resolveCachePos = (resolveCachePos + 1) % resolveCacheSize;\n return result\n};\n\nObject.defineProperties( ResolvedPos.prototype, prototypeAccessors$2 );\n\nvar resolveCache = [], resolveCachePos = 0, resolveCacheSize = 12;\n\n// ::- Represents a flat range of content, i.e. one that starts and\n// ends in the same node.\nvar NodeRange = function NodeRange($from, $to, depth) {\n // :: ResolvedPos A resolved position along the start of the\n // content. May have a `depth` greater than this object's `depth`\n // property, since these are the positions that were used to\n // compute the range, not re-resolved positions directly at its\n // boundaries.\n this.$from = $from;\n // :: ResolvedPos A position along the end of the content. See\n // caveat for [`$from`](#model.NodeRange.$from).\n this.$to = $to;\n // :: number The depth of the node that this range points into.\n this.depth = depth;\n};\n\nvar prototypeAccessors$1$1 = { start: { configurable: true },end: { configurable: true },parent: { configurable: true },startIndex: { configurable: true },endIndex: { configurable: true } };\n\n// :: number The position at the start of the range.\nprototypeAccessors$1$1.start.get = function () { return this.$from.before(this.depth + 1) };\n// :: number The position at the end of the range.\nprototypeAccessors$1$1.end.get = function () { return this.$to.after(this.depth + 1) };\n\n// :: Node The parent node that the range points into.\nprototypeAccessors$1$1.parent.get = function () { return this.$from.node(this.depth) };\n// :: number The start index of the range in the parent node.\nprototypeAccessors$1$1.startIndex.get = function () { return this.$from.index(this.depth) };\n// :: number The end index of the range in the parent node.\nprototypeAccessors$1$1.endIndex.get = function () { return this.$to.indexAfter(this.depth) };\n\nObject.defineProperties( NodeRange.prototype, prototypeAccessors$1$1 );\n\nvar emptyAttrs = Object.create(null);\n\n// ::- This class represents a node in the tree that makes up a\n// ProseMirror document. So a document is an instance of `Node`, with\n// children that are also instances of `Node`.\n//\n// Nodes are persistent data structures. Instead of changing them, you\n// create new ones with the content you want. Old ones keep pointing\n// at the old document shape. This is made cheaper by sharing\n// structure between the old and new data as much as possible, which a\n// tree shape like this (without back pointers) makes easy.\n//\n// **Do not** directly mutate the properties of a `Node` object. See\n// [the guide](/docs/guide/#doc) for more information.\nvar Node = function Node(type, attrs, content, marks) {\n // :: NodeType\n // The type of node that this is.\n this.type = type;\n\n // :: Object\n // An object mapping attribute names to values. The kind of\n // attributes allowed and required are\n // [determined](#model.NodeSpec.attrs) by the node type.\n this.attrs = attrs;\n\n // :: Fragment\n // A container holding the node's children.\n this.content = content || Fragment.empty;\n\n // :: [Mark]\n // The marks (things like whether it is emphasized or part of a\n // link) applied to this node.\n this.marks = marks || Mark.none;\n};\n\nvar prototypeAccessors$3 = { nodeSize: { configurable: true },childCount: { configurable: true },textContent: { configurable: true },firstChild: { configurable: true },lastChild: { configurable: true },isBlock: { configurable: true },isTextblock: { configurable: true },inlineContent: { configurable: true },isInline: { configurable: true },isText: { configurable: true },isLeaf: { configurable: true },isAtom: { configurable: true } };\n\n// text:: ?string\n// For text nodes, this contains the node's text content.\n\n// :: number\n// The size of this node, as defined by the integer-based [indexing\n// scheme](/docs/guide/#doc.indexing). For text nodes, this is the\n// amount of characters. For other leaf nodes, it is one. For\n// non-leaf nodes, it is the size of the content plus two (the start\n// and end token).\nprototypeAccessors$3.nodeSize.get = function () { return this.isLeaf ? 1 : 2 + this.content.size };\n\n// :: number\n// The number of children that the node has.\nprototypeAccessors$3.childCount.get = function () { return this.content.childCount };\n\n// :: (number) → Node\n// Get the child node at the given index. Raises an error when the\n// index is out of range.\nNode.prototype.child = function child (index) { return this.content.child(index) };\n\n// :: (number) → ?Node\n// Get the child node at the given index, if it exists.\nNode.prototype.maybeChild = function maybeChild (index) { return this.content.maybeChild(index) };\n\n// :: ((node: Node, offset: number, index: number))\n// Call `f` for every child node, passing the node, its offset\n// into this parent node, and its index.\nNode.prototype.forEach = function forEach (f) { this.content.forEach(f); };\n\n// :: (number, number, (node: Node, pos: number, parent: Node, index: number) → ?bool, ?number)\n// Invoke a callback for all descendant nodes recursively between\n// the given two positions that are relative to start of this node's\n// content. The callback is invoked with the node, its\n// parent-relative position, its parent node, and its child index.\n// When the callback returns false for a given node, that node's\n// children will not be recursed over. The last parameter can be\n// used to specify a starting position to count from.\nNode.prototype.nodesBetween = function nodesBetween (from, to, f, startPos) {\n if ( startPos === void 0 ) startPos = 0;\n\n this.content.nodesBetween(from, to, f, startPos, this);\n};\n\n// :: ((node: Node, pos: number, parent: Node) → ?bool)\n// Call the given callback for every descendant node. Doesn't\n// descend into a node when the callback returns `false`.\nNode.prototype.descendants = function descendants (f) {\n this.nodesBetween(0, this.content.size, f);\n};\n\n// :: string\n// Concatenates all the text nodes found in this fragment and its\n// children.\nprototypeAccessors$3.textContent.get = function () { return this.textBetween(0, this.content.size, \"\") };\n\n// :: (number, number, ?string, ?string) → string\n// Get all text between positions `from` and `to`. When\n// `blockSeparator` is given, it will be inserted whenever a new\n// block node is started. When `leafText` is given, it'll be\n// inserted for every non-text leaf node encountered.\nNode.prototype.textBetween = function textBetween (from, to, blockSeparator, leafText) {\n return this.content.textBetween(from, to, blockSeparator, leafText)\n};\n\n// :: ?Node\n// Returns this node's first child, or `null` if there are no\n// children.\nprototypeAccessors$3.firstChild.get = function () { return this.content.firstChild };\n\n// :: ?Node\n// Returns this node's last child, or `null` if there are no\n// children.\nprototypeAccessors$3.lastChild.get = function () { return this.content.lastChild };\n\n// :: (Node) → bool\n// Test whether two nodes represent the same piece of document.\nNode.prototype.eq = function eq (other) {\n return this == other || (this.sameMarkup(other) && this.content.eq(other.content))\n};\n\n// :: (Node) → bool\n// Compare the markup (type, attributes, and marks) of this node to\n// those of another. Returns `true` if both have the same markup.\nNode.prototype.sameMarkup = function sameMarkup (other) {\n return this.hasMarkup(other.type, other.attrs, other.marks)\n};\n\n// :: (NodeType, ?Object, ?[Mark]) → bool\n// Check whether this node's markup correspond to the given type,\n// attributes, and marks.\nNode.prototype.hasMarkup = function hasMarkup (type, attrs, marks) {\n return this.type == type &&\n compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) &&\n Mark.sameSet(this.marks, marks || Mark.none)\n};\n\n// :: (?Fragment) → Node\n// Create a new node with the same markup as this node, containing\n// the given content (or empty, if no content is given).\nNode.prototype.copy = function copy (content) {\n if ( content === void 0 ) content = null;\n\n if (content == this.content) { return this }\n return new this.constructor(this.type, this.attrs, content, this.marks)\n};\n\n// :: ([Mark]) → Node\n// Create a copy of this node, with the given set of marks instead\n// of the node's own marks.\nNode.prototype.mark = function mark (marks) {\n return marks == this.marks ? this : new this.constructor(this.type, this.attrs, this.content, marks)\n};\n\n// :: (number, ?number) → Node\n// Create a copy of this node with only the content between the\n// given positions. If `to` is not given, it defaults to the end of\n// the node.\nNode.prototype.cut = function cut (from, to) {\n if (from == 0 && to == this.content.size) { return this }\n return this.copy(this.content.cut(from, to))\n};\n\n// :: (number, ?number) → Slice\n// Cut out the part of the document between the given positions, and\n// return it as a `Slice` object.\nNode.prototype.slice = function slice (from, to, includeParents) {\n if ( to === void 0 ) to = this.content.size;\n if ( includeParents === void 0 ) includeParents = false;\n\n if (from == to) { return Slice.empty }\n\n var $from = this.resolve(from), $to = this.resolve(to);\n var depth = includeParents ? 0 : $from.sharedDepth(to);\n var start = $from.start(depth), node = $from.node(depth);\n var content = node.content.cut($from.pos - start, $to.pos - start);\n return new Slice(content, $from.depth - depth, $to.depth - depth)\n};\n\n// :: (number, number, Slice) → Node\n// Replace the part of the document between the given positions with\n// the given slice. The slice must 'fit', meaning its open sides\n// must be able to connect to the surrounding content, and its\n// content nodes must be valid children for the node they are placed\n// into. If any of this is violated, an error of type\n// [`ReplaceError`](#model.ReplaceError) is thrown.\nNode.prototype.replace = function replace$1 (from, to, slice) {\n return replace(this.resolve(from), this.resolve(to), slice)\n};\n\n// :: (number) → ?Node\n// Find the node directly after the given position.\nNode.prototype.nodeAt = function nodeAt (pos) {\n for (var node = this;;) {\n var ref = node.content.findIndex(pos);\n var index = ref.index;\n var offset = ref.offset;\n node = node.maybeChild(index);\n if (!node) { return null }\n if (offset == pos || node.isText) { return node }\n pos -= offset + 1;\n }\n};\n\n// :: (number) → {node: ?Node, index: number, offset: number}\n// Find the (direct) child node after the given offset, if any,\n// and return it along with its index and offset relative to this\n// node.\nNode.prototype.childAfter = function childAfter (pos) {\n var ref = this.content.findIndex(pos);\n var index = ref.index;\n var offset = ref.offset;\n return {node: this.content.maybeChild(index), index: index, offset: offset}\n};\n\n// :: (number) → {node: ?Node, index: number, offset: number}\n// Find the (direct) child node before the given offset, if any,\n// and return it along with its index and offset relative to this\n// node.\nNode.prototype.childBefore = function childBefore (pos) {\n if (pos == 0) { return {node: null, index: 0, offset: 0} }\n var ref = this.content.findIndex(pos);\n var index = ref.index;\n var offset = ref.offset;\n if (offset < pos) { return {node: this.content.child(index), index: index, offset: offset} }\n var node = this.content.child(index - 1);\n return {node: node, index: index - 1, offset: offset - node.nodeSize}\n};\n\n// :: (number) → ResolvedPos\n// Resolve the given position in the document, returning an\n// [object](#model.ResolvedPos) with information about its context.\nNode.prototype.resolve = function resolve (pos) { return ResolvedPos.resolveCached(this, pos) };\n\nNode.prototype.resolveNoCache = function resolveNoCache (pos) { return ResolvedPos.resolve(this, pos) };\n\n// :: (number, number, union) → bool\n// Test whether a given mark or mark type occurs in this document\n// between the two given positions.\nNode.prototype.rangeHasMark = function rangeHasMark (from, to, type) {\n var found = false;\n if (to > from) { this.nodesBetween(from, to, function (node) {\n if (type.isInSet(node.marks)) { found = true; }\n return !found\n }); }\n return found\n};\n\n// :: bool\n// True when this is a block (non-inline node)\nprototypeAccessors$3.isBlock.get = function () { return this.type.isBlock };\n\n// :: bool\n// True when this is a textblock node, a block node with inline\n// content.\nprototypeAccessors$3.isTextblock.get = function () { return this.type.isTextblock };\n\n// :: bool\n// True when this node allows inline content.\nprototypeAccessors$3.inlineContent.get = function () { return this.type.inlineContent };\n\n// :: bool\n// True when this is an inline node (a text node or a node that can\n// appear among text).\nprototypeAccessors$3.isInline.get = function () { return this.type.isInline };\n\n// :: bool\n// True when this is a text node.\nprototypeAccessors$3.isText.get = function () { return this.type.isText };\n\n// :: bool\n// True when this is a leaf node.\nprototypeAccessors$3.isLeaf.get = function () { return this.type.isLeaf };\n\n// :: bool\n// True when this is an atom, i.e. when it does not have directly\n// editable content. This is usually the same as `isLeaf`, but can\n// be configured with the [`atom` property](#model.NodeSpec.atom) on\n// a node's spec (typically used when the node is displayed as an\n// uneditable [node view](#view.NodeView)).\nprototypeAccessors$3.isAtom.get = function () { return this.type.isAtom };\n\n// :: () → string\n// Return a string representation of this node for debugging\n// purposes.\nNode.prototype.toString = function toString () {\n if (this.type.spec.toDebugString) { return this.type.spec.toDebugString(this) }\n var name = this.type.name;\n if (this.content.size)\n { name += \"(\" + this.content.toStringInner() + \")\"; }\n return wrapMarks(this.marks, name)\n};\n\n// :: (number) → ContentMatch\n// Get the content match in this node at the given index.\nNode.prototype.contentMatchAt = function contentMatchAt (index) {\n var match = this.type.contentMatch.matchFragment(this.content, 0, index);\n if (!match) { throw new Error(\"Called contentMatchAt on a node with invalid content\") }\n return match\n};\n\n// :: (number, number, ?Fragment, ?number, ?number) → bool\n// Test whether replacing the range between `from` and `to` (by\n// child index) with the given replacement fragment (which defaults\n// to the empty fragment) would leave the node's content valid. You\n// can optionally pass `start` and `end` indices into the\n// replacement fragment.\nNode.prototype.canReplace = function canReplace (from, to, replacement, start, end) {\n if ( replacement === void 0 ) replacement = Fragment.empty;\n if ( start === void 0 ) start = 0;\n if ( end === void 0 ) end = replacement.childCount;\n\n var one = this.contentMatchAt(from).matchFragment(replacement, start, end);\n var two = one && one.matchFragment(this.content, to);\n if (!two || !two.validEnd) { return false }\n for (var i = start; i < end; i++) { if (!this.type.allowsMarks(replacement.child(i).marks)) { return false } }\n return true\n};\n\n// :: (number, number, NodeType, ?[Mark]) → bool\n// Test whether replacing the range `from` to `to` (by index) with a\n// node of the given type would leave the node's content valid.\nNode.prototype.canReplaceWith = function canReplaceWith (from, to, type, marks) {\n if (marks && !this.type.allowsMarks(marks)) { return false }\n var start = this.contentMatchAt(from).matchType(type);\n var end = start && start.matchFragment(this.content, to);\n return end ? end.validEnd : false\n};\n\n// :: (Node) → bool\n// Test whether the given node's content could be appended to this\n// node. If that node is empty, this will only return true if there\n// is at least one node type that can appear in both nodes (to avoid\n// merging completely incompatible nodes).\nNode.prototype.canAppend = function canAppend (other) {\n if (other.content.size) { return this.canReplace(this.childCount, this.childCount, other.content) }\n else { return this.type.compatibleContent(other.type) }\n};\n\n// :: ()\n// Check whether this node and its descendants conform to the\n// schema, and raise error when they do not.\nNode.prototype.check = function check () {\n if (!this.type.validContent(this.content))\n { throw new RangeError((\"Invalid content for node \" + (this.type.name) + \": \" + (this.content.toString().slice(0, 50)))) }\n this.content.forEach(function (node) { return node.check(); });\n};\n\n// :: () → Object\n// Return a JSON-serializeable representation of this node.\nNode.prototype.toJSON = function toJSON () {\n var obj = {type: this.type.name};\n for (var _ in this.attrs) {\n obj.attrs = this.attrs;\n break\n }\n if (this.content.size)\n { obj.content = this.content.toJSON(); }\n if (this.marks.length)\n { obj.marks = this.marks.map(function (n) { return n.toJSON(); }); }\n return obj\n};\n\n// :: (Schema, Object) → Node\n// Deserialize a node from its JSON representation.\nNode.fromJSON = function fromJSON (schema, json) {\n if (!json) { throw new RangeError(\"Invalid input for Node.fromJSON\") }\n var marks = null;\n if (json.marks) {\n if (!Array.isArray(json.marks)) { throw new RangeError(\"Invalid mark data for Node.fromJSON\") }\n marks = json.marks.map(schema.markFromJSON);\n }\n if (json.type == \"text\") {\n if (typeof json.text != \"string\") { throw new RangeError(\"Invalid text node in JSON\") }\n return schema.text(json.text, marks)\n }\n var content = Fragment.fromJSON(schema, json.content);\n return schema.nodeType(json.type).create(json.attrs, content, marks)\n};\n\nObject.defineProperties( Node.prototype, prototypeAccessors$3 );\n\nvar TextNode = /*@__PURE__*/(function (Node) {\n function TextNode(type, attrs, content, marks) {\n Node.call(this, type, attrs, null, marks);\n\n if (!content) { throw new RangeError(\"Empty text nodes are not allowed\") }\n\n this.text = content;\n }\n\n if ( Node ) TextNode.__proto__ = Node;\n TextNode.prototype = Object.create( Node && Node.prototype );\n TextNode.prototype.constructor = TextNode;\n\n var prototypeAccessors$1 = { textContent: { configurable: true },nodeSize: { configurable: true } };\n\n TextNode.prototype.toString = function toString () {\n if (this.type.spec.toDebugString) { return this.type.spec.toDebugString(this) }\n return wrapMarks(this.marks, JSON.stringify(this.text))\n };\n\n prototypeAccessors$1.textContent.get = function () { return this.text };\n\n TextNode.prototype.textBetween = function textBetween (from, to) { return this.text.slice(from, to) };\n\n prototypeAccessors$1.nodeSize.get = function () { return this.text.length };\n\n TextNode.prototype.mark = function mark (marks) {\n return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks)\n };\n\n TextNode.prototype.withText = function withText (text) {\n if (text == this.text) { return this }\n return new TextNode(this.type, this.attrs, text, this.marks)\n };\n\n TextNode.prototype.cut = function cut (from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.text.length;\n\n if (from == 0 && to == this.text.length) { return this }\n return this.withText(this.text.slice(from, to))\n };\n\n TextNode.prototype.eq = function eq (other) {\n return this.sameMarkup(other) && this.text == other.text\n };\n\n TextNode.prototype.toJSON = function toJSON () {\n var base = Node.prototype.toJSON.call(this);\n base.text = this.text;\n return base\n };\n\n Object.defineProperties( TextNode.prototype, prototypeAccessors$1 );\n\n return TextNode;\n}(Node));\n\nfunction wrapMarks(marks, str) {\n for (var i = marks.length - 1; i >= 0; i--)\n { str = marks[i].type.name + \"(\" + str + \")\"; }\n return str\n}\n\n// ::- Instances of this class represent a match state of a node\n// type's [content expression](#model.NodeSpec.content), and can be\n// used to find out whether further content matches here, and whether\n// a given position is a valid end of the node.\nvar ContentMatch = function ContentMatch(validEnd) {\n // :: bool\n // True when this match state represents a valid end of the node.\n this.validEnd = validEnd;\n this.next = [];\n this.wrapCache = [];\n};\n\nvar prototypeAccessors$4 = { inlineContent: { configurable: true },defaultType: { configurable: true },edgeCount: { configurable: true } };\n\nContentMatch.parse = function parse (string, nodeTypes) {\n var stream = new TokenStream(string, nodeTypes);\n if (stream.next == null) { return ContentMatch.empty }\n var expr = parseExpr(stream);\n if (stream.next) { stream.err(\"Unexpected trailing text\"); }\n var match = dfa(nfa(expr));\n checkForDeadEnds(match, stream);\n return match\n};\n\n// :: (NodeType) → ?ContentMatch\n// Match a node type, returning a match after that node if\n// successful.\nContentMatch.prototype.matchType = function matchType (type) {\n for (var i = 0; i < this.next.length; i += 2)\n { if (this.next[i] == type) { return this.next[i + 1] } }\n return null\n};\n\n// :: (Fragment, ?number, ?number) → ?ContentMatch\n// Try to match a fragment. Returns the resulting match when\n// successful.\nContentMatch.prototype.matchFragment = function matchFragment (frag, start, end) {\n if ( start === void 0 ) start = 0;\n if ( end === void 0 ) end = frag.childCount;\n\n var cur = this;\n for (var i = start; cur && i < end; i++)\n { cur = cur.matchType(frag.child(i).type); }\n return cur\n};\n\nprototypeAccessors$4.inlineContent.get = function () {\n var first = this.next[0];\n return first ? first.isInline : false\n};\n\n// :: ?NodeType\n// Get the first matching node type at this match position that can\n// be generated.\nprototypeAccessors$4.defaultType.get = function () {\n for (var i = 0; i < this.next.length; i += 2) {\n var type = this.next[i];\n if (!(type.isText || type.hasRequiredAttrs())) { return type }\n }\n};\n\nContentMatch.prototype.compatible = function compatible (other) {\n for (var i = 0; i < this.next.length; i += 2)\n { for (var j = 0; j < other.next.length; j += 2)\n { if (this.next[i] == other.next[j]) { return true } } }\n return false\n};\n\n// :: (Fragment, bool, ?number) → ?Fragment\n// Try to match the given fragment, and if that fails, see if it can\n// be made to match by inserting nodes in front of it. When\n// successful, return a fragment of inserted nodes (which may be\n// empty if nothing had to be inserted). When `toEnd` is true, only\n// return a fragment if the resulting match goes to the end of the\n// content expression.\nContentMatch.prototype.fillBefore = function fillBefore (after, toEnd, startIndex) {\n if ( toEnd === void 0 ) toEnd = false;\n if ( startIndex === void 0 ) startIndex = 0;\n\n var seen = [this];\n function search(match, types) {\n var finished = match.matchFragment(after, startIndex);\n if (finished && (!toEnd || finished.validEnd))\n { return Fragment.from(types.map(function (tp) { return tp.createAndFill(); })) }\n\n for (var i = 0; i < match.next.length; i += 2) {\n var type = match.next[i], next = match.next[i + 1];\n if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {\n seen.push(next);\n var found = search(next, types.concat(type));\n if (found) { return found }\n }\n }\n }\n\n return search(this, [])\n};\n\n// :: (NodeType) → ?[NodeType]\n// Find a set of wrapping node types that would allow a node of the\n// given type to appear at this position. The result may be empty\n// (when it fits directly) and will be null when no such wrapping\n// exists.\nContentMatch.prototype.findWrapping = function findWrapping (target) {\n for (var i = 0; i < this.wrapCache.length; i += 2)\n { if (this.wrapCache[i] == target) { return this.wrapCache[i + 1] } }\n var computed = this.computeWrapping(target);\n this.wrapCache.push(target, computed);\n return computed\n};\n\nContentMatch.prototype.computeWrapping = function computeWrapping (target) {\n var seen = Object.create(null), active = [{match: this, type: null, via: null}];\n while (active.length) {\n var current = active.shift(), match = current.match;\n if (match.matchType(target)) {\n var result = [];\n for (var obj = current; obj.type; obj = obj.via)\n { result.push(obj.type); }\n return result.reverse()\n }\n for (var i = 0; i < match.next.length; i += 2) {\n var type = match.next[i];\n if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || match.next[i + 1].validEnd)) {\n active.push({match: type.contentMatch, type: type, via: current});\n seen[type.name] = true;\n }\n }\n }\n};\n\n// :: number\n// The number of outgoing edges this node has in the finite\n// automaton that describes the content expression.\nprototypeAccessors$4.edgeCount.get = function () {\n return this.next.length >> 1\n};\n\n// :: (number) → {type: NodeType, next: ContentMatch}\n// Get the _n_​th outgoing edge from this node in the finite\n// automaton that describes the content expression.\nContentMatch.prototype.edge = function edge (n) {\n var i = n << 1;\n if (i >= this.next.length) { throw new RangeError((\"There's no \" + n + \"th edge in this content match\")) }\n return {type: this.next[i], next: this.next[i + 1]}\n};\n\nContentMatch.prototype.toString = function toString () {\n var seen = [];\n function scan(m) {\n seen.push(m);\n for (var i = 1; i < m.next.length; i += 2)\n { if (seen.indexOf(m.next[i]) == -1) { scan(m.next[i]); } }\n }\n scan(this);\n return seen.map(function (m, i) {\n var out = i + (m.validEnd ? \"*\" : \" \") + \" \";\n for (var i$1 = 0; i$1 < m.next.length; i$1 += 2)\n { out += (i$1 ? \", \" : \"\") + m.next[i$1].name + \"->\" + seen.indexOf(m.next[i$1 + 1]); }\n return out\n }).join(\"\\n\")\n};\n\nObject.defineProperties( ContentMatch.prototype, prototypeAccessors$4 );\n\nContentMatch.empty = new ContentMatch(true);\n\nvar TokenStream = function TokenStream(string, nodeTypes) {\n this.string = string;\n this.nodeTypes = nodeTypes;\n this.inline = null;\n this.pos = 0;\n this.tokens = string.split(/\\s*(?=\\b|\\W|$)/);\n if (this.tokens[this.tokens.length - 1] == \"\") { this.tokens.pop(); }\n if (this.tokens[0] == \"\") { this.tokens.unshift(); }\n};\n\nvar prototypeAccessors$1$2 = { next: { configurable: true } };\n\nprototypeAccessors$1$2.next.get = function () { return this.tokens[this.pos] };\n\nTokenStream.prototype.eat = function eat (tok) { return this.next == tok && (this.pos++ || true) };\n\nTokenStream.prototype.err = function err (str) { throw new SyntaxError(str + \" (in content expression '\" + this.string + \"')\") };\n\nObject.defineProperties( TokenStream.prototype, prototypeAccessors$1$2 );\n\nfunction parseExpr(stream) {\n var exprs = [];\n do { exprs.push(parseExprSeq(stream)); }\n while (stream.eat(\"|\"))\n return exprs.length == 1 ? exprs[0] : {type: \"choice\", exprs: exprs}\n}\n\nfunction parseExprSeq(stream) {\n var exprs = [];\n do { exprs.push(parseExprSubscript(stream)); }\n while (stream.next && stream.next != \")\" && stream.next != \"|\")\n return exprs.length == 1 ? exprs[0] : {type: \"seq\", exprs: exprs}\n}\n\nfunction parseExprSubscript(stream) {\n var expr = parseExprAtom(stream);\n for (;;) {\n if (stream.eat(\"+\"))\n { expr = {type: \"plus\", expr: expr}; }\n else if (stream.eat(\"*\"))\n { expr = {type: \"star\", expr: expr}; }\n else if (stream.eat(\"?\"))\n { expr = {type: \"opt\", expr: expr}; }\n else if (stream.eat(\"{\"))\n { expr = parseExprRange(stream, expr); }\n else { break }\n }\n return expr\n}\n\nfunction parseNum(stream) {\n if (/\\D/.test(stream.next)) { stream.err(\"Expected number, got '\" + stream.next + \"'\"); }\n var result = Number(stream.next);\n stream.pos++;\n return result\n}\n\nfunction parseExprRange(stream, expr) {\n var min = parseNum(stream), max = min;\n if (stream.eat(\",\")) {\n if (stream.next != \"}\") { max = parseNum(stream); }\n else { max = -1; }\n }\n if (!stream.eat(\"}\")) { stream.err(\"Unclosed braced range\"); }\n return {type: \"range\", min: min, max: max, expr: expr}\n}\n\nfunction resolveName(stream, name) {\n var types = stream.nodeTypes, type = types[name];\n if (type) { return [type] }\n var result = [];\n for (var typeName in types) {\n var type$1 = types[typeName];\n if (type$1.groups.indexOf(name) > -1) { result.push(type$1); }\n }\n if (result.length == 0) { stream.err(\"No node type or group '\" + name + \"' found\"); }\n return result\n}\n\nfunction parseExprAtom(stream) {\n if (stream.eat(\"(\")) {\n var expr = parseExpr(stream);\n if (!stream.eat(\")\")) { stream.err(\"Missing closing paren\"); }\n return expr\n } else if (!/\\W/.test(stream.next)) {\n var exprs = resolveName(stream, stream.next).map(function (type) {\n if (stream.inline == null) { stream.inline = type.isInline; }\n else if (stream.inline != type.isInline) { stream.err(\"Mixing inline and block content\"); }\n return {type: \"name\", value: type}\n });\n stream.pos++;\n return exprs.length == 1 ? exprs[0] : {type: \"choice\", exprs: exprs}\n } else {\n stream.err(\"Unexpected token '\" + stream.next + \"'\");\n }\n}\n\n// The code below helps compile a regular-expression-like language\n// into a deterministic finite automaton. For a good introduction to\n// these concepts, see https://swtch.com/~rsc/regexp/regexp1.html\n\n// : (Object) → [[{term: ?any, to: number}]]\n// Construct an NFA from an expression as returned by the parser. The\n// NFA is represented as an array of states, which are themselves\n// arrays of edges, which are `{term, to}` objects. The first state is\n// the entry state and the last node is the success state.\n//\n// Note that unlike typical NFAs, the edge ordering in this one is\n// significant, in that it is used to contruct filler content when\n// necessary.\nfunction nfa(expr) {\n var nfa = [[]];\n connect(compile(expr, 0), node());\n return nfa\n\n function node() { return nfa.push([]) - 1 }\n function edge(from, to, term) {\n var edge = {term: term, to: to};\n nfa[from].push(edge);\n return edge\n }\n function connect(edges, to) { edges.forEach(function (edge) { return edge.to = to; }); }\n\n function compile(expr, from) {\n if (expr.type == \"choice\") {\n return expr.exprs.reduce(function (out, expr) { return out.concat(compile(expr, from)); }, [])\n } else if (expr.type == \"seq\") {\n for (var i = 0;; i++) {\n var next = compile(expr.exprs[i], from);\n if (i == expr.exprs.length - 1) { return next }\n connect(next, from = node());\n }\n } else if (expr.type == \"star\") {\n var loop = node();\n edge(from, loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)]\n } else if (expr.type == \"plus\") {\n var loop$1 = node();\n connect(compile(expr.expr, from), loop$1);\n connect(compile(expr.expr, loop$1), loop$1);\n return [edge(loop$1)]\n } else if (expr.type == \"opt\") {\n return [edge(from)].concat(compile(expr.expr, from))\n } else if (expr.type == \"range\") {\n var cur = from;\n for (var i$1 = 0; i$1 < expr.min; i$1++) {\n var next$1 = node();\n connect(compile(expr.expr, cur), next$1);\n cur = next$1;\n }\n if (expr.max == -1) {\n connect(compile(expr.expr, cur), cur);\n } else {\n for (var i$2 = expr.min; i$2 < expr.max; i$2++) {\n var next$2 = node();\n edge(cur, next$2);\n connect(compile(expr.expr, cur), next$2);\n cur = next$2;\n }\n }\n return [edge(cur)]\n } else if (expr.type == \"name\") {\n return [edge(from, null, expr.value)]\n }\n }\n}\n\nfunction cmp(a, b) { return b - a }\n\n// Get the set of nodes reachable by null edges from `node`. Omit\n// nodes with only a single null-out-edge, since they may lead to\n// needless duplicated nodes.\nfunction nullFrom(nfa, node) {\n var result = [];\n scan(node);\n return result.sort(cmp)\n\n function scan(node) {\n var edges = nfa[node];\n if (edges.length == 1 && !edges[0].term) { return scan(edges[0].to) }\n result.push(node);\n for (var i = 0; i < edges.length; i++) {\n var ref = edges[i];\n var term = ref.term;\n var to = ref.to;\n if (!term && result.indexOf(to) == -1) { scan(to); }\n }\n }\n}\n\n// : ([[{term: ?any, to: number}]]) → ContentMatch\n// Compiles an NFA as produced by `nfa` into a DFA, modeled as a set\n// of state objects (`ContentMatch` instances) with transitions\n// between them.\nfunction dfa(nfa) {\n var labeled = Object.create(null);\n return explore(nullFrom(nfa, 0))\n\n function explore(states) {\n var out = [];\n states.forEach(function (node) {\n nfa[node].forEach(function (ref) {\n var term = ref.term;\n var to = ref.to;\n\n if (!term) { return }\n var known = out.indexOf(term), set = known > -1 && out[known + 1];\n nullFrom(nfa, to).forEach(function (node) {\n if (!set) { out.push(term, set = []); }\n if (set.indexOf(node) == -1) { set.push(node); }\n });\n });\n });\n var state = labeled[states.join(\",\")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1);\n for (var i = 0; i < out.length; i += 2) {\n var states$1 = out[i + 1].sort(cmp);\n state.next.push(out[i], labeled[states$1.join(\",\")] || explore(states$1));\n }\n return state\n }\n}\n\nfunction checkForDeadEnds(match, stream) {\n for (var i = 0, work = [match]; i < work.length; i++) {\n var state = work[i], dead = !state.validEnd, nodes = [];\n for (var j = 0; j < state.next.length; j += 2) {\n var node = state.next[j], next = state.next[j + 1];\n nodes.push(node.name);\n if (dead && !(node.isText || node.hasRequiredAttrs())) { dead = false; }\n if (work.indexOf(next) == -1) { work.push(next); }\n }\n if (dead) { stream.err(\"Only non-generatable nodes (\" + nodes.join(\", \") + \") in a required position (see https://prosemirror.net/docs/guide/#generatable)\"); }\n }\n}\n\n// For node types where all attrs have a default value (or which don't\n// have any attributes), build up a single reusable default attribute\n// object, and use it for all nodes that don't specify specific\n// attributes.\nfunction defaultAttrs(attrs) {\n var defaults = Object.create(null);\n for (var attrName in attrs) {\n var attr = attrs[attrName];\n if (!attr.hasDefault) { return null }\n defaults[attrName] = attr.default;\n }\n return defaults\n}\n\nfunction computeAttrs(attrs, value) {\n var built = Object.create(null);\n for (var name in attrs) {\n var given = value && value[name];\n if (given === undefined) {\n var attr = attrs[name];\n if (attr.hasDefault) { given = attr.default; }\n else { throw new RangeError(\"No value supplied for attribute \" + name) }\n }\n built[name] = given;\n }\n return built\n}\n\nfunction initAttrs(attrs) {\n var result = Object.create(null);\n if (attrs) { for (var name in attrs) { result[name] = new Attribute(attrs[name]); } }\n return result\n}\n\n// ::- Node types are objects allocated once per `Schema` and used to\n// [tag](#model.Node.type) `Node` instances. They contain information\n// about the node type, such as its name and what kind of node it\n// represents.\nvar NodeType = function NodeType(name, schema, spec) {\n // :: string\n // The name the node type has in this schema.\n this.name = name;\n\n // :: Schema\n // A link back to the `Schema` the node type belongs to.\n this.schema = schema;\n\n // :: NodeSpec\n // The spec that this type is based on\n this.spec = spec;\n\n this.groups = spec.group ? spec.group.split(\" \") : [];\n this.attrs = initAttrs(spec.attrs);\n\n this.defaultAttrs = defaultAttrs(this.attrs);\n\n // :: ContentMatch\n // The starting match of the node type's content expression.\n this.contentMatch = null;\n\n // : ?[MarkType]\n // The set of marks allowed in this node. `null` means all marks\n // are allowed.\n this.markSet = null;\n\n // :: bool\n // True if this node type has inline content.\n this.inlineContent = null;\n\n // :: bool\n // True if this is a block type\n this.isBlock = !(spec.inline || name == \"text\");\n\n // :: bool\n // True if this is the text node type.\n this.isText = name == \"text\";\n};\n\nvar prototypeAccessors$5 = { isInline: { configurable: true },isTextblock: { configurable: true },isLeaf: { configurable: true },isAtom: { configurable: true } };\n\n// :: bool\n// True if this is an inline type.\nprototypeAccessors$5.isInline.get = function () { return !this.isBlock };\n\n// :: bool\n// True if this is a textblock type, a block that contains inline\n// content.\nprototypeAccessors$5.isTextblock.get = function () { return this.isBlock && this.inlineContent };\n\n// :: bool\n// True for node types that allow no content.\nprototypeAccessors$5.isLeaf.get = function () { return this.contentMatch == ContentMatch.empty };\n\n// :: bool\n// True when this node is an atom, i.e. when it does not have\n// directly editable content.\nprototypeAccessors$5.isAtom.get = function () { return this.isLeaf || this.spec.atom };\n\n// :: () → bool\n// Tells you whether this node type has any required attributes.\nNodeType.prototype.hasRequiredAttrs = function hasRequiredAttrs () {\n for (var n in this.attrs) { if (this.attrs[n].isRequired) { return true } }\n return false\n};\n\nNodeType.prototype.compatibleContent = function compatibleContent (other) {\n return this == other || this.contentMatch.compatible(other.contentMatch)\n};\n\nNodeType.prototype.computeAttrs = function computeAttrs$1 (attrs) {\n if (!attrs && this.defaultAttrs) { return this.defaultAttrs }\n else { return computeAttrs(this.attrs, attrs) }\n};\n\n// :: (?Object, ?union, ?[Mark]) → Node\n// Create a `Node` of this type. The given attributes are\n// checked and defaulted (you can pass `null` to use the type's\n// defaults entirely, if no required attributes exist). `content`\n// may be a `Fragment`, a node, an array of nodes, or\n// `null`. Similarly `marks` may be `null` to default to the empty\n// set of marks.\nNodeType.prototype.create = function create (attrs, content, marks) {\n if (this.isText) { throw new Error(\"NodeType.create can't construct text nodes\") }\n return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks))\n};\n\n// :: (?Object, ?union, ?[Mark]) → Node\n// Like [`create`](#model.NodeType.create), but check the given content\n// against the node type's content restrictions, and throw an error\n// if it doesn't match.\nNodeType.prototype.createChecked = function createChecked (attrs, content, marks) {\n content = Fragment.from(content);\n if (!this.validContent(content))\n { throw new RangeError(\"Invalid content for node \" + this.name) }\n return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks))\n};\n\n// :: (?Object, ?union, ?[Mark]) → ?Node\n// Like [`create`](#model.NodeType.create), but see if it is necessary to\n// add nodes to the start or end of the given fragment to make it\n// fit the node. If no fitting wrapping can be found, return null.\n// Note that, due to the fact that required nodes can always be\n// created, this will always succeed if you pass null or\n// `Fragment.empty` as content.\nNodeType.prototype.createAndFill = function createAndFill (attrs, content, marks) {\n attrs = this.computeAttrs(attrs);\n content = Fragment.from(content);\n if (content.size) {\n var before = this.contentMatch.fillBefore(content);\n if (!before) { return null }\n content = before.append(content);\n }\n var after = this.contentMatch.matchFragment(content).fillBefore(Fragment.empty, true);\n if (!after) { return null }\n return new Node(this, attrs, content.append(after), Mark.setFrom(marks))\n};\n\n// :: (Fragment) → bool\n// Returns true if the given fragment is valid content for this node\n// type with the given attributes.\nNodeType.prototype.validContent = function validContent (content) {\n var result = this.contentMatch.matchFragment(content);\n if (!result || !result.validEnd) { return false }\n for (var i = 0; i < content.childCount; i++)\n { if (!this.allowsMarks(content.child(i).marks)) { return false } }\n return true\n};\n\n// :: (MarkType) → bool\n// Check whether the given mark type is allowed in this node.\nNodeType.prototype.allowsMarkType = function allowsMarkType (markType) {\n return this.markSet == null || this.markSet.indexOf(markType) > -1\n};\n\n// :: ([Mark]) → bool\n// Test whether the given set of marks are allowed in this node.\nNodeType.prototype.allowsMarks = function allowsMarks (marks) {\n if (this.markSet == null) { return true }\n for (var i = 0; i < marks.length; i++) { if (!this.allowsMarkType(marks[i].type)) { return false } }\n return true\n};\n\n// :: ([Mark]) → [Mark]\n// Removes the marks that are not allowed in this node from the given set.\nNodeType.prototype.allowedMarks = function allowedMarks (marks) {\n if (this.markSet == null) { return marks }\n var copy;\n for (var i = 0; i < marks.length; i++) {\n if (!this.allowsMarkType(marks[i].type)) {\n if (!copy) { copy = marks.slice(0, i); }\n } else if (copy) {\n copy.push(marks[i]);\n }\n }\n return !copy ? marks : copy.length ? copy : Mark.empty\n};\n\nNodeType.compile = function compile (nodes, schema) {\n var result = Object.create(null);\n nodes.forEach(function (name, spec) { return result[name] = new NodeType(name, schema, spec); });\n\n var topType = schema.spec.topNode || \"doc\";\n if (!result[topType]) { throw new RangeError(\"Schema is missing its top node type ('\" + topType + \"')\") }\n if (!result.text) { throw new RangeError(\"Every schema needs a 'text' type\") }\n for (var _ in result.text.attrs) { throw new RangeError(\"The text node type should not have attributes\") }\n\n return result\n};\n\nObject.defineProperties( NodeType.prototype, prototypeAccessors$5 );\n\n// Attribute descriptors\n\nvar Attribute = function Attribute(options) {\n this.hasDefault = Object.prototype.hasOwnProperty.call(options, \"default\");\n this.default = options.default;\n};\n\nvar prototypeAccessors$1$3 = { isRequired: { configurable: true } };\n\nprototypeAccessors$1$3.isRequired.get = function () {\n return !this.hasDefault\n};\n\nObject.defineProperties( Attribute.prototype, prototypeAccessors$1$3 );\n\n// Marks\n\n// ::- Like nodes, marks (which are associated with nodes to signify\n// things like emphasis or being part of a link) are\n// [tagged](#model.Mark.type) with type objects, which are\n// instantiated once per `Schema`.\nvar MarkType = function MarkType(name, rank, schema, spec) {\n // :: string\n // The name of the mark type.\n this.name = name;\n\n // :: Schema\n // The schema that this mark type instance is part of.\n this.schema = schema;\n\n // :: MarkSpec\n // The spec on which the type is based.\n this.spec = spec;\n\n this.attrs = initAttrs(spec.attrs);\n\n this.rank = rank;\n this.excluded = null;\n var defaults = defaultAttrs(this.attrs);\n this.instance = defaults && new Mark(this, defaults);\n};\n\n// :: (?Object) → Mark\n// Create a mark of this type. `attrs` may be `null` or an object\n// containing only some of the mark's attributes. The others, if\n// they have defaults, will be added.\nMarkType.prototype.create = function create (attrs) {\n if (!attrs && this.instance) { return this.instance }\n return new Mark(this, computeAttrs(this.attrs, attrs))\n};\n\nMarkType.compile = function compile (marks, schema) {\n var result = Object.create(null), rank = 0;\n marks.forEach(function (name, spec) { return result[name] = new MarkType(name, rank++, schema, spec); });\n return result\n};\n\n// :: ([Mark]) → [Mark]\n// When there is a mark of this type in the given set, a new set\n// without it is returned. Otherwise, the input set is returned.\nMarkType.prototype.removeFromSet = function removeFromSet (set) {\n for (var i = 0; i < set.length; i++)\n { if (set[i].type == this)\n { return set.slice(0, i).concat(set.slice(i + 1)) } }\n return set\n};\n\n// :: ([Mark]) → ?Mark\n// Tests whether there is a mark of this type in the given set.\nMarkType.prototype.isInSet = function isInSet (set) {\n for (var i = 0; i < set.length; i++)\n { if (set[i].type == this) { return set[i] } }\n};\n\n// :: (MarkType) → bool\n// Queries whether a given mark type is\n// [excluded](#model.MarkSpec.excludes) by this one.\nMarkType.prototype.excludes = function excludes (other) {\n return this.excluded.indexOf(other) > -1\n};\n\n// SchemaSpec:: interface\n// An object describing a schema, as passed to the [`Schema`](#model.Schema)\n// constructor.\n//\n// nodes:: union, OrderedMap>\n// The node types in this schema. Maps names to\n// [`NodeSpec`](#model.NodeSpec) objects that describe the node type\n// associated with that name. Their order is significant—it\n// determines which [parse rules](#model.NodeSpec.parseDOM) take\n// precedence by default, and which nodes come first in a given\n// [group](#model.NodeSpec.group).\n//\n// marks:: ?union, OrderedMap>\n// The mark types that exist in this schema. The order in which they\n// are provided determines the order in which [mark\n// sets](#model.Mark.addToSet) are sorted and in which [parse\n// rules](#model.MarkSpec.parseDOM) are tried.\n//\n// topNode:: ?string\n// The name of the default top-level node for the schema. Defaults\n// to `\"doc\"`.\n\n// NodeSpec:: interface\n//\n// content:: ?string\n// The content expression for this node, as described in the [schema\n// guide](/docs/guide/#schema.content_expressions). When not given,\n// the node does not allow any content.\n//\n// marks:: ?string\n// The marks that are allowed inside of this node. May be a\n// space-separated string referring to mark names or groups, `\"_\"`\n// to explicitly allow all marks, or `\"\"` to disallow marks. When\n// not given, nodes with inline content default to allowing all\n// marks, other nodes default to not allowing marks.\n//\n// group:: ?string\n// The group or space-separated groups to which this node belongs,\n// which can be referred to in the content expressions for the\n// schema.\n//\n// inline:: ?bool\n// Should be set to true for inline nodes. (Implied for text nodes.)\n//\n// atom:: ?bool\n// Can be set to true to indicate that, though this isn't a [leaf\n// node](#model.NodeType.isLeaf), it doesn't have directly editable\n// content and should be treated as a single unit in the view.\n//\n// attrs:: ?Object\n// The attributes that nodes of this type get.\n//\n// selectable:: ?bool\n// Controls whether nodes of this type can be selected as a [node\n// selection](#state.NodeSelection). Defaults to true for non-text\n// nodes.\n//\n// draggable:: ?bool\n// Determines whether nodes of this type can be dragged without\n// being selected. Defaults to false.\n//\n// code:: ?bool\n// Can be used to indicate that this node contains code, which\n// causes some commands to behave differently.\n//\n// defining:: ?bool\n// Determines whether this node is considered an important parent\n// node during replace operations (such as paste). Non-defining (the\n// default) nodes get dropped when their entire content is replaced,\n// whereas defining nodes persist and wrap the inserted content.\n// Likewise, in _inserted_ content the defining parents of the\n// content are preserved when possible. Typically,\n// non-default-paragraph textblock types, and possibly list items,\n// are marked as defining.\n//\n// isolating:: ?bool\n// When enabled (default is false), the sides of nodes of this type\n// count as boundaries that regular editing operations, like\n// backspacing or lifting, won't cross. An example of a node that\n// should probably have this enabled is a table cell.\n//\n// toDOM:: ?(node: Node) → DOMOutputSpec\n// Defines the default way a node of this type should be serialized\n// to DOM/HTML (as used by\n// [`DOMSerializer.fromSchema`](#model.DOMSerializer^fromSchema)).\n// Should return a DOM node or an [array\n// structure](#model.DOMOutputSpec) that describes one, with an\n// optional number zero (“hole”) in it to indicate where the node's\n// content should be inserted.\n//\n// For text nodes, the default is to create a text DOM node. Though\n// it is possible to create a serializer where text is rendered\n// differently, this is not supported inside the editor, so you\n// shouldn't override that in your text node spec.\n//\n// parseDOM:: ?[ParseRule]\n// Associates DOM parser information with this node, which can be\n// used by [`DOMParser.fromSchema`](#model.DOMParser^fromSchema) to\n// automatically derive a parser. The `node` field in the rules is\n// implied (the name of this node will be filled in automatically).\n// If you supply your own parser, you do not need to also specify\n// parsing rules in your schema.\n//\n// toDebugString:: ?(node: Node) -> string\n// Defines the default way a node of this type should be serialized\n// to a string representation for debugging (e.g. in error messages).\n\n// MarkSpec:: interface\n//\n// attrs:: ?Object\n// The attributes that marks of this type get.\n//\n// inclusive:: ?bool\n// Whether this mark should be active when the cursor is positioned\n// at its end (or at its start when that is also the start of the\n// parent node). Defaults to true.\n//\n// excludes:: ?string\n// Determines which other marks this mark can coexist with. Should\n// be a space-separated strings naming other marks or groups of marks.\n// When a mark is [added](#model.Mark.addToSet) to a set, all marks\n// that it excludes are removed in the process. If the set contains\n// any mark that excludes the new mark but is not, itself, excluded\n// by the new mark, the mark can not be added an the set. You can\n// use the value `\"_\"` to indicate that the mark excludes all\n// marks in the schema.\n//\n// Defaults to only being exclusive with marks of the same type. You\n// can set it to an empty string (or any string not containing the\n// mark's own name) to allow multiple marks of a given type to\n// coexist (as long as they have different attributes).\n//\n// group:: ?string\n// The group or space-separated groups to which this mark belongs.\n//\n// spanning:: ?bool\n// Determines whether marks of this type can span multiple adjacent\n// nodes when serialized to DOM/HTML. Defaults to true.\n//\n// toDOM:: ?(mark: Mark, inline: bool) → DOMOutputSpec\n// Defines the default way marks of this type should be serialized\n// to DOM/HTML. When the resulting spec contains a hole, that is\n// where the marked content is placed. Otherwise, it is appended to\n// the top node.\n//\n// parseDOM:: ?[ParseRule]\n// Associates DOM parser information with this mark (see the\n// corresponding [node spec field](#model.NodeSpec.parseDOM)). The\n// `mark` field in the rules is implied.\n\n// AttributeSpec:: interface\n//\n// Used to [define](#model.NodeSpec.attrs) attributes on nodes or\n// marks.\n//\n// default:: ?any\n// The default value for this attribute, to use when no explicit\n// value is provided. Attributes that have no default must be\n// provided whenever a node or mark of a type that has them is\n// created.\n\n// ::- A document schema. Holds [node](#model.NodeType) and [mark\n// type](#model.MarkType) objects for the nodes and marks that may\n// occur in conforming documents, and provides functionality for\n// creating and deserializing such documents.\nvar Schema = function Schema(spec) {\n // :: SchemaSpec\n // The [spec](#model.SchemaSpec) on which the schema is based,\n // with the added guarantee that its `nodes` and `marks`\n // properties are\n // [`OrderedMap`](https://github.com/marijnh/orderedmap) instances\n // (not raw objects).\n this.spec = {};\n for (var prop in spec) { this.spec[prop] = spec[prop]; }\n this.spec.nodes = OrderedMap.from(spec.nodes);\n this.spec.marks = OrderedMap.from(spec.marks);\n\n // :: Object\n // An object mapping the schema's node names to node type objects.\n this.nodes = NodeType.compile(this.spec.nodes, this);\n\n // :: Object\n // A map from mark names to mark type objects.\n this.marks = MarkType.compile(this.spec.marks, this);\n\n var contentExprCache = Object.create(null);\n for (var prop$1 in this.nodes) {\n if (prop$1 in this.marks)\n { throw new RangeError(prop$1 + \" can not be both a node and a mark\") }\n var type = this.nodes[prop$1], contentExpr = type.spec.content || \"\", markExpr = type.spec.marks;\n type.contentMatch = contentExprCache[contentExpr] ||\n (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));\n type.inlineContent = type.contentMatch.inlineContent;\n type.markSet = markExpr == \"_\" ? null :\n markExpr ? gatherMarks(this, markExpr.split(\" \")) :\n markExpr == \"\" || !type.inlineContent ? [] : null;\n }\n for (var prop$2 in this.marks) {\n var type$1 = this.marks[prop$2], excl = type$1.spec.excludes;\n type$1.excluded = excl == null ? [type$1] : excl == \"\" ? [] : gatherMarks(this, excl.split(\" \"));\n }\n\n this.nodeFromJSON = this.nodeFromJSON.bind(this);\n this.markFromJSON = this.markFromJSON.bind(this);\n\n // :: NodeType\n // The type of the [default top node](#model.SchemaSpec.topNode)\n // for this schema.\n this.topNodeType = this.nodes[this.spec.topNode || \"doc\"];\n\n // :: Object\n // An object for storing whatever values modules may want to\n // compute and cache per schema. (If you want to store something\n // in it, try to use property names unlikely to clash.)\n this.cached = Object.create(null);\n this.cached.wrappings = Object.create(null);\n};\n\n// :: (union, ?Object, ?union, ?[Mark]) → Node\n// Create a node in this schema. The `type` may be a string or a\n// `NodeType` instance. Attributes will be extended\n// with defaults, `content` may be a `Fragment`,\n// `null`, a `Node`, or an array of nodes.\nSchema.prototype.node = function node (type, attrs, content, marks) {\n if (typeof type == \"string\")\n { type = this.nodeType(type); }\n else if (!(type instanceof NodeType))\n { throw new RangeError(\"Invalid node type: \" + type) }\n else if (type.schema != this)\n { throw new RangeError(\"Node type from different schema used (\" + type.name + \")\") }\n\n return type.createChecked(attrs, content, marks)\n};\n\n// :: (string, ?[Mark]) → Node\n// Create a text node in the schema. Empty text nodes are not\n// allowed.\nSchema.prototype.text = function text (text$1, marks) {\n var type = this.nodes.text;\n return new TextNode(type, type.defaultAttrs, text$1, Mark.setFrom(marks))\n};\n\n// :: (union, ?Object) → Mark\n// Create a mark with the given type and attributes.\nSchema.prototype.mark = function mark (type, attrs) {\n if (typeof type == \"string\") { type = this.marks[type]; }\n return type.create(attrs)\n};\n\n// :: (Object) → Node\n// Deserialize a node from its JSON representation. This method is\n// bound.\nSchema.prototype.nodeFromJSON = function nodeFromJSON (json) {\n return Node.fromJSON(this, json)\n};\n\n// :: (Object) → Mark\n// Deserialize a mark from its JSON representation. This method is\n// bound.\nSchema.prototype.markFromJSON = function markFromJSON (json) {\n return Mark.fromJSON(this, json)\n};\n\nSchema.prototype.nodeType = function nodeType (name) {\n var found = this.nodes[name];\n if (!found) { throw new RangeError(\"Unknown node type: \" + name) }\n return found\n};\n\nfunction gatherMarks(schema, marks) {\n var found = [];\n for (var i = 0; i < marks.length; i++) {\n var name = marks[i], mark = schema.marks[name], ok = mark;\n if (mark) {\n found.push(mark);\n } else {\n for (var prop in schema.marks) {\n var mark$1 = schema.marks[prop];\n if (name == \"_\" || (mark$1.spec.group && mark$1.spec.group.split(\" \").indexOf(name) > -1))\n { found.push(ok = mark$1); }\n }\n }\n if (!ok) { throw new SyntaxError(\"Unknown mark type: '\" + marks[i] + \"'\") }\n }\n return found\n}\n\n// ParseOptions:: interface\n// These are the options recognized by the\n// [`parse`](#model.DOMParser.parse) and\n// [`parseSlice`](#model.DOMParser.parseSlice) methods.\n//\n// preserveWhitespace:: ?union\n// By default, whitespace is collapsed as per HTML's rules. Pass\n// `true` to preserve whitespace, but normalize newlines to\n// spaces, and `\"full\"` to preserve whitespace entirely.\n//\n// findPositions:: ?[{node: dom.Node, offset: number}]\n// When given, the parser will, beside parsing the content,\n// record the document positions of the given DOM positions. It\n// will do so by writing to the objects, adding a `pos` property\n// that holds the document position. DOM positions that are not\n// in the parsed content will not be written to.\n//\n// from:: ?number\n// The child node index to start parsing from.\n//\n// to:: ?number\n// The child node index to stop parsing at.\n//\n// topNode:: ?Node\n// By default, the content is parsed into the schema's default\n// [top node type](#model.Schema.topNodeType). You can pass this\n// option to use the type and attributes from a different node\n// as the top container.\n//\n// topMatch:: ?ContentMatch\n// Provide the starting content match that content parsed into the\n// top node is matched against.\n//\n// context:: ?ResolvedPos\n// A set of additional nodes to count as\n// [context](#model.ParseRule.context) when parsing, above the\n// given [top node](#model.ParseOptions.topNode).\n\n// ParseRule:: interface\n// A value that describes how to parse a given DOM node or inline\n// style as a ProseMirror node or mark.\n//\n// tag:: ?string\n// A CSS selector describing the kind of DOM elements to match. A\n// single rule should have _either_ a `tag` or a `style` property.\n//\n// namespace:: ?string\n// The namespace to match. This should be used with `tag`.\n// Nodes are only matched when the namespace matches or this property\n// is null.\n//\n// style:: ?string\n// A CSS property name to match. When given, this rule matches\n// inline styles that list that property. May also have the form\n// `\"property=value\"`, in which case the rule only matches if the\n// property's value exactly matches the given value. (For more\n// complicated filters, use [`getAttrs`](#model.ParseRule.getAttrs)\n// and return false to indicate that the match failed.)\n//\n// priority:: ?number\n// Can be used to change the order in which the parse rules in a\n// schema are tried. Those with higher priority come first. Rules\n// without a priority are counted as having priority 50. This\n// property is only meaningful in a schema—when directly\n// constructing a parser, the order of the rule array is used.\n//\n// context:: ?string\n// When given, restricts this rule to only match when the current\n// context—the parent nodes into which the content is being\n// parsed—matches this expression. Should contain one or more node\n// names or node group names followed by single or double slashes.\n// For example `\"paragraph/\"` means the rule only matches when the\n// parent node is a paragraph, `\"blockquote/paragraph/\"` restricts\n// it to be in a paragraph that is inside a blockquote, and\n// `\"section//\"` matches any position inside a section—a double\n// slash matches any sequence of ancestor nodes. To allow multiple\n// different contexts, they can be separated by a pipe (`|`)\n// character, as in `\"blockquote/|list_item/\"`.\n//\n// node:: ?string\n// The name of the node type to create when this rule matches. Only\n// valid for rules with a `tag` property, not for style rules. Each\n// rule should have one of a `node`, `mark`, or `ignore` property\n// (except when it appears in a [node](#model.NodeSpec.parseDOM) or\n// [mark spec](#model.MarkSpec.parseDOM), in which case the `node`\n// or `mark` property will be derived from its position).\n//\n// mark:: ?string\n// The name of the mark type to wrap the matched content in.\n//\n// ignore:: ?bool\n// When true, ignore content that matches this rule.\n//\n// closeParent:: ?bool\n// When true, finding an element that matches this rule will close\n// the current node.\n//\n// skip:: ?bool\n// When true, ignore the node that matches this rule, but do parse\n// its content.\n//\n// attrs:: ?Object\n// Attributes for the node or mark created by this rule. When\n// `getAttrs` is provided, it takes precedence.\n//\n// getAttrs:: ?(union) → ?union\n// A function used to compute the attributes for the node or mark\n// created by this rule. Can also be used to describe further\n// conditions the DOM element or style must match. When it returns\n// `false`, the rule won't match. When it returns null or undefined,\n// that is interpreted as an empty/default set of attributes.\n//\n// Called with a DOM Element for `tag` rules, and with a string (the\n// style's value) for `style` rules.\n//\n// contentElement:: ?union\n// For `tag` rules that produce non-leaf nodes or marks, by default\n// the content of the DOM element is parsed as content of the mark\n// or node. If the child nodes are in a descendent node, this may be\n// a CSS selector string that the parser must use to find the actual\n// content element, or a function that returns the actual content\n// element to the parser.\n//\n// getContent:: ?(dom.Node, schema: Schema) → Fragment\n// Can be used to override the content of a matched node. When\n// present, instead of parsing the node's child nodes, the result of\n// this function is used.\n//\n// preserveWhitespace:: ?union\n// Controls whether whitespace should be preserved when parsing the\n// content inside the matched element. `false` means whitespace may\n// be collapsed, `true` means that whitespace should be preserved\n// but newlines normalized to spaces, and `\"full\"` means that\n// newlines should also be preserved.\n\n// ::- A DOM parser represents a strategy for parsing DOM content into\n// a ProseMirror document conforming to a given schema. Its behavior\n// is defined by an array of [rules](#model.ParseRule).\nvar DOMParser = function DOMParser(schema, rules) {\n var this$1 = this;\n\n // :: Schema\n // The schema into which the parser parses.\n this.schema = schema;\n // :: [ParseRule]\n // The set of [parse rules](#model.ParseRule) that the parser\n // uses, in order of precedence.\n this.rules = rules;\n this.tags = [];\n this.styles = [];\n\n rules.forEach(function (rule) {\n if (rule.tag) { this$1.tags.push(rule); }\n else if (rule.style) { this$1.styles.push(rule); }\n });\n\n // Only normalize list elements when lists in the schema can't directly contain themselves\n this.normalizeLists = !this.tags.some(function (r) {\n if (!/^(ul|ol)\\b/.test(r.tag) || !r.node) { return false }\n var node = schema.nodes[r.node];\n return node.contentMatch.matchType(node)\n });\n};\n\n// :: (dom.Node, ?ParseOptions) → Node\n// Parse a document from the content of a DOM node.\nDOMParser.prototype.parse = function parse (dom, options) {\n if ( options === void 0 ) options = {};\n\n var context = new ParseContext(this, options, false);\n context.addAll(dom, null, options.from, options.to);\n return context.finish()\n};\n\n// :: (dom.Node, ?ParseOptions) → Slice\n// Parses the content of the given DOM node, like\n// [`parse`](#model.DOMParser.parse), and takes the same set of\n// options. But unlike that method, which produces a whole node,\n// this one returns a slice that is open at the sides, meaning that\n// the schema constraints aren't applied to the start of nodes to\n// the left of the input and the end of nodes at the end.\nDOMParser.prototype.parseSlice = function parseSlice (dom, options) {\n if ( options === void 0 ) options = {};\n\n var context = new ParseContext(this, options, true);\n context.addAll(dom, null, options.from, options.to);\n return Slice.maxOpen(context.finish())\n};\n\nDOMParser.prototype.matchTag = function matchTag (dom, context) {\n for (var i = 0; i < this.tags.length; i++) {\n var rule = this.tags[i];\n if (matches(dom, rule.tag) &&\n (rule.namespace === undefined || dom.namespaceURI == rule.namespace) &&\n (!rule.context || context.matchesContext(rule.context))) {\n if (rule.getAttrs) {\n var result = rule.getAttrs(dom);\n if (result === false) { continue }\n rule.attrs = result;\n }\n return rule\n }\n }\n};\n\nDOMParser.prototype.matchStyle = function matchStyle (prop, value, context) {\n for (var i = 0; i < this.styles.length; i++) {\n var rule = this.styles[i];\n if (rule.style.indexOf(prop) != 0 ||\n rule.context && !context.matchesContext(rule.context) ||\n // Test that the style string either precisely matches the prop,\n // or has an '=' sign after the prop, followed by the given\n // value.\n rule.style.length > prop.length &&\n (rule.style.charCodeAt(prop.length) != 61 || rule.style.slice(prop.length + 1) != value))\n { continue }\n if (rule.getAttrs) {\n var result = rule.getAttrs(value);\n if (result === false) { continue }\n rule.attrs = result;\n }\n return rule\n }\n};\n\n// : (Schema) → [ParseRule]\nDOMParser.schemaRules = function schemaRules (schema) {\n var result = [];\n function insert(rule) {\n var priority = rule.priority == null ? 50 : rule.priority, i = 0;\n for (; i < result.length; i++) {\n var next = result[i], nextPriority = next.priority == null ? 50 : next.priority;\n if (nextPriority < priority) { break }\n }\n result.splice(i, 0, rule);\n }\n\n var loop = function ( name ) {\n var rules = schema.marks[name].spec.parseDOM;\n if (rules) { rules.forEach(function (rule) {\n insert(rule = copy(rule));\n rule.mark = name;\n }); }\n };\n\n for (var name in schema.marks) loop( name );\n var loop$1 = function ( name ) {\n var rules$1 = schema.nodes[name$1].spec.parseDOM;\n if (rules$1) { rules$1.forEach(function (rule) {\n insert(rule = copy(rule));\n rule.node = name$1;\n }); }\n };\n\n for (var name$1 in schema.nodes) loop$1();\n return result\n};\n\n// :: (Schema) → DOMParser\n// Construct a DOM parser using the parsing rules listed in a\n// schema's [node specs](#model.NodeSpec.parseDOM), reordered by\n// [priority](#model.ParseRule.priority).\nDOMParser.fromSchema = function fromSchema (schema) {\n return schema.cached.domParser ||\n (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema)))\n};\n\n// : Object The block-level tags in HTML5\nvar blockTags = {\n address: true, article: true, aside: true, blockquote: true, canvas: true,\n dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true,\n footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true,\n h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true,\n output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true\n};\n\n// : Object The tags that we normally ignore.\nvar ignoreTags = {\n head: true, noscript: true, object: true, script: true, style: true, title: true\n};\n\n// : Object List tags.\nvar listTags = {ol: true, ul: true};\n\n// Using a bitfield for node context options\nvar OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4;\n\nfunction wsOptionsFor(preserveWhitespace) {\n return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === \"full\" ? OPT_PRESERVE_WS_FULL : 0)\n}\n\nvar NodeContext = function NodeContext(type, attrs, marks, pendingMarks, solid, match, options) {\n this.type = type;\n this.attrs = attrs;\n this.solid = solid;\n this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);\n this.options = options;\n this.content = [];\n // Marks applied to this node itself\n this.marks = marks;\n // Marks applied to its children\n this.activeMarks = Mark.none;\n // Marks that can't apply here, but will be used in children if possible\n this.pendingMarks = pendingMarks;\n // Nested Marks with same type\n this.stashMarks = [];\n};\n\nNodeContext.prototype.findWrapping = function findWrapping (node) {\n if (!this.match) {\n if (!this.type) { return [] }\n var fill = this.type.contentMatch.fillBefore(Fragment.from(node));\n if (fill) {\n this.match = this.type.contentMatch.matchFragment(fill);\n } else {\n var start = this.type.contentMatch, wrap;\n if (wrap = start.findWrapping(node.type)) {\n this.match = start;\n return wrap\n } else {\n return null\n }\n }\n }\n return this.match.findWrapping(node.type)\n};\n\nNodeContext.prototype.finish = function finish (openEnd) {\n if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace\n var last = this.content[this.content.length - 1], m;\n if (last && last.isText && (m = /[ \\t\\r\\n\\u000c]+$/.exec(last.text))) {\n if (last.text.length == m[0].length) { this.content.pop(); }\n else { this.content[this.content.length - 1] = last.withText(last.text.slice(0, last.text.length - m[0].length)); }\n }\n }\n var content = Fragment.from(this.content);\n if (!openEnd && this.match)\n { content = content.append(this.match.fillBefore(Fragment.empty, true)); }\n return this.type ? this.type.create(this.attrs, content, this.marks) : content\n};\n\nNodeContext.prototype.popFromStashMark = function popFromStashMark (markType) {\n for (var i = this.stashMarks.length - 1; i >= 0; i--)\n { if (this.stashMarks[i].type == markType) { return this.stashMarks.splice(i, 1)[0] } }\n};\n\nNodeContext.prototype.applyPending = function applyPending (nextType) {\n for (var i = 0, pending = this.pendingMarks; i < pending.length; i++) {\n var mark = pending[i];\n if ((this.type ? this.type.allowsMarkType(mark.type) : markMayApply(mark.type, nextType)) &&\n !mark.isInSet(this.activeMarks)) {\n var found = findSameTypeInSet(mark, this.activeMarks);\n if (found) { this.stashMarks.push(found); }\n this.activeMarks = mark.addToSet(this.activeMarks);\n this.pendingMarks = mark.removeFromSet(this.pendingMarks);\n }\n }\n};\n\nvar ParseContext = function ParseContext(parser, options, open) {\n // : DOMParser The parser we are using.\n this.parser = parser;\n // : Object The options passed to this parse.\n this.options = options;\n this.isOpen = open;\n var topNode = options.topNode, topContext;\n var topOptions = wsOptionsFor(options.preserveWhitespace) | (open ? OPT_OPEN_LEFT : 0);\n if (topNode)\n { topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, Mark.none, true,\n options.topMatch || topNode.type.contentMatch, topOptions); }\n else if (open)\n { topContext = new NodeContext(null, null, Mark.none, Mark.none, true, null, topOptions); }\n else\n { topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, Mark.none, true, null, topOptions); }\n this.nodes = [topContext];\n // : [Mark] The current set of marks\n this.open = 0;\n this.find = options.findPositions;\n this.needsBlock = false;\n};\n\nvar prototypeAccessors$6 = { top: { configurable: true },currentPos: { configurable: true } };\n\nprototypeAccessors$6.top.get = function () {\n return this.nodes[this.open]\n};\n\n// : (dom.Node)\n// Add a DOM node to the content. Text is inserted as text node,\n// otherwise, the node is passed to `addElement` or, if it has a\n// `style` attribute, `addElementWithStyles`.\nParseContext.prototype.addDOM = function addDOM (dom) {\n if (dom.nodeType == 3) {\n this.addTextNode(dom);\n } else if (dom.nodeType == 1) {\n var style = dom.getAttribute(\"style\");\n var marks = style ? this.readStyles(parseStyles(style)) : null, top = this.top;\n if (marks != null) { for (var i = 0; i < marks.length; i++) { this.addPendingMark(marks[i]); } }\n this.addElement(dom);\n if (marks != null) { for (var i$1 = 0; i$1 < marks.length; i$1++) { this.removePendingMark(marks[i$1], top); } }\n }\n};\n\nParseContext.prototype.addTextNode = function addTextNode (dom) {\n var value = dom.nodeValue;\n var top = this.top;\n if ((top.type ? top.type.inlineContent : top.content.length && top.content[0].isInline) || /[^ \\t\\r\\n\\u000c]/.test(value)) {\n if (!(top.options & OPT_PRESERVE_WS)) {\n value = value.replace(/[ \\t\\r\\n\\u000c]+/g, \" \");\n // If this starts with whitespace, and there is no node before it, or\n // a hard break, or a text node that ends with whitespace, strip the\n // leading space.\n if (/^[ \\t\\r\\n\\u000c]/.test(value) && this.open == this.nodes.length - 1) {\n var nodeBefore = top.content[top.content.length - 1];\n var domNodeBefore = dom.previousSibling;\n if (!nodeBefore ||\n (domNodeBefore && domNodeBefore.nodeName == 'BR') ||\n (nodeBefore.isText && /[ \\t\\r\\n\\u000c]$/.test(nodeBefore.text)))\n { value = value.slice(1); }\n }\n } else if (!(top.options & OPT_PRESERVE_WS_FULL)) {\n value = value.replace(/\\r?\\n|\\r/g, \" \");\n }\n if (value) { this.insertNode(this.parser.schema.text(value)); }\n this.findInText(dom);\n } else {\n this.findInside(dom);\n }\n};\n\n// : (dom.Element)\n// Try to find a handler for the given tag and use that to parse. If\n// none is found, the element's content nodes are added directly.\nParseContext.prototype.addElement = function addElement (dom) {\n var name = dom.nodeName.toLowerCase();\n if (listTags.hasOwnProperty(name) && this.parser.normalizeLists) { normalizeList(dom); }\n var rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) || this.parser.matchTag(dom, this);\n if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {\n this.findInside(dom);\n } else if (!rule || rule.skip || rule.closeParent) {\n if (rule && rule.closeParent) { this.open = Math.max(0, this.open - 1); }\n else if (rule && rule.skip.nodeType) { dom = rule.skip; }\n var sync, top = this.top, oldNeedsBlock = this.needsBlock;\n if (blockTags.hasOwnProperty(name)) {\n sync = true;\n if (!top.type) { this.needsBlock = true; }\n } else if (!dom.firstChild) {\n this.leafFallback(dom);\n return\n }\n this.addAll(dom);\n if (sync) { this.sync(top); }\n this.needsBlock = oldNeedsBlock;\n } else {\n this.addElementByRule(dom, rule);\n }\n};\n\n// Called for leaf DOM nodes that would otherwise be ignored\nParseContext.prototype.leafFallback = function leafFallback (dom) {\n if (dom.nodeName == \"BR\" && this.top.type && this.top.type.inlineContent)\n { this.addTextNode(dom.ownerDocument.createTextNode(\"\\n\")); }\n};\n\n// Run any style parser associated with the node's styles. Either\n// return an array of marks, or null to indicate some of the styles\n// had a rule with `ignore` set.\nParseContext.prototype.readStyles = function readStyles (styles) {\n var marks = Mark.none;\n for (var i = 0; i < styles.length; i += 2) {\n var rule = this.parser.matchStyle(styles[i], styles[i + 1], this);\n if (!rule) { continue }\n if (rule.ignore) { return null }\n marks = this.parser.schema.marks[rule.mark].create(rule.attrs).addToSet(marks);\n }\n return marks\n};\n\n// : (dom.Element, ParseRule) → bool\n// Look up a handler for the given node. If none are found, return\n// false. Otherwise, apply it, use its return value to drive the way\n// the node's content is wrapped, and return true.\nParseContext.prototype.addElementByRule = function addElementByRule (dom, rule) {\n var this$1 = this;\n\n var sync, nodeType, markType, mark;\n if (rule.node) {\n nodeType = this.parser.schema.nodes[rule.node];\n if (!nodeType.isLeaf) {\n sync = this.enter(nodeType, rule.attrs, rule.preserveWhitespace);\n } else if (!this.insertNode(nodeType.create(rule.attrs))) {\n this.leafFallback(dom);\n }\n } else {\n markType = this.parser.schema.marks[rule.mark];\n mark = markType.create(rule.attrs);\n this.addPendingMark(mark);\n }\n var startIn = this.top;\n\n if (nodeType && nodeType.isLeaf) {\n this.findInside(dom);\n } else if (rule.getContent) {\n this.findInside(dom);\n rule.getContent(dom, this.parser.schema).forEach(function (node) { return this$1.insertNode(node); });\n } else {\n var contentDOM = rule.contentElement;\n if (typeof contentDOM == \"string\") { contentDOM = dom.querySelector(contentDOM); }\n else if (typeof contentDOM == \"function\") { contentDOM = contentDOM(dom); }\n if (!contentDOM) { contentDOM = dom; }\n this.findAround(dom, contentDOM, true);\n this.addAll(contentDOM, sync);\n }\n if (sync) { this.sync(startIn); this.open--; }\n if (mark) { this.removePendingMark(mark, startIn); }\n};\n\n// : (dom.Node, ?NodeBuilder, ?number, ?number)\n// Add all child nodes between `startIndex` and `endIndex` (or the\n// whole node, if not given). If `sync` is passed, use it to\n// synchronize after every block element.\nParseContext.prototype.addAll = function addAll (parent, sync, startIndex, endIndex) {\n var index = startIndex || 0;\n for (var dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild,\n end = endIndex == null ? null : parent.childNodes[endIndex];\n dom != end; dom = dom.nextSibling, ++index) {\n this.findAtPoint(parent, index);\n this.addDOM(dom);\n if (sync && blockTags.hasOwnProperty(dom.nodeName.toLowerCase()))\n { this.sync(sync); }\n }\n this.findAtPoint(parent, index);\n};\n\n// Try to find a way to fit the given node type into the current\n// context. May add intermediate wrappers and/or leave non-solid\n// nodes that we're in.\nParseContext.prototype.findPlace = function findPlace (node) {\n var route, sync;\n for (var depth = this.open; depth >= 0; depth--) {\n var cx = this.nodes[depth];\n var found = cx.findWrapping(node);\n if (found && (!route || route.length > found.length)) {\n route = found;\n sync = cx;\n if (!found.length) { break }\n }\n if (cx.solid) { break }\n }\n if (!route) { return false }\n this.sync(sync);\n for (var i = 0; i < route.length; i++)\n { this.enterInner(route[i], null, false); }\n return true\n};\n\n// : (Node) → ?Node\n// Try to insert the given node, adjusting the context when needed.\nParseContext.prototype.insertNode = function insertNode (node) {\n if (node.isInline && this.needsBlock && !this.top.type) {\n var block = this.textblockFromContext();\n if (block) { this.enterInner(block); }\n }\n if (this.findPlace(node)) {\n this.closeExtra();\n var top = this.top;\n top.applyPending(node.type);\n if (top.match) { top.match = top.match.matchType(node.type); }\n var marks = top.activeMarks;\n for (var i = 0; i < node.marks.length; i++)\n { if (!top.type || top.type.allowsMarkType(node.marks[i].type))\n { marks = node.marks[i].addToSet(marks); } }\n top.content.push(node.mark(marks));\n return true\n }\n return false\n};\n\n// : (NodeType, ?Object) → bool\n// Try to start a node of the given type, adjusting the context when\n// necessary.\nParseContext.prototype.enter = function enter (type, attrs, preserveWS) {\n var ok = this.findPlace(type.create(attrs));\n if (ok) { this.enterInner(type, attrs, true, preserveWS); }\n return ok\n};\n\n// Open a node of the given type\nParseContext.prototype.enterInner = function enterInner (type, attrs, solid, preserveWS) {\n this.closeExtra();\n var top = this.top;\n top.applyPending(type);\n top.match = top.match && top.match.matchType(type, attrs);\n var options = preserveWS == null ? top.options & ~OPT_OPEN_LEFT : wsOptionsFor(preserveWS);\n if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0) { options |= OPT_OPEN_LEFT; }\n this.nodes.push(new NodeContext(type, attrs, top.activeMarks, top.pendingMarks, solid, null, options));\n this.open++;\n};\n\n// Make sure all nodes above this.open are finished and added to\n// their parents\nParseContext.prototype.closeExtra = function closeExtra (openEnd) {\n var i = this.nodes.length - 1;\n if (i > this.open) {\n for (; i > this.open; i--) { this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd)); }\n this.nodes.length = this.open + 1;\n }\n};\n\nParseContext.prototype.finish = function finish () {\n this.open = 0;\n this.closeExtra(this.isOpen);\n return this.nodes[0].finish(this.isOpen || this.options.topOpen)\n};\n\nParseContext.prototype.sync = function sync (to) {\n for (var i = this.open; i >= 0; i--) { if (this.nodes[i] == to) {\n this.open = i;\n return\n } }\n};\n\nprototypeAccessors$6.currentPos.get = function () {\n this.closeExtra();\n var pos = 0;\n for (var i = this.open; i >= 0; i--) {\n var content = this.nodes[i].content;\n for (var j = content.length - 1; j >= 0; j--)\n { pos += content[j].nodeSize; }\n if (i) { pos++; }\n }\n return pos\n};\n\nParseContext.prototype.findAtPoint = function findAtPoint (parent, offset) {\n if (this.find) { for (var i = 0; i < this.find.length; i++) {\n if (this.find[i].node == parent && this.find[i].offset == offset)\n { this.find[i].pos = this.currentPos; }\n } }\n};\n\nParseContext.prototype.findInside = function findInside (parent) {\n if (this.find) { for (var i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node))\n { this.find[i].pos = this.currentPos; }\n } }\n};\n\nParseContext.prototype.findAround = function findAround (parent, content, before) {\n if (parent != content && this.find) { for (var i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {\n var pos = content.compareDocumentPosition(this.find[i].node);\n if (pos & (before ? 2 : 4))\n { this.find[i].pos = this.currentPos; }\n }\n } }\n};\n\nParseContext.prototype.findInText = function findInText (textNode) {\n if (this.find) { for (var i = 0; i < this.find.length; i++) {\n if (this.find[i].node == textNode)\n { this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset); }\n } }\n};\n\n// : (string) → bool\n// Determines whether the given [context\n// string](#ParseRule.context) matches this context.\nParseContext.prototype.matchesContext = function matchesContext (context) {\n var this$1 = this;\n\n if (context.indexOf(\"|\") > -1)\n { return context.split(/\\s*\\|\\s*/).some(this.matchesContext, this) }\n\n var parts = context.split(\"/\");\n var option = this.options.context;\n var useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);\n var minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);\n var match = function (i, depth) {\n for (; i >= 0; i--) {\n var part = parts[i];\n if (part == \"\") {\n if (i == parts.length - 1 || i == 0) { continue }\n for (; depth >= minDepth; depth--)\n { if (match(i - 1, depth)) { return true } }\n return false\n } else {\n var next = depth > 0 || (depth == 0 && useRoot) ? this$1.nodes[depth].type\n : option && depth >= minDepth ? option.node(depth - minDepth).type\n : null;\n if (!next || (next.name != part && next.groups.indexOf(part) == -1))\n { return false }\n depth--;\n }\n }\n return true\n };\n return match(parts.length - 1, this.open)\n};\n\nParseContext.prototype.textblockFromContext = function textblockFromContext () {\n var $context = this.options.context;\n if ($context) { for (var d = $context.depth; d >= 0; d--) {\n var deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;\n if (deflt && deflt.isTextblock && deflt.defaultAttrs) { return deflt }\n } }\n for (var name in this.parser.schema.nodes) {\n var type = this.parser.schema.nodes[name];\n if (type.isTextblock && type.defaultAttrs) { return type }\n }\n};\n\nParseContext.prototype.addPendingMark = function addPendingMark (mark) {\n var found = findSameTypeInSet(mark, this.top.pendingMarks);\n if (found) { this.top.stashMarks.push(found); }\n this.top.pendingMarks = mark.addToSet(this.top.pendingMarks);\n};\n\nParseContext.prototype.removePendingMark = function removePendingMark (mark, upto) {\n for (var depth = this.open; depth >= 0; depth--) {\n var level = this.nodes[depth];\n var found = level.pendingMarks.lastIndexOf(mark);\n if (found > -1) {\n level.pendingMarks = mark.removeFromSet(level.pendingMarks);\n } else {\n level.activeMarks = mark.removeFromSet(level.activeMarks);\n var stashMark = level.popFromStashMark(mark.type);\n if (stashMark) { level.activeMarks = stashMark.addToSet(level.activeMarks); }\n }\n if (level == upto) { break }\n }\n};\n\nObject.defineProperties( ParseContext.prototype, prototypeAccessors$6 );\n\n// Kludge to work around directly nested list nodes produced by some\n// tools and allowed by browsers to mean that the nested list is\n// actually part of the list item above it.\nfunction normalizeList(dom) {\n for (var child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {\n var name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;\n if (name && listTags.hasOwnProperty(name) && prevItem) {\n prevItem.appendChild(child);\n child = prevItem;\n } else if (name == \"li\") {\n prevItem = child;\n } else if (name) {\n prevItem = null;\n }\n }\n}\n\n// Apply a CSS selector.\nfunction matches(dom, selector) {\n return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector)\n}\n\n// : (string) → [string]\n// Tokenize a style attribute into property/value pairs.\nfunction parseStyles(style) {\n var re = /\\s*([\\w-]+)\\s*:\\s*([^;]+)/g, m, result = [];\n while (m = re.exec(style)) { result.push(m[1], m[2].trim()); }\n return result\n}\n\nfunction copy(obj) {\n var copy = {};\n for (var prop in obj) { copy[prop] = obj[prop]; }\n return copy\n}\n\n// Used when finding a mark at the top level of a fragment parse.\n// Checks whether it would be reasonable to apply a given mark type to\n// a given node, by looking at the way the mark occurs in the schema.\nfunction markMayApply(markType, nodeType) {\n var nodes = nodeType.schema.nodes;\n var loop = function ( name ) {\n var parent = nodes[name];\n if (!parent.allowsMarkType(markType)) { return }\n var seen = [], scan = function (match) {\n seen.push(match);\n for (var i = 0; i < match.edgeCount; i++) {\n var ref = match.edge(i);\n var type = ref.type;\n var next = ref.next;\n if (type == nodeType) { return true }\n if (seen.indexOf(next) < 0 && scan(next)) { return true }\n }\n };\n if (scan(parent.contentMatch)) { return { v: true } }\n };\n\n for (var name in nodes) {\n var returned = loop( name );\n\n if ( returned ) return returned.v;\n }\n}\n\nfunction findSameTypeInSet(mark, set) {\n for (var i = 0; i < set.length; i++) {\n if (mark.type == set[i].type) { return set[i] }\n }\n}\n\n// DOMOutputSpec:: interface\n// A description of a DOM structure. Can be either a string, which is\n// interpreted as a text node, a DOM node, which is interpreted as\n// itself, a `{dom: Node, contentDOM: ?Node}` object, or an array.\n//\n// An array describes a DOM element. The first value in the array\n// should be a string—the name of the DOM element, optionally prefixed\n// by a namespace URL and a space. If the second element is plain\n// object, it is interpreted as a set of attributes for the element.\n// Any elements after that (including the 2nd if it's not an attribute\n// object) are interpreted as children of the DOM elements, and must\n// either be valid `DOMOutputSpec` values, or the number zero.\n//\n// The number zero (pronounced “hole”) is used to indicate the place\n// where a node's child nodes should be inserted. If it occurs in an\n// output spec, it should be the only child element in its parent\n// node.\n\n// ::- A DOM serializer knows how to convert ProseMirror nodes and\n// marks of various types to DOM nodes.\nvar DOMSerializer = function DOMSerializer(nodes, marks) {\n // :: Object<(node: Node) → DOMOutputSpec>\n // The node serialization functions.\n this.nodes = nodes || {};\n // :: Object\n // The mark serialization functions.\n this.marks = marks || {};\n};\n\n// :: (Fragment, ?Object) → dom.DocumentFragment\n// Serialize the content of this fragment to a DOM fragment. When\n// not in the browser, the `document` option, containing a DOM\n// document, should be passed so that the serializer can create\n// nodes.\nDOMSerializer.prototype.serializeFragment = function serializeFragment (fragment, options, target) {\n var this$1 = this;\n if ( options === void 0 ) options = {};\n\n if (!target) { target = doc(options).createDocumentFragment(); }\n\n var top = target, active = null;\n fragment.forEach(function (node) {\n if (active || node.marks.length) {\n if (!active) { active = []; }\n var keep = 0, rendered = 0;\n while (keep < active.length && rendered < node.marks.length) {\n var next = node.marks[rendered];\n if (!this$1.marks[next.type.name]) { rendered++; continue }\n if (!next.eq(active[keep]) || next.type.spec.spanning === false) { break }\n keep += 2; rendered++;\n }\n while (keep < active.length) {\n top = active.pop();\n active.pop();\n }\n while (rendered < node.marks.length) {\n var add = node.marks[rendered++];\n var markDOM = this$1.serializeMark(add, node.isInline, options);\n if (markDOM) {\n active.push(add, top);\n top.appendChild(markDOM.dom);\n top = markDOM.contentDOM || markDOM.dom;\n }\n }\n }\n top.appendChild(this$1.serializeNode(node, options));\n });\n\n return target\n};\n\n// :: (Node, ?Object) → dom.Node\n// Serialize this node to a DOM node. This can be useful when you\n// need to serialize a part of a document, as opposed to the whole\n// document. To serialize a whole document, use\n// [`serializeFragment`](#model.DOMSerializer.serializeFragment) on\n// its [content](#model.Node.content).\nDOMSerializer.prototype.serializeNode = function serializeNode (node, options) {\n if ( options === void 0 ) options = {};\n\n var ref =\n DOMSerializer.renderSpec(doc(options), this.nodes[node.type.name](node));\n var dom = ref.dom;\n var contentDOM = ref.contentDOM;\n if (contentDOM) {\n if (node.isLeaf)\n { throw new RangeError(\"Content hole not allowed in a leaf node spec\") }\n if (options.onContent)\n { options.onContent(node, contentDOM, options); }\n else\n { this.serializeFragment(node.content, options, contentDOM); }\n }\n return dom\n};\n\nDOMSerializer.prototype.serializeNodeAndMarks = function serializeNodeAndMarks (node, options) {\n if ( options === void 0 ) options = {};\n\n var dom = this.serializeNode(node, options);\n for (var i = node.marks.length - 1; i >= 0; i--) {\n var wrap = this.serializeMark(node.marks[i], node.isInline, options);\n if (wrap) {\n(wrap.contentDOM || wrap.dom).appendChild(dom);\n dom = wrap.dom;\n }\n }\n return dom\n};\n\nDOMSerializer.prototype.serializeMark = function serializeMark (mark, inline, options) {\n if ( options === void 0 ) options = {};\n\n var toDOM = this.marks[mark.type.name];\n return toDOM && DOMSerializer.renderSpec(doc(options), toDOM(mark, inline))\n};\n\n// :: (dom.Document, DOMOutputSpec) → {dom: dom.Node, contentDOM: ?dom.Node}\n// Render an [output spec](#model.DOMOutputSpec) to a DOM node. If\n// the spec has a hole (zero) in it, `contentDOM` will point at the\n// node with the hole.\nDOMSerializer.renderSpec = function renderSpec (doc, structure, xmlNS) {\n if ( xmlNS === void 0 ) xmlNS = null;\n\n if (typeof structure == \"string\")\n { return {dom: doc.createTextNode(structure)} }\n if (structure.nodeType != null)\n { return {dom: structure} }\n if (structure.dom && structure.dom.nodeType != null)\n { return structure }\n var tagName = structure[0], space = tagName.indexOf(\" \");\n if (space > 0) {\n xmlNS = tagName.slice(0, space);\n tagName = tagName.slice(space + 1);\n }\n var contentDOM = null, dom = xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName);\n var attrs = structure[1], start = 1;\n if (attrs && typeof attrs == \"object\" && attrs.nodeType == null && !Array.isArray(attrs)) {\n start = 2;\n for (var name in attrs) { if (attrs[name] != null) {\n var space$1 = name.indexOf(\" \");\n if (space$1 > 0) { dom.setAttributeNS(name.slice(0, space$1), name.slice(space$1 + 1), attrs[name]); }\n else { dom.setAttribute(name, attrs[name]); }\n } }\n }\n for (var i = start; i < structure.length; i++) {\n var child = structure[i];\n if (child === 0) {\n if (i < structure.length - 1 || i > start)\n { throw new RangeError(\"Content hole must be the only child of its parent node\") }\n return {dom: dom, contentDOM: dom}\n } else {\n var ref = DOMSerializer.renderSpec(doc, child, xmlNS);\n var inner = ref.dom;\n var innerContent = ref.contentDOM;\n dom.appendChild(inner);\n if (innerContent) {\n if (contentDOM) { throw new RangeError(\"Multiple content holes\") }\n contentDOM = innerContent;\n }\n }\n }\n return {dom: dom, contentDOM: contentDOM}\n};\n\n// :: (Schema) → DOMSerializer\n// Build a serializer using the [`toDOM`](#model.NodeSpec.toDOM)\n// properties in a schema's node and mark specs.\nDOMSerializer.fromSchema = function fromSchema (schema) {\n return schema.cached.domSerializer ||\n (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)))\n};\n\n// : (Schema) → Object<(node: Node) → DOMOutputSpec>\n// Gather the serializers in a schema's node specs into an object.\n// This can be useful as a base to build a custom serializer from.\nDOMSerializer.nodesFromSchema = function nodesFromSchema (schema) {\n var result = gatherToDOM(schema.nodes);\n if (!result.text) { result.text = function (node) { return node.text; }; }\n return result\n};\n\n// : (Schema) → Object<(mark: Mark) → DOMOutputSpec>\n// Gather the serializers in a schema's mark specs into an object.\nDOMSerializer.marksFromSchema = function marksFromSchema (schema) {\n return gatherToDOM(schema.marks)\n};\n\nfunction gatherToDOM(obj) {\n var result = {};\n for (var name in obj) {\n var toDOM = obj[name].spec.toDOM;\n if (toDOM) { result[name] = toDOM; }\n }\n return result\n}\n\nfunction doc(options) {\n // declare global: window\n return options.document || window.document\n}\n\nexport { ContentMatch, DOMParser, DOMSerializer, Fragment, Mark, MarkType, Node, NodeRange, NodeType, ReplaceError, ResolvedPos, Schema, Slice };\n//# sourceMappingURL=index.es.js.map\n","import { ReplaceError, Slice, Fragment, MarkType } from 'prosemirror-model';\n\n// Mappable:: interface\n// There are several things that positions can be mapped through.\n// Such objects conform to this interface.\n//\n// map:: (pos: number, assoc: ?number) → number\n// Map a position through this object. When given, `assoc` (should\n// be -1 or 1, defaults to 1) determines with which side the\n// position is associated, which determines in which direction to\n// move when a chunk of content is inserted at the mapped position.\n//\n// mapResult:: (pos: number, assoc: ?number) → MapResult\n// Map a position, and return an object containing additional\n// information about the mapping. The result's `deleted` field tells\n// you whether the position was deleted (completely enclosed in a\n// replaced range) during the mapping. When content on only one side\n// is deleted, the position itself is only considered deleted when\n// `assoc` points in the direction of the deleted content.\n\n// Recovery values encode a range index and an offset. They are\n// represented as numbers, because tons of them will be created when\n// mapping, for example, a large number of decorations. The number's\n// lower 16 bits provide the index, the remaining bits the offset.\n//\n// Note: We intentionally don't use bit shift operators to en- and\n// decode these, since those clip to 32 bits, which we might in rare\n// cases want to overflow. A 64-bit float can represent 48-bit\n// integers precisely.\n\nvar lower16 = 0xffff;\nvar factor16 = Math.pow(2, 16);\n\nfunction makeRecover(index, offset) { return index + offset * factor16 }\nfunction recoverIndex(value) { return value & lower16 }\nfunction recoverOffset(value) { return (value - (value & lower16)) / factor16 }\n\n// ::- An object representing a mapped position with extra\n// information.\nvar MapResult = function MapResult(pos, deleted, recover) {\n if ( deleted === void 0 ) deleted = false;\n if ( recover === void 0 ) recover = null;\n\n // :: number The mapped version of the position.\n this.pos = pos;\n // :: bool Tells you whether the position was deleted, that is,\n // whether the step removed its surroundings from the document.\n this.deleted = deleted;\n this.recover = recover;\n};\n\n// :: class extends Mappable\n// A map describing the deletions and insertions made by a step, which\n// can be used to find the correspondence between positions in the\n// pre-step version of a document and the same position in the\n// post-step version.\nvar StepMap = function StepMap(ranges, inverted) {\n if ( inverted === void 0 ) inverted = false;\n\n this.ranges = ranges;\n this.inverted = inverted;\n};\n\nStepMap.prototype.recover = function recover (value) {\n var diff = 0, index = recoverIndex(value);\n if (!this.inverted) { for (var i = 0; i < index; i++)\n { diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1]; } }\n return this.ranges[index * 3] + diff + recoverOffset(value)\n};\n\n// : (number, ?number) → MapResult\nStepMap.prototype.mapResult = function mapResult (pos, assoc) {\n if ( assoc === void 0 ) assoc = 1;\n return this._map(pos, assoc, false) };\n\n// : (number, ?number) → number\nStepMap.prototype.map = function map (pos, assoc) {\n if ( assoc === void 0 ) assoc = 1;\n return this._map(pos, assoc, true) };\n\nStepMap.prototype._map = function _map (pos, assoc, simple) {\n var diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (var i = 0; i < this.ranges.length; i += 3) {\n var start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos) { break }\n var oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;\n if (pos <= end) {\n var side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;\n var result = start + diff + (side < 0 ? 0 : newSize);\n if (simple) { return result }\n var recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);\n return new MapResult(result, assoc < 0 ? pos != start : pos != end, recover)\n }\n diff += newSize - oldSize;\n }\n return simple ? pos + diff : new MapResult(pos + diff)\n};\n\nStepMap.prototype.touches = function touches (pos, recover) {\n var diff = 0, index = recoverIndex(recover);\n var oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (var i = 0; i < this.ranges.length; i += 3) {\n var start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos) { break }\n var oldSize = this.ranges[i + oldIndex], end = start + oldSize;\n if (pos <= end && i == index * 3) { return true }\n diff += this.ranges[i + newIndex] - oldSize;\n }\n return false\n};\n\n// :: ((oldStart: number, oldEnd: number, newStart: number, newEnd: number))\n// Calls the given function on each of the changed ranges included in\n// this map.\nStepMap.prototype.forEach = function forEach (f) {\n var oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (var i = 0, diff = 0; i < this.ranges.length; i += 3) {\n var start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);\n var oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];\n f(oldStart, oldStart + oldSize, newStart, newStart + newSize);\n diff += newSize - oldSize;\n }\n};\n\n// :: () → StepMap\n// Create an inverted version of this map. The result can be used to\n// map positions in the post-step document to the pre-step document.\nStepMap.prototype.invert = function invert () {\n return new StepMap(this.ranges, !this.inverted)\n};\n\nStepMap.prototype.toString = function toString () {\n return (this.inverted ? \"-\" : \"\") + JSON.stringify(this.ranges)\n};\n\n// :: (n: number) → StepMap\n// Create a map that moves all positions by offset `n` (which may be\n// negative). This can be useful when applying steps meant for a\n// sub-document to a larger document, or vice-versa.\nStepMap.offset = function offset (n) {\n return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n])\n};\n\nStepMap.empty = new StepMap([]);\n\n// :: class extends Mappable\n// A mapping represents a pipeline of zero or more [step\n// maps](#transform.StepMap). It has special provisions for losslessly\n// handling mapping positions through a series of steps in which some\n// steps are inverted versions of earlier steps. (This comes up when\n// ‘[rebasing](/docs/guide/#transform.rebasing)’ steps for\n// collaboration or history management.)\nvar Mapping = function Mapping(maps, mirror, from, to) {\n // :: [StepMap]\n // The step maps in this mapping.\n this.maps = maps || [];\n // :: number\n // The starting position in the `maps` array, used when `map` or\n // `mapResult` is called.\n this.from = from || 0;\n // :: number\n // The end position in the `maps` array.\n this.to = to == null ? this.maps.length : to;\n this.mirror = mirror;\n};\n\n// :: (?number, ?number) → Mapping\n// Create a mapping that maps only through a part of this one.\nMapping.prototype.slice = function slice (from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.maps.length;\n\n return new Mapping(this.maps, this.mirror, from, to)\n};\n\nMapping.prototype.copy = function copy () {\n return new Mapping(this.maps.slice(), this.mirror && this.mirror.slice(), this.from, this.to)\n};\n\n// :: (StepMap, ?number)\n// Add a step map to the end of this mapping. If `mirrors` is\n// given, it should be the index of the step map that is the mirror\n// image of this one.\nMapping.prototype.appendMap = function appendMap (map, mirrors) {\n this.to = this.maps.push(map);\n if (mirrors != null) { this.setMirror(this.maps.length - 1, mirrors); }\n};\n\n// :: (Mapping)\n// Add all the step maps in a given mapping to this one (preserving\n// mirroring information).\nMapping.prototype.appendMapping = function appendMapping (mapping) {\n for (var i = 0, startSize = this.maps.length; i < mapping.maps.length; i++) {\n var mirr = mapping.getMirror(i);\n this.appendMap(mapping.maps[i], mirr != null && mirr < i ? startSize + mirr : null);\n }\n};\n\n// :: (number) → ?number\n// Finds the offset of the step map that mirrors the map at the\n// given offset, in this mapping (as per the second argument to\n// `appendMap`).\nMapping.prototype.getMirror = function getMirror (n) {\n if (this.mirror) { for (var i = 0; i < this.mirror.length; i++)\n { if (this.mirror[i] == n) { return this.mirror[i + (i % 2 ? -1 : 1)] } } }\n};\n\nMapping.prototype.setMirror = function setMirror (n, m) {\n if (!this.mirror) { this.mirror = []; }\n this.mirror.push(n, m);\n};\n\n// :: (Mapping)\n// Append the inverse of the given mapping to this one.\nMapping.prototype.appendMappingInverted = function appendMappingInverted (mapping) {\n for (var i = mapping.maps.length - 1, totalSize = this.maps.length + mapping.maps.length; i >= 0; i--) {\n var mirr = mapping.getMirror(i);\n this.appendMap(mapping.maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : null);\n }\n};\n\n// :: () → Mapping\n// Create an inverted version of this mapping.\nMapping.prototype.invert = function invert () {\n var inverse = new Mapping;\n inverse.appendMappingInverted(this);\n return inverse\n};\n\n// : (number, ?number) → number\n// Map a position through this mapping.\nMapping.prototype.map = function map (pos, assoc) {\n if ( assoc === void 0 ) assoc = 1;\n\n if (this.mirror) { return this._map(pos, assoc, true) }\n for (var i = this.from; i < this.to; i++)\n { pos = this.maps[i].map(pos, assoc); }\n return pos\n};\n\n// : (number, ?number) → MapResult\n// Map a position through this mapping, returning a mapping\n// result.\nMapping.prototype.mapResult = function mapResult (pos, assoc) {\n if ( assoc === void 0 ) assoc = 1;\n return this._map(pos, assoc, false) };\n\nMapping.prototype._map = function _map (pos, assoc, simple) {\n var deleted = false;\n\n for (var i = this.from; i < this.to; i++) {\n var map = this.maps[i], result = map.mapResult(pos, assoc);\n if (result.recover != null) {\n var corr = this.getMirror(i);\n if (corr != null && corr > i && corr < this.to) {\n i = corr;\n pos = this.maps[corr].recover(result.recover);\n continue\n }\n }\n\n if (result.deleted) { deleted = true; }\n pos = result.pos;\n }\n\n return simple ? pos : new MapResult(pos, deleted)\n};\n\nfunction TransformError(message) {\n var err = Error.call(this, message);\n err.__proto__ = TransformError.prototype;\n return err\n}\n\nTransformError.prototype = Object.create(Error.prototype);\nTransformError.prototype.constructor = TransformError;\nTransformError.prototype.name = \"TransformError\";\n\n// ::- Abstraction to build up and track an array of\n// [steps](#transform.Step) representing a document transformation.\n//\n// Most transforming methods return the `Transform` object itself, so\n// that they can be chained.\nvar Transform = function Transform(doc) {\n // :: Node\n // The current document (the result of applying the steps in the\n // transform).\n this.doc = doc;\n // :: [Step]\n // The steps in this transform.\n this.steps = [];\n // :: [Node]\n // The documents before each of the steps.\n this.docs = [];\n // :: Mapping\n // A mapping with the maps for each of the steps in this transform.\n this.mapping = new Mapping;\n};\n\nvar prototypeAccessors = { before: { configurable: true },docChanged: { configurable: true } };\n\n// :: Node The starting document.\nprototypeAccessors.before.get = function () { return this.docs.length ? this.docs[0] : this.doc };\n\n// :: (step: Step) → this\n// Apply a new step in this transform, saving the result. Throws an\n// error when the step fails.\nTransform.prototype.step = function step (object) {\n var result = this.maybeStep(object);\n if (result.failed) { throw new TransformError(result.failed) }\n return this\n};\n\n// :: (Step) → StepResult\n// Try to apply a step in this transformation, ignoring it if it\n// fails. Returns the step result.\nTransform.prototype.maybeStep = function maybeStep (step) {\n var result = step.apply(this.doc);\n if (!result.failed) { this.addStep(step, result.doc); }\n return result\n};\n\n// :: bool\n// True when the document has been changed (when there are any\n// steps).\nprototypeAccessors.docChanged.get = function () {\n return this.steps.length > 0\n};\n\nTransform.prototype.addStep = function addStep (step, doc) {\n this.docs.push(this.doc);\n this.steps.push(step);\n this.mapping.appendMap(step.getMap());\n this.doc = doc;\n};\n\nObject.defineProperties( Transform.prototype, prototypeAccessors );\n\nfunction mustOverride() { throw new Error(\"Override me\") }\n\nvar stepsByID = Object.create(null);\n\n// ::- A step object represents an atomic change. It generally applies\n// only to the document it was created for, since the positions\n// stored in it will only make sense for that document.\n//\n// New steps are defined by creating classes that extend `Step`,\n// overriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`\n// methods, and registering your class with a unique\n// JSON-serialization identifier using\n// [`Step.jsonID`](#transform.Step^jsonID).\nvar Step = function Step () {};\n\nStep.prototype.apply = function apply (_doc) { return mustOverride() };\n\n// :: () → StepMap\n// Get the step map that represents the changes made by this step,\n// and which can be used to transform between positions in the old\n// and the new document.\nStep.prototype.getMap = function getMap () { return StepMap.empty };\n\n// :: (doc: Node) → Step\n// Create an inverted version of this step. Needs the document as it\n// was before the step as argument.\nStep.prototype.invert = function invert (_doc) { return mustOverride() };\n\n// :: (mapping: Mappable) → ?Step\n// Map this step through a mappable thing, returning either a\n// version of that step with its positions adjusted, or `null` if\n// the step was entirely deleted by the mapping.\nStep.prototype.map = function map (_mapping) { return mustOverride() };\n\n// :: (other: Step) → ?Step\n// Try to merge this step with another one, to be applied directly\n// after it. Returns the merged step when possible, null if the\n// steps can't be merged.\nStep.prototype.merge = function merge (_other) { return null };\n\n// :: () → Object\n// Create a JSON-serializeable representation of this step. When\n// defining this for a custom subclass, make sure the result object\n// includes the step type's [JSON id](#transform.Step^jsonID) under\n// the `stepType` property.\nStep.prototype.toJSON = function toJSON () { return mustOverride() };\n\n// :: (Schema, Object) → Step\n// Deserialize a step from its JSON representation. Will call\n// through to the step class' own implementation of this method.\nStep.fromJSON = function fromJSON (schema, json) {\n if (!json || !json.stepType) { throw new RangeError(\"Invalid input for Step.fromJSON\") }\n var type = stepsByID[json.stepType];\n if (!type) { throw new RangeError((\"No step type \" + (json.stepType) + \" defined\")) }\n return type.fromJSON(schema, json)\n};\n\n// :: (string, constructor)\n// To be able to serialize steps to JSON, each step needs a string\n// ID to attach to its JSON representation. Use this method to\n// register an ID for your step classes. Try to pick something\n// that's unlikely to clash with steps from other modules.\nStep.jsonID = function jsonID (id, stepClass) {\n if (id in stepsByID) { throw new RangeError(\"Duplicate use of step JSON ID \" + id) }\n stepsByID[id] = stepClass;\n stepClass.prototype.jsonID = id;\n return stepClass\n};\n\n// ::- The result of [applying](#transform.Step.apply) a step. Contains either a\n// new document or a failure value.\nvar StepResult = function StepResult(doc, failed) {\n // :: ?Node The transformed document.\n this.doc = doc;\n // :: ?string Text providing information about a failed step.\n this.failed = failed;\n};\n\n// :: (Node) → StepResult\n// Create a successful step result.\nStepResult.ok = function ok (doc) { return new StepResult(doc, null) };\n\n// :: (string) → StepResult\n// Create a failed step result.\nStepResult.fail = function fail (message) { return new StepResult(null, message) };\n\n// :: (Node, number, number, Slice) → StepResult\n// Call [`Node.replace`](#model.Node.replace) with the given\n// arguments. Create a successful result if it succeeds, and a\n// failed one if it throws a `ReplaceError`.\nStepResult.fromReplace = function fromReplace (doc, from, to, slice) {\n try {\n return StepResult.ok(doc.replace(from, to, slice))\n } catch (e) {\n if (e instanceof ReplaceError) { return StepResult.fail(e.message) }\n throw e\n }\n};\n\n// ::- Replace a part of the document with a slice of new content.\nvar ReplaceStep = /*@__PURE__*/(function (Step) {\n function ReplaceStep(from, to, slice, structure) {\n Step.call(this);\n this.from = from;\n this.to = to;\n this.slice = slice;\n this.structure = !!structure;\n }\n\n if ( Step ) ReplaceStep.__proto__ = Step;\n ReplaceStep.prototype = Object.create( Step && Step.prototype );\n ReplaceStep.prototype.constructor = ReplaceStep;\n\n ReplaceStep.prototype.apply = function apply (doc) {\n if (this.structure && contentBetween(doc, this.from, this.to))\n { return StepResult.fail(\"Structure replace would overwrite content\") }\n return StepResult.fromReplace(doc, this.from, this.to, this.slice)\n };\n\n ReplaceStep.prototype.getMap = function getMap () {\n return new StepMap([this.from, this.to - this.from, this.slice.size])\n };\n\n ReplaceStep.prototype.invert = function invert (doc) {\n return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to))\n };\n\n ReplaceStep.prototype.map = function map (mapping) {\n var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted) { return null }\n return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice)\n };\n\n ReplaceStep.prototype.merge = function merge (other) {\n if (!(other instanceof ReplaceStep) || other.structure != this.structure) { return null }\n\n if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {\n var slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);\n return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure)\n } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {\n var slice$1 = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);\n return new ReplaceStep(other.from, this.to, slice$1, this.structure)\n } else {\n return null\n }\n };\n\n ReplaceStep.prototype.toJSON = function toJSON () {\n var json = {stepType: \"replace\", from: this.from, to: this.to};\n if (this.slice.size) { json.slice = this.slice.toJSON(); }\n if (this.structure) { json.structure = true; }\n return json\n };\n\n ReplaceStep.fromJSON = function fromJSON (schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n { throw new RangeError(\"Invalid input for ReplaceStep.fromJSON\") }\n return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure)\n };\n\n return ReplaceStep;\n}(Step));\n\nStep.jsonID(\"replace\", ReplaceStep);\n\n// ::- Replace a part of the document with a slice of content, but\n// preserve a range of the replaced content by moving it into the\n// slice.\nvar ReplaceAroundStep = /*@__PURE__*/(function (Step) {\n function ReplaceAroundStep(from, to, gapFrom, gapTo, slice, insert, structure) {\n Step.call(this);\n this.from = from;\n this.to = to;\n this.gapFrom = gapFrom;\n this.gapTo = gapTo;\n this.slice = slice;\n this.insert = insert;\n this.structure = !!structure;\n }\n\n if ( Step ) ReplaceAroundStep.__proto__ = Step;\n ReplaceAroundStep.prototype = Object.create( Step && Step.prototype );\n ReplaceAroundStep.prototype.constructor = ReplaceAroundStep;\n\n ReplaceAroundStep.prototype.apply = function apply (doc) {\n if (this.structure && (contentBetween(doc, this.from, this.gapFrom) ||\n contentBetween(doc, this.gapTo, this.to)))\n { return StepResult.fail(\"Structure gap-replace would overwrite content\") }\n\n var gap = doc.slice(this.gapFrom, this.gapTo);\n if (gap.openStart || gap.openEnd)\n { return StepResult.fail(\"Gap is not a flat range\") }\n var inserted = this.slice.insertAt(this.insert, gap.content);\n if (!inserted) { return StepResult.fail(\"Content does not fit in gap\") }\n return StepResult.fromReplace(doc, this.from, this.to, inserted)\n };\n\n ReplaceAroundStep.prototype.getMap = function getMap () {\n return new StepMap([this.from, this.gapFrom - this.from, this.insert,\n this.gapTo, this.to - this.gapTo, this.slice.size - this.insert])\n };\n\n ReplaceAroundStep.prototype.invert = function invert (doc) {\n var gap = this.gapTo - this.gapFrom;\n return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap,\n this.from + this.insert, this.from + this.insert + gap,\n doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from),\n this.gapFrom - this.from, this.structure)\n };\n\n ReplaceAroundStep.prototype.map = function map (mapping) {\n var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n var gapFrom = mapping.map(this.gapFrom, -1), gapTo = mapping.map(this.gapTo, 1);\n if ((from.deleted && to.deleted) || gapFrom < from.pos || gapTo > to.pos) { return null }\n return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure)\n };\n\n ReplaceAroundStep.prototype.toJSON = function toJSON () {\n var json = {stepType: \"replaceAround\", from: this.from, to: this.to,\n gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert};\n if (this.slice.size) { json.slice = this.slice.toJSON(); }\n if (this.structure) { json.structure = true; }\n return json\n };\n\n ReplaceAroundStep.fromJSON = function fromJSON (schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\" ||\n typeof json.gapFrom != \"number\" || typeof json.gapTo != \"number\" || typeof json.insert != \"number\")\n { throw new RangeError(\"Invalid input for ReplaceAroundStep.fromJSON\") }\n return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo,\n Slice.fromJSON(schema, json.slice), json.insert, !!json.structure)\n };\n\n return ReplaceAroundStep;\n}(Step));\n\nStep.jsonID(\"replaceAround\", ReplaceAroundStep);\n\nfunction contentBetween(doc, from, to) {\n var $from = doc.resolve(from), dist = to - from, depth = $from.depth;\n while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {\n depth--;\n dist--;\n }\n if (dist > 0) {\n var next = $from.node(depth).maybeChild($from.indexAfter(depth));\n while (dist > 0) {\n if (!next || next.isLeaf) { return true }\n next = next.firstChild;\n dist--;\n }\n }\n return false\n}\n\nfunction canCut(node, start, end) {\n return (start == 0 || node.canReplace(start, node.childCount)) &&\n (end == node.childCount || node.canReplace(0, end))\n}\n\n// :: (NodeRange) → ?number\n// Try to find a target depth to which the content in the given range\n// can be lifted. Will not go across\n// [isolating](#model.NodeSpec.isolating) parent nodes.\nfunction liftTarget(range) {\n var parent = range.parent;\n var content = parent.content.cutByIndex(range.startIndex, range.endIndex);\n for (var depth = range.depth;; --depth) {\n var node = range.$from.node(depth);\n var index = range.$from.index(depth), endIndex = range.$to.indexAfter(depth);\n if (depth < range.depth && node.canReplace(index, endIndex, content))\n { return depth }\n if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex)) { break }\n }\n}\n\n// :: (NodeRange, number) → this\n// Split the content in the given range off from its parent, if there\n// is sibling content before or after it, and move it up the tree to\n// the depth specified by `target`. You'll probably want to use\n// [`liftTarget`](#transform.liftTarget) to compute `target`, to make\n// sure the lift is valid.\nTransform.prototype.lift = function(range, target) {\n var $from = range.$from;\n var $to = range.$to;\n var depth = range.depth;\n\n var gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);\n var start = gapStart, end = gapEnd;\n\n var before = Fragment.empty, openStart = 0;\n for (var d = depth, splitting = false; d > target; d--)\n { if (splitting || $from.index(d) > 0) {\n splitting = true;\n before = Fragment.from($from.node(d).copy(before));\n openStart++;\n } else {\n start--;\n } }\n var after = Fragment.empty, openEnd = 0;\n for (var d$1 = depth, splitting$1 = false; d$1 > target; d$1--)\n { if (splitting$1 || $to.after(d$1 + 1) < $to.end(d$1)) {\n splitting$1 = true;\n after = Fragment.from($to.node(d$1).copy(after));\n openEnd++;\n } else {\n end++;\n } }\n\n return this.step(new ReplaceAroundStep(start, end, gapStart, gapEnd,\n new Slice(before.append(after), openStart, openEnd),\n before.size - openStart, true))\n};\n\n// :: (NodeRange, NodeType, ?Object, ?NodeRange) → ?[{type: NodeType, attrs: ?Object}]\n// Try to find a valid way to wrap the content in the given range in a\n// node of the given type. May introduce extra nodes around and inside\n// the wrapper node, if necessary. Returns null if no valid wrapping\n// could be found. When `innerRange` is given, that range's content is\n// used as the content to fit into the wrapping, instead of the\n// content of `range`.\nfunction findWrapping(range, nodeType, attrs, innerRange) {\n if ( innerRange === void 0 ) innerRange = range;\n\n var around = findWrappingOutside(range, nodeType);\n var inner = around && findWrappingInside(innerRange, nodeType);\n if (!inner) { return null }\n return around.map(withAttrs).concat({type: nodeType, attrs: attrs}).concat(inner.map(withAttrs))\n}\n\nfunction withAttrs(type) { return {type: type, attrs: null} }\n\nfunction findWrappingOutside(range, type) {\n var parent = range.parent;\n var startIndex = range.startIndex;\n var endIndex = range.endIndex;\n var around = parent.contentMatchAt(startIndex).findWrapping(type);\n if (!around) { return null }\n var outer = around.length ? around[0] : type;\n return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null\n}\n\nfunction findWrappingInside(range, type) {\n var parent = range.parent;\n var startIndex = range.startIndex;\n var endIndex = range.endIndex;\n var inner = parent.child(startIndex);\n var inside = type.contentMatch.findWrapping(inner.type);\n if (!inside) { return null }\n var lastType = inside.length ? inside[inside.length - 1] : type;\n var innerMatch = lastType.contentMatch;\n for (var i = startIndex; innerMatch && i < endIndex; i++)\n { innerMatch = innerMatch.matchType(parent.child(i).type); }\n if (!innerMatch || !innerMatch.validEnd) { return null }\n return inside\n}\n\n// :: (NodeRange, [{type: NodeType, attrs: ?Object}]) → this\n// Wrap the given [range](#model.NodeRange) in the given set of wrappers.\n// The wrappers are assumed to be valid in this position, and should\n// probably be computed with [`findWrapping`](#transform.findWrapping).\nTransform.prototype.wrap = function(range, wrappers) {\n var content = Fragment.empty;\n for (var i = wrappers.length - 1; i >= 0; i--)\n { content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content)); }\n\n var start = range.start, end = range.end;\n return this.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true))\n};\n\n// :: (number, ?number, NodeType, ?Object) → this\n// Set the type of all textblocks (partly) between `from` and `to` to\n// the given node type with the given attributes.\nTransform.prototype.setBlockType = function(from, to, type, attrs) {\n var this$1 = this;\n if ( to === void 0 ) to = from;\n\n if (!type.isTextblock) { throw new RangeError(\"Type given to setBlockType should be a textblock\") }\n var mapFrom = this.steps.length;\n this.doc.nodesBetween(from, to, function (node, pos) {\n if (node.isTextblock && !node.hasMarkup(type, attrs) && canChangeType(this$1.doc, this$1.mapping.slice(mapFrom).map(pos), type)) {\n // Ensure all markup that isn't allowed in the new node type is cleared\n this$1.clearIncompatible(this$1.mapping.slice(mapFrom).map(pos, 1), type);\n var mapping = this$1.mapping.slice(mapFrom);\n var startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);\n this$1.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1,\n new Slice(Fragment.from(type.create(attrs, null, node.marks)), 0, 0), 1, true));\n return false\n }\n });\n return this\n};\n\nfunction canChangeType(doc, pos, type) {\n var $pos = doc.resolve(pos), index = $pos.index();\n return $pos.parent.canReplaceWith(index, index + 1, type)\n}\n\n// :: (number, ?NodeType, ?Object, ?[Mark]) → this\n// Change the type, attributes, and/or marks of the node at `pos`.\n// When `type` isn't given, the existing node type is preserved,\nTransform.prototype.setNodeMarkup = function(pos, type, attrs, marks) {\n var node = this.doc.nodeAt(pos);\n if (!node) { throw new RangeError(\"No node at given position\") }\n if (!type) { type = node.type; }\n var newNode = type.create(attrs, null, marks || node.marks);\n if (node.isLeaf)\n { return this.replaceWith(pos, pos + node.nodeSize, newNode) }\n\n if (!type.validContent(node.content))\n { throw new RangeError(\"Invalid content for node type \" + type.name) }\n\n return this.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1,\n new Slice(Fragment.from(newNode), 0, 0), 1, true))\n};\n\n// :: (Node, number, number, ?[?{type: NodeType, attrs: ?Object}]) → bool\n// Check whether splitting at the given position is allowed.\nfunction canSplit(doc, pos, depth, typesAfter) {\n if ( depth === void 0 ) depth = 1;\n\n var $pos = doc.resolve(pos), base = $pos.depth - depth;\n var innerType = (typesAfter && typesAfter[typesAfter.length - 1]) || $pos.parent;\n if (base < 0 || $pos.parent.type.spec.isolating ||\n !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) ||\n !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))\n { return false }\n for (var d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {\n var node = $pos.node(d), index$1 = $pos.index(d);\n if (node.type.spec.isolating) { return false }\n var rest = node.content.cutByIndex(index$1, node.childCount);\n var after = (typesAfter && typesAfter[i]) || node;\n if (after != node) { rest = rest.replaceChild(0, after.type.create(after.attrs)); }\n if (!node.canReplace(index$1 + 1, node.childCount) || !after.type.validContent(rest))\n { return false }\n }\n var index = $pos.indexAfter(base);\n var baseType = typesAfter && typesAfter[0];\n return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type)\n}\n\n// :: (number, ?number, ?[?{type: NodeType, attrs: ?Object}]) → this\n// Split the node at the given position, and optionally, if `depth` is\n// greater than one, any number of nodes above that. By default, the\n// parts split off will inherit the node type of the original node.\n// This can be changed by passing an array of types and attributes to\n// use after the split.\nTransform.prototype.split = function(pos, depth, typesAfter) {\n if ( depth === void 0 ) depth = 1;\n\n var $pos = this.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;\n for (var d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {\n before = Fragment.from($pos.node(d).copy(before));\n var typeAfter = typesAfter && typesAfter[i];\n after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));\n }\n return this.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true))\n};\n\n// :: (Node, number) → bool\n// Test whether the blocks before and after a given position can be\n// joined.\nfunction canJoin(doc, pos) {\n var $pos = doc.resolve(pos), index = $pos.index();\n return joinable($pos.nodeBefore, $pos.nodeAfter) &&\n $pos.parent.canReplace(index, index + 1)\n}\n\nfunction joinable(a, b) {\n return a && b && !a.isLeaf && a.canAppend(b)\n}\n\n// :: (Node, number, ?number) → ?number\n// Find an ancestor of the given position that can be joined to the\n// block before (or after if `dir` is positive). Returns the joinable\n// point, if any.\nfunction joinPoint(doc, pos, dir) {\n if ( dir === void 0 ) dir = -1;\n\n var $pos = doc.resolve(pos);\n for (var d = $pos.depth;; d--) {\n var before = (void 0), after = (void 0), index = $pos.index(d);\n if (d == $pos.depth) {\n before = $pos.nodeBefore;\n after = $pos.nodeAfter;\n } else if (dir > 0) {\n before = $pos.node(d + 1);\n index++;\n after = $pos.node(d).maybeChild(index);\n } else {\n before = $pos.node(d).maybeChild(index - 1);\n after = $pos.node(d + 1);\n }\n if (before && !before.isTextblock && joinable(before, after) &&\n $pos.node(d).canReplace(index, index + 1)) { return pos }\n if (d == 0) { break }\n pos = dir < 0 ? $pos.before(d) : $pos.after(d);\n }\n}\n\n// :: (number, ?number) → this\n// Join the blocks around the given position. If depth is 2, their\n// last and first siblings are also joined, and so on.\nTransform.prototype.join = function(pos, depth) {\n if ( depth === void 0 ) depth = 1;\n\n var step = new ReplaceStep(pos - depth, pos + depth, Slice.empty, true);\n return this.step(step)\n};\n\n// :: (Node, number, NodeType) → ?number\n// Try to find a point where a node of the given type can be inserted\n// near `pos`, by searching up the node hierarchy when `pos` itself\n// isn't a valid place but is at the start or end of a node. Return\n// null if no position was found.\nfunction insertPoint(doc, pos, nodeType) {\n var $pos = doc.resolve(pos);\n if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType)) { return pos }\n\n if ($pos.parentOffset == 0)\n { for (var d = $pos.depth - 1; d >= 0; d--) {\n var index = $pos.index(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType)) { return $pos.before(d + 1) }\n if (index > 0) { return null }\n } }\n if ($pos.parentOffset == $pos.parent.content.size)\n { for (var d$1 = $pos.depth - 1; d$1 >= 0; d$1--) {\n var index$1 = $pos.indexAfter(d$1);\n if ($pos.node(d$1).canReplaceWith(index$1, index$1, nodeType)) { return $pos.after(d$1 + 1) }\n if (index$1 < $pos.node(d$1).childCount) { return null }\n } }\n}\n\n// :: (Node, number, Slice) → ?number\n// Finds a position at or around the given position where the given\n// slice can be inserted. Will look at parent nodes' nearest boundary\n// and try there, even if the original position wasn't directly at the\n// start or end of that node. Returns null when no position was found.\nfunction dropPoint(doc, pos, slice) {\n var $pos = doc.resolve(pos);\n if (!slice.content.size) { return pos }\n var content = slice.content;\n for (var i = 0; i < slice.openStart; i++) { content = content.firstChild.content; }\n for (var pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {\n for (var d = $pos.depth; d >= 0; d--) {\n var bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;\n var insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);\n if (pass == 1\n ? $pos.node(d).canReplace(insertPos, insertPos, content)\n : $pos.node(d).contentMatchAt(insertPos).findWrapping(content.firstChild.type))\n { return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1) }\n }\n }\n return null\n}\n\nfunction mapFragment(fragment, f, parent) {\n var mapped = [];\n for (var i = 0; i < fragment.childCount; i++) {\n var child = fragment.child(i);\n if (child.content.size) { child = child.copy(mapFragment(child.content, f, child)); }\n if (child.isInline) { child = f(child, parent, i); }\n mapped.push(child);\n }\n return Fragment.fromArray(mapped)\n}\n\n// ::- Add a mark to all inline content between two positions.\nvar AddMarkStep = /*@__PURE__*/(function (Step) {\n function AddMarkStep(from, to, mark) {\n Step.call(this);\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n\n if ( Step ) AddMarkStep.__proto__ = Step;\n AddMarkStep.prototype = Object.create( Step && Step.prototype );\n AddMarkStep.prototype.constructor = AddMarkStep;\n\n AddMarkStep.prototype.apply = function apply (doc) {\n var this$1 = this;\n\n var oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from);\n var parent = $from.node($from.sharedDepth(this.to));\n var slice = new Slice(mapFragment(oldSlice.content, function (node, parent) {\n if (!parent.type.allowsMarkType(this$1.mark.type)) { return node }\n return node.mark(this$1.mark.addToSet(node.marks))\n }, parent), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice)\n };\n\n AddMarkStep.prototype.invert = function invert () {\n return new RemoveMarkStep(this.from, this.to, this.mark)\n };\n\n AddMarkStep.prototype.map = function map (mapping) {\n var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos) { return null }\n return new AddMarkStep(from.pos, to.pos, this.mark)\n };\n\n AddMarkStep.prototype.merge = function merge (other) {\n if (other instanceof AddMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n { return new AddMarkStep(Math.min(this.from, other.from),\n Math.max(this.to, other.to), this.mark) }\n };\n\n AddMarkStep.prototype.toJSON = function toJSON () {\n return {stepType: \"addMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to}\n };\n\n AddMarkStep.fromJSON = function fromJSON (schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n { throw new RangeError(\"Invalid input for AddMarkStep.fromJSON\") }\n return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark))\n };\n\n return AddMarkStep;\n}(Step));\n\nStep.jsonID(\"addMark\", AddMarkStep);\n\n// ::- Remove a mark from all inline content between two positions.\nvar RemoveMarkStep = /*@__PURE__*/(function (Step) {\n function RemoveMarkStep(from, to, mark) {\n Step.call(this);\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n\n if ( Step ) RemoveMarkStep.__proto__ = Step;\n RemoveMarkStep.prototype = Object.create( Step && Step.prototype );\n RemoveMarkStep.prototype.constructor = RemoveMarkStep;\n\n RemoveMarkStep.prototype.apply = function apply (doc) {\n var this$1 = this;\n\n var oldSlice = doc.slice(this.from, this.to);\n var slice = new Slice(mapFragment(oldSlice.content, function (node) {\n return node.mark(this$1.mark.removeFromSet(node.marks))\n }), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice)\n };\n\n RemoveMarkStep.prototype.invert = function invert () {\n return new AddMarkStep(this.from, this.to, this.mark)\n };\n\n RemoveMarkStep.prototype.map = function map (mapping) {\n var from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos) { return null }\n return new RemoveMarkStep(from.pos, to.pos, this.mark)\n };\n\n RemoveMarkStep.prototype.merge = function merge (other) {\n if (other instanceof RemoveMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n { return new RemoveMarkStep(Math.min(this.from, other.from),\n Math.max(this.to, other.to), this.mark) }\n };\n\n RemoveMarkStep.prototype.toJSON = function toJSON () {\n return {stepType: \"removeMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to}\n };\n\n RemoveMarkStep.fromJSON = function fromJSON (schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n { throw new RangeError(\"Invalid input for RemoveMarkStep.fromJSON\") }\n return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark))\n };\n\n return RemoveMarkStep;\n}(Step));\n\nStep.jsonID(\"removeMark\", RemoveMarkStep);\n\n// :: (number, number, Mark) → this\n// Add the given mark to the inline content between `from` and `to`.\nTransform.prototype.addMark = function(from, to, mark) {\n var this$1 = this;\n\n var removed = [], added = [], removing = null, adding = null;\n this.doc.nodesBetween(from, to, function (node, pos, parent) {\n if (!node.isInline) { return }\n var marks = node.marks;\n if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {\n var start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to);\n var newSet = mark.addToSet(marks);\n\n for (var i = 0; i < marks.length; i++) {\n if (!marks[i].isInSet(newSet)) {\n if (removing && removing.to == start && removing.mark.eq(marks[i]))\n { removing.to = end; }\n else\n { removed.push(removing = new RemoveMarkStep(start, end, marks[i])); }\n }\n }\n\n if (adding && adding.to == start)\n { adding.to = end; }\n else\n { added.push(adding = new AddMarkStep(start, end, mark)); }\n }\n });\n\n removed.forEach(function (s) { return this$1.step(s); });\n added.forEach(function (s) { return this$1.step(s); });\n return this\n};\n\n// :: (number, number, ?union) → this\n// Remove marks from inline nodes between `from` and `to`. When `mark`\n// is a single mark, remove precisely that mark. When it is a mark type,\n// remove all marks of that type. When it is null, remove all marks of\n// any type.\nTransform.prototype.removeMark = function(from, to, mark) {\n var this$1 = this;\n if ( mark === void 0 ) mark = null;\n\n var matched = [], step = 0;\n this.doc.nodesBetween(from, to, function (node, pos) {\n if (!node.isInline) { return }\n step++;\n var toRemove = null;\n if (mark instanceof MarkType) {\n var found = mark.isInSet(node.marks);\n if (found) { toRemove = [found]; }\n } else if (mark) {\n if (mark.isInSet(node.marks)) { toRemove = [mark]; }\n } else {\n toRemove = node.marks;\n }\n if (toRemove && toRemove.length) {\n var end = Math.min(pos + node.nodeSize, to);\n for (var i = 0; i < toRemove.length; i++) {\n var style = toRemove[i], found$1 = (void 0);\n for (var j = 0; j < matched.length; j++) {\n var m = matched[j];\n if (m.step == step - 1 && style.eq(matched[j].style)) { found$1 = m; }\n }\n if (found$1) {\n found$1.to = end;\n found$1.step = step;\n } else {\n matched.push({style: style, from: Math.max(pos, from), to: end, step: step});\n }\n }\n }\n });\n matched.forEach(function (m) { return this$1.step(new RemoveMarkStep(m.from, m.to, m.style)); });\n return this\n};\n\n// :: (number, NodeType, ?ContentMatch) → this\n// Removes all marks and nodes from the content of the node at `pos`\n// that don't match the given new parent node type. Accepts an\n// optional starting [content match](#model.ContentMatch) as third\n// argument.\nTransform.prototype.clearIncompatible = function(pos, parentType, match) {\n if ( match === void 0 ) match = parentType.contentMatch;\n\n var node = this.doc.nodeAt(pos);\n var delSteps = [], cur = pos + 1;\n for (var i = 0; i < node.childCount; i++) {\n var child = node.child(i), end = cur + child.nodeSize;\n var allowed = match.matchType(child.type, child.attrs);\n if (!allowed) {\n delSteps.push(new ReplaceStep(cur, end, Slice.empty));\n } else {\n match = allowed;\n for (var j = 0; j < child.marks.length; j++) { if (!parentType.allowsMarkType(child.marks[j].type))\n { this.step(new RemoveMarkStep(cur, end, child.marks[j])); } }\n }\n cur = end;\n }\n if (!match.validEnd) {\n var fill = match.fillBefore(Fragment.empty, true);\n this.replace(cur, cur, new Slice(fill, 0, 0));\n }\n for (var i$1 = delSteps.length - 1; i$1 >= 0; i$1--) { this.step(delSteps[i$1]); }\n return this\n};\n\n// :: (Node, number, ?number, ?Slice) → ?Step\n// ‘Fit’ a slice into a given position in the document, producing a\n// [step](#transform.Step) that inserts it. Will return null if\n// there's no meaningful way to insert the slice here, or inserting it\n// would be a no-op (an empty slice over an empty range).\nfunction replaceStep(doc, from, to, slice) {\n if ( to === void 0 ) to = from;\n if ( slice === void 0 ) slice = Slice.empty;\n\n if (from == to && !slice.size) { return null }\n\n var $from = doc.resolve(from), $to = doc.resolve(to);\n // Optimization -- avoid work if it's obvious that it's not needed.\n if (fitsTrivially($from, $to, slice)) { return new ReplaceStep(from, to, slice) }\n return new Fitter($from, $to, slice).fit()\n}\n\n// :: (number, ?number, ?Slice) → this\n// Replace the part of the document between `from` and `to` with the\n// given `slice`.\nTransform.prototype.replace = function(from, to, slice) {\n if ( to === void 0 ) to = from;\n if ( slice === void 0 ) slice = Slice.empty;\n\n var step = replaceStep(this.doc, from, to, slice);\n if (step) { this.step(step); }\n return this\n};\n\n// :: (number, number, union) → this\n// Replace the given range with the given content, which may be a\n// fragment, node, or array of nodes.\nTransform.prototype.replaceWith = function(from, to, content) {\n return this.replace(from, to, new Slice(Fragment.from(content), 0, 0))\n};\n\n// :: (number, number) → this\n// Delete the content between the given positions.\nTransform.prototype.delete = function(from, to) {\n return this.replace(from, to, Slice.empty)\n};\n\n// :: (number, union) → this\n// Insert the given content at the given position.\nTransform.prototype.insert = function(pos, content) {\n return this.replaceWith(pos, pos, content)\n};\n\nfunction fitsTrivially($from, $to, slice) {\n return !slice.openStart && !slice.openEnd && $from.start() == $to.start() &&\n $from.parent.canReplace($from.index(), $to.index(), slice.content)\n}\n\n// Algorithm for 'placing' the elements of a slice into a gap:\n//\n// We consider the content of each node that is open to the left to be\n// independently placeable. I.e. in , when the\n// paragraph on the left is open, \"foo\" can be placed (somewhere on\n// the left side of the replacement gap) independently from p(\"bar\").\n//\n// This class tracks the state of the placement progress in the\n// following properties:\n//\n// - `frontier` holds a stack of `{type, match}` objects that\n// represent the open side of the replacement. It starts at\n// `$from`, then moves forward as content is placed, and is finally\n// reconciled with `$to`.\n//\n// - `unplaced` is a slice that represents the content that hasn't\n// been placed yet.\n//\n// - `placed` is a fragment of placed content. Its open-start value\n// is implicit in `$from`, and its open-end value in `frontier`.\nvar Fitter = function Fitter($from, $to, slice) {\n this.$to = $to;\n this.$from = $from;\n this.unplaced = slice;\n\n this.frontier = [];\n for (var i = 0; i <= $from.depth; i++) {\n var node = $from.node(i);\n this.frontier.push({\n type: node.type,\n match: node.contentMatchAt($from.indexAfter(i))\n });\n }\n\n this.placed = Fragment.empty;\n for (var i$1 = $from.depth; i$1 > 0; i$1--)\n { this.placed = Fragment.from($from.node(i$1).copy(this.placed)); }\n};\n\nvar prototypeAccessors$1 = { depth: { configurable: true } };\n\nprototypeAccessors$1.depth.get = function () { return this.frontier.length - 1 };\n\nFitter.prototype.fit = function fit () {\n // As long as there's unplaced content, try to place some of it.\n // If that fails, either increase the open score of the unplaced\n // slice, or drop nodes from it, and then try again.\n while (this.unplaced.size) {\n var fit = this.findFittable();\n if (fit) { this.placeNodes(fit); }\n else { this.openMore() || this.dropNode(); }\n }\n // When there's inline content directly after the frontier _and_\n // directly after `this.$to`, we must generate a `ReplaceAround`\n // step that pulls that content into the node after the frontier.\n // That means the fitting must be done to the end of the textblock\n // node after `this.$to`, not `this.$to` itself.\n var moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;\n var $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));\n if (!$to) { return null }\n\n // If closing to `$to` succeeded, create a step\n var content = this.placed, openStart = $from.depth, openEnd = $to.depth;\n while (openStart && openEnd && content.childCount == 1) { // Normalize by dropping open parent nodes\n content = content.firstChild.content;\n openStart--; openEnd--;\n }\n var slice = new Slice(content, openStart, openEnd);\n if (moveInline > -1)\n { return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize) }\n if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps\n { return new ReplaceStep($from.pos, $to.pos, slice) }\n};\n\n// Find a position on the start spine of `this.unplaced` that has\n// content that can be moved somewhere on the frontier. Returns two\n// depths, one for the slice and one for the frontier.\nFitter.prototype.findFittable = function findFittable () {\n // Only try wrapping nodes (pass 2) after finding a place without\n // wrapping failed.\n for (var pass = 1; pass <= 2; pass++) {\n for (var sliceDepth = this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {\n var fragment = (void 0), parent = (void 0);\n if (sliceDepth) {\n parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;\n fragment = parent.content;\n } else {\n fragment = this.unplaced.content;\n }\n var first = fragment.firstChild;\n for (var frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {\n var ref = this.frontier[frontierDepth];\n var type = ref.type;\n var match = ref.match;\n var wrap = (void 0), inject = (void 0);\n // In pass 1, if the next node matches, or there is no next\n // node but the parents look compatible, we've found a\n // place.\n if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false))\n : type.compatibleContent(parent.type)))\n { return {sliceDepth: sliceDepth, frontierDepth: frontierDepth, parent: parent, inject: inject} }\n // In pass 2, look for a set of wrapping nodes that make\n // `first` fit here.\n else if (pass == 2 && first && (wrap = match.findWrapping(first.type)))\n { return {sliceDepth: sliceDepth, frontierDepth: frontierDepth, parent: parent, wrap: wrap} }\n // Don't continue looking further up if the parent node\n // would fit here.\n if (parent && match.matchType(parent.type)) { break }\n }\n }\n }\n};\n\nFitter.prototype.openMore = function openMore () {\n var ref = this.unplaced;\n var content = ref.content;\n var openStart = ref.openStart;\n var openEnd = ref.openEnd;\n var inner = contentAt(content, openStart);\n if (!inner.childCount || inner.firstChild.isLeaf) { return false }\n this.unplaced = new Slice(content, openStart + 1,\n Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0));\n return true\n};\n\nFitter.prototype.dropNode = function dropNode () {\n var ref = this.unplaced;\n var content = ref.content;\n var openStart = ref.openStart;\n var openEnd = ref.openEnd;\n var inner = contentAt(content, openStart);\n if (inner.childCount <= 1 && openStart > 0) {\n var openAtEnd = content.size - openStart <= openStart + inner.size;\n this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1,\n openAtEnd ? openStart - 1 : openEnd);\n } else {\n this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);\n }\n};\n\n// : ({sliceDepth: number, frontierDepth: number, parent: ?Node, wrap: ?[NodeType], inject: ?Fragment})\n// Move content from the unplaced slice at `sliceDepth` to the\n// frontier node at `frontierDepth`. Close that frontier node when\n// applicable.\nFitter.prototype.placeNodes = function placeNodes (ref) {\n var sliceDepth = ref.sliceDepth;\n var frontierDepth = ref.frontierDepth;\n var parent = ref.parent;\n var inject = ref.inject;\n var wrap = ref.wrap;\n\n while (this.depth > frontierDepth) { this.closeFrontierNode(); }\n if (wrap) { for (var i = 0; i < wrap.length; i++) { this.openFrontierNode(wrap[i]); } }\n\n var slice = this.unplaced, fragment = parent ? parent.content : slice.content;\n var openStart = slice.openStart - sliceDepth;\n var taken = 0, add = [];\n var ref$1 = this.frontier[frontierDepth];\n var match = ref$1.match;\n var type = ref$1.type;\n if (inject) {\n for (var i$1 = 0; i$1 < inject.childCount; i$1++) { add.push(inject.child(i$1)); }\n match = match.matchFragment(inject);\n }\n // Computes the amount of (end) open nodes at the end of the\n // fragment. When 0, the parent is open, but no more. When\n // negative, nothing is open.\n var openEndCount = (fragment.size + sliceDepth) - (slice.content.size - slice.openEnd);\n // Scan over the fragment, fitting as many child nodes as\n // possible.\n while (taken < fragment.childCount) {\n var next = fragment.child(taken), matches = match.matchType(next.type);\n if (!matches) { break }\n taken++;\n if (taken > 1 || openStart == 0 || next.content.size) { // Drop empty open nodes\n match = matches;\n add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0,\n taken == fragment.childCount ? openEndCount : -1));\n }\n }\n var toEnd = taken == fragment.childCount;\n if (!toEnd) { openEndCount = -1; }\n\n this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));\n this.frontier[frontierDepth].match = match;\n\n // If the parent types match, and the entire node was moved, and\n // it's not open, close this frontier node right away.\n if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type) { this.closeFrontierNode(); }\n\n // Add new frontier nodes for any open nodes at the end.\n for (var i$2 = 0, cur = fragment; i$2 < openEndCount; i$2++) {\n var node = cur.lastChild;\n this.frontier.push({type: node.type, match: node.contentMatchAt(node.childCount)});\n cur = node.content;\n }\n\n // Update `this.unplaced`. Drop the entire node from which we\n // placed it we got to its end, otherwise just drop the placed\n // nodes.\n this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd)\n : sliceDepth == 0 ? Slice.empty\n : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1),\n sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);\n};\n\nFitter.prototype.mustMoveInline = function mustMoveInline () {\n if (!this.$to.parent.isTextblock || this.$to.end() == this.$to.pos) { return -1 }\n var top = this.frontier[this.depth], level;\n if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) ||\n (this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth)) { return -1 }\n\n var ref = this.$to;\n var depth = ref.depth;\n var after = this.$to.after(depth);\n while (depth > 1 && after == this.$to.end(--depth)) { ++after; }\n return after\n};\n\nFitter.prototype.findCloseLevel = function findCloseLevel ($to) {\n scan: for (var i = Math.min(this.depth, $to.depth); i >= 0; i--) {\n var ref = this.frontier[i];\n var match = ref.match;\n var type = ref.type;\n var dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));\n var fit = contentAfterFits($to, i, type, match, dropInner);\n if (!fit) { continue }\n for (var d = i - 1; d >= 0; d--) {\n var ref$1 = this.frontier[d];\n var match$1 = ref$1.match;\n var type$1 = ref$1.type;\n var matches = contentAfterFits($to, d, type$1, match$1, true);\n if (!matches || matches.childCount) { continue scan }\n }\n return {depth: i, fit: fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to}\n }\n};\n\nFitter.prototype.close = function close ($to) {\n var close = this.findCloseLevel($to);\n if (!close) { return null }\n\n while (this.depth > close.depth) { this.closeFrontierNode(); }\n if (close.fit.childCount) { this.placed = addToFragment(this.placed, close.depth, close.fit); }\n $to = close.move;\n for (var d = close.depth + 1; d <= $to.depth; d++) {\n var node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));\n this.openFrontierNode(node.type, node.attrs, add);\n }\n return $to\n};\n\nFitter.prototype.openFrontierNode = function openFrontierNode (type, attrs, content) {\n var top = this.frontier[this.depth];\n top.match = top.match.matchType(type);\n this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));\n this.frontier.push({type: type, match: type.contentMatch});\n};\n\nFitter.prototype.closeFrontierNode = function closeFrontierNode () {\n var open = this.frontier.pop();\n var add = open.match.fillBefore(Fragment.empty, true);\n if (add.childCount) { this.placed = addToFragment(this.placed, this.frontier.length, add); }\n};\n\nObject.defineProperties( Fitter.prototype, prototypeAccessors$1 );\n\nfunction dropFromFragment(fragment, depth, count) {\n if (depth == 0) { return fragment.cutByIndex(count) }\n return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)))\n}\n\nfunction addToFragment(fragment, depth, content) {\n if (depth == 0) { return fragment.append(content) }\n return fragment.replaceChild(fragment.childCount - 1,\n fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)))\n}\n\nfunction contentAt(fragment, depth) {\n for (var i = 0; i < depth; i++) { fragment = fragment.firstChild.content; }\n return fragment\n}\n\nfunction closeNodeStart(node, openStart, openEnd) {\n if (openStart <= 0) { return node }\n var frag = node.content;\n if (openStart > 1)\n { frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0)); }\n if (openStart > 0) {\n frag = node.type.contentMatch.fillBefore(frag).append(frag);\n if (openEnd <= 0) { frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true)); }\n }\n return node.copy(frag)\n}\n\nfunction contentAfterFits($to, depth, type, match, open) {\n var node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);\n if (index == node.childCount && !type.compatibleContent(node.type)) { return null }\n var fit = match.fillBefore(node.content, true, index);\n return fit && !invalidMarks(type, node.content, index) ? fit : null\n}\n\nfunction invalidMarks(type, fragment, start) {\n for (var i = start; i < fragment.childCount; i++)\n { if (!type.allowsMarks(fragment.child(i).marks)) { return true } }\n return false\n}\n\n// :: (number, number, Slice) → this\n// Replace a range of the document with a given slice, using `from`,\n// `to`, and the slice's [`openStart`](#model.Slice.openStart) property\n// as hints, rather than fixed start and end points. This method may\n// grow the replaced area or close open nodes in the slice in order to\n// get a fit that is more in line with WYSIWYG expectations, by\n// dropping fully covered parent nodes of the replaced region when\n// they are marked [non-defining](#model.NodeSpec.defining), or\n// including an open parent node from the slice that _is_ marked as\n// [defining](#model.NodeSpec.defining).\n//\n// This is the method, for example, to handle paste. The similar\n// [`replace`](#transform.Transform.replace) method is a more\n// primitive tool which will _not_ move the start and end of its given\n// range, and is useful in situations where you need more precise\n// control over what happens.\nTransform.prototype.replaceRange = function(from, to, slice) {\n if (!slice.size) { return this.deleteRange(from, to) }\n\n var $from = this.doc.resolve(from), $to = this.doc.resolve(to);\n if (fitsTrivially($from, $to, slice))\n { return this.step(new ReplaceStep(from, to, slice)) }\n\n var targetDepths = coveredDepths($from, this.doc.resolve(to));\n // Can't replace the whole document, so remove 0 if it's present\n if (targetDepths[targetDepths.length - 1] == 0) { targetDepths.pop(); }\n // Negative numbers represent not expansion over the whole node at\n // that depth, but replacing from $from.before(-D) to $to.pos.\n var preferredTarget = -($from.depth + 1);\n targetDepths.unshift(preferredTarget);\n // This loop picks a preferred target depth, if one of the covering\n // depths is not outside of a defining node, and adds negative\n // depths for any depth that has $from at its start and does not\n // cross a defining node.\n for (var d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {\n var spec = $from.node(d).type.spec;\n if (spec.defining || spec.isolating) { break }\n if (targetDepths.indexOf(d) > -1) { preferredTarget = d; }\n else if ($from.before(d) == pos) { targetDepths.splice(1, 0, -d); }\n }\n // Try to fit each possible depth of the slice into each possible\n // target depth, starting with the preferred depths.\n var preferredTargetIndex = targetDepths.indexOf(preferredTarget);\n\n var leftNodes = [], preferredDepth = slice.openStart;\n for (var content = slice.content, i = 0;; i++) {\n var node = content.firstChild;\n leftNodes.push(node);\n if (i == slice.openStart) { break }\n content = node.content;\n }\n // Back up if the node directly above openStart, or the node above\n // that separated only by a non-defining textblock node, is defining.\n if (preferredDepth > 0 && leftNodes[preferredDepth - 1].type.spec.defining &&\n $from.node(preferredTargetIndex).type != leftNodes[preferredDepth - 1].type)\n { preferredDepth -= 1; }\n else if (preferredDepth >= 2 && leftNodes[preferredDepth - 1].isTextblock && leftNodes[preferredDepth - 2].type.spec.defining &&\n $from.node(preferredTargetIndex).type != leftNodes[preferredDepth - 2].type)\n { preferredDepth -= 2; }\n\n for (var j = slice.openStart; j >= 0; j--) {\n var openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);\n var insert = leftNodes[openDepth];\n if (!insert) { continue }\n for (var i$1 = 0; i$1 < targetDepths.length; i$1++) {\n // Loop over possible expansion levels, starting with the\n // preferred one\n var targetDepth = targetDepths[(i$1 + preferredTargetIndex) % targetDepths.length], expand = true;\n if (targetDepth < 0) { expand = false; targetDepth = -targetDepth; }\n var parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);\n if (parent.canReplaceWith(index, index, insert.type, insert.marks))\n { return this.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to,\n new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth),\n openDepth, slice.openEnd)) }\n }\n }\n\n var startSteps = this.steps.length;\n for (var i$2 = targetDepths.length - 1; i$2 >= 0; i$2--) {\n this.replace(from, to, slice);\n if (this.steps.length > startSteps) { break }\n var depth = targetDepths[i$2];\n if (i$2 < 0) { continue }\n from = $from.before(depth); to = $to.after(depth);\n }\n return this\n};\n\nfunction closeFragment(fragment, depth, oldOpen, newOpen, parent) {\n if (depth < oldOpen) {\n var first = fragment.firstChild;\n fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));\n }\n if (depth > newOpen) {\n var match = parent.contentMatchAt(0);\n var start = match.fillBefore(fragment).append(fragment);\n fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));\n }\n return fragment\n}\n\n// :: (number, number, Node) → this\n// Replace the given range with a node, but use `from` and `to` as\n// hints, rather than precise positions. When from and to are the same\n// and are at the start or end of a parent node in which the given\n// node doesn't fit, this method may _move_ them out towards a parent\n// that does allow the given node to be placed. When the given range\n// completely covers a parent node, this method may completely replace\n// that parent node.\nTransform.prototype.replaceRangeWith = function(from, to, node) {\n if (!node.isInline && from == to && this.doc.resolve(from).parent.content.size) {\n var point = insertPoint(this.doc, from, node.type);\n if (point != null) { from = to = point; }\n }\n return this.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0))\n};\n\n// :: (number, number) → this\n// Delete the given range, expanding it to cover fully covered\n// parent nodes until a valid replace is found.\nTransform.prototype.deleteRange = function(from, to) {\n var $from = this.doc.resolve(from), $to = this.doc.resolve(to);\n var covered = coveredDepths($from, $to);\n for (var i = 0; i < covered.length; i++) {\n var depth = covered[i], last = i == covered.length - 1;\n if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd)\n { return this.delete($from.start(depth), $to.end(depth)) }\n if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))\n { return this.delete($from.before(depth), $to.after(depth)) }\n }\n for (var d = 1; d <= $from.depth && d <= $to.depth; d++) {\n if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d)\n { return this.delete($from.before(d), to) }\n }\n return this.delete(from, to)\n};\n\n// : (ResolvedPos, ResolvedPos) → [number]\n// Returns an array of all depths for which $from - $to spans the\n// whole content of the nodes at that depth.\nfunction coveredDepths($from, $to) {\n var result = [], minDepth = Math.min($from.depth, $to.depth);\n for (var d = minDepth; d >= 0; d--) {\n var start = $from.start(d);\n if (start < $from.pos - ($from.depth - d) ||\n $to.end(d) > $to.pos + ($to.depth - d) ||\n $from.node(d).type.spec.isolating ||\n $to.node(d).type.spec.isolating) { break }\n if (start == $to.start(d)) { result.push(d); }\n }\n return result\n}\n\nexport { AddMarkStep, MapResult, Mapping, RemoveMarkStep, ReplaceAroundStep, ReplaceStep, Step, StepMap, StepResult, Transform, TransformError, canJoin, canSplit, dropPoint, findWrapping, insertPoint, joinPoint, liftTarget, replaceStep };\n//# sourceMappingURL=index.es.js.map\n","import { Slice, Fragment, Mark, Node } from 'prosemirror-model';\nimport { ReplaceStep, ReplaceAroundStep, Transform } from 'prosemirror-transform';\n\nvar classesById = Object.create(null);\n\n// ::- Superclass for editor selections. Every selection type should\n// extend this. Should not be instantiated directly.\nvar Selection = function Selection($anchor, $head, ranges) {\n // :: [SelectionRange]\n // The ranges covered by the selection.\n this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];\n // :: ResolvedPos\n // The resolved anchor of the selection (the side that stays in\n // place when the selection is modified).\n this.$anchor = $anchor;\n // :: ResolvedPos\n // The resolved head of the selection (the side that moves when\n // the selection is modified).\n this.$head = $head;\n};\n\nvar prototypeAccessors = { anchor: { configurable: true },head: { configurable: true },from: { configurable: true },to: { configurable: true },$from: { configurable: true },$to: { configurable: true },empty: { configurable: true } };\n\n// :: number\n// The selection's anchor, as an unresolved position.\nprototypeAccessors.anchor.get = function () { return this.$anchor.pos };\n\n// :: number\n// The selection's head.\nprototypeAccessors.head.get = function () { return this.$head.pos };\n\n// :: number\n// The lower bound of the selection's main range.\nprototypeAccessors.from.get = function () { return this.$from.pos };\n\n// :: number\n// The upper bound of the selection's main range.\nprototypeAccessors.to.get = function () { return this.$to.pos };\n\n// :: ResolvedPos\n// The resolved lowerbound of the selection's main range.\nprototypeAccessors.$from.get = function () {\n return this.ranges[0].$from\n};\n\n// :: ResolvedPos\n// The resolved upper bound of the selection's main range.\nprototypeAccessors.$to.get = function () {\n return this.ranges[0].$to\n};\n\n// :: bool\n// Indicates whether the selection contains any content.\nprototypeAccessors.empty.get = function () {\n var ranges = this.ranges;\n for (var i = 0; i < ranges.length; i++)\n { if (ranges[i].$from.pos != ranges[i].$to.pos) { return false } }\n return true\n};\n\n// eq:: (Selection) → bool\n// Test whether the selection is the same as another selection.\n\n// map:: (doc: Node, mapping: Mappable) → Selection\n// Map this selection through a [mappable](#transform.Mappable) thing. `doc`\n// should be the new document to which we are mapping.\n\n// :: () → Slice\n// Get the content of this selection as a slice.\nSelection.prototype.content = function content () {\n return this.$from.node(0).slice(this.from, this.to, true)\n};\n\n// :: (Transaction, ?Slice)\n// Replace the selection with a slice or, if no slice is given,\n// delete the selection. Will append to the given transaction.\nSelection.prototype.replace = function replace (tr, content) {\n if ( content === void 0 ) content = Slice.empty;\n\n // Put the new selection at the position after the inserted\n // content. When that ended in an inline node, search backwards,\n // to get the position after that node. If not, search forward.\n var lastNode = content.content.lastChild, lastParent = null;\n for (var i = 0; i < content.openEnd; i++) {\n lastParent = lastNode;\n lastNode = lastNode.lastChild;\n }\n\n var mapFrom = tr.steps.length, ranges = this.ranges;\n for (var i$1 = 0; i$1 < ranges.length; i$1++) {\n var ref = ranges[i$1];\n var $from = ref.$from;\n var $to = ref.$to;\n var mapping = tr.mapping.slice(mapFrom);\n tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i$1 ? Slice.empty : content);\n if (i$1 == 0)\n { selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1); }\n }\n};\n\n// :: (Transaction, Node)\n// Replace the selection with the given node, appending the changes\n// to the given transaction.\nSelection.prototype.replaceWith = function replaceWith (tr, node) {\n var mapFrom = tr.steps.length, ranges = this.ranges;\n for (var i = 0; i < ranges.length; i++) {\n var ref = ranges[i];\n var $from = ref.$from;\n var $to = ref.$to;\n var mapping = tr.mapping.slice(mapFrom);\n var from = mapping.map($from.pos), to = mapping.map($to.pos);\n if (i) {\n tr.deleteRange(from, to);\n } else {\n tr.replaceRangeWith(from, to, node);\n selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);\n }\n }\n};\n\n// toJSON:: () → Object\n// Convert the selection to a JSON representation. When implementing\n// this for a custom selection class, make sure to give the object a\n// `type` property whose value matches the ID under which you\n// [registered](#state.Selection^jsonID) your class.\n\n// :: (ResolvedPos, number, ?bool) → ?Selection\n// Find a valid cursor or leaf node selection starting at the given\n// position and searching back if `dir` is negative, and forward if\n// positive. When `textOnly` is true, only consider cursor\n// selections. Will return null when no valid selection position is\n// found.\nSelection.findFrom = function findFrom ($pos, dir, textOnly) {\n var inner = $pos.parent.inlineContent ? new TextSelection($pos)\n : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);\n if (inner) { return inner }\n\n for (var depth = $pos.depth - 1; depth >= 0; depth--) {\n var found = dir < 0\n ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly)\n : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);\n if (found) { return found }\n }\n};\n\n// :: (ResolvedPos, ?number) → Selection\n// Find a valid cursor or leaf node selection near the given\n// position. Searches forward first by default, but if `bias` is\n// negative, it will search backwards first.\nSelection.near = function near ($pos, bias) {\n if ( bias === void 0 ) bias = 1;\n\n return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0))\n};\n\n// :: (Node) → Selection\n// Find the cursor or leaf node selection closest to the start of\n// the given document. Will return an\n// [`AllSelection`](#state.AllSelection) if no valid position\n// exists.\nSelection.atStart = function atStart (doc) {\n return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc)\n};\n\n// :: (Node) → Selection\n// Find the cursor or leaf node selection closest to the end of the\n// given document.\nSelection.atEnd = function atEnd (doc) {\n return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc)\n};\n\n// :: (Node, Object) → Selection\n// Deserialize the JSON representation of a selection. Must be\n// implemented for custom classes (as a static class method).\nSelection.fromJSON = function fromJSON (doc, json) {\n if (!json || !json.type) { throw new RangeError(\"Invalid input for Selection.fromJSON\") }\n var cls = classesById[json.type];\n if (!cls) { throw new RangeError((\"No selection type \" + (json.type) + \" defined\")) }\n return cls.fromJSON(doc, json)\n};\n\n// :: (string, constructor)\n// To be able to deserialize selections from JSON, custom selection\n// classes must register themselves with an ID string, so that they\n// can be disambiguated. Try to pick something that's unlikely to\n// clash with classes from other modules.\nSelection.jsonID = function jsonID (id, selectionClass) {\n if (id in classesById) { throw new RangeError(\"Duplicate use of selection JSON ID \" + id) }\n classesById[id] = selectionClass;\n selectionClass.prototype.jsonID = id;\n return selectionClass\n};\n\n// :: () → SelectionBookmark\n// Get a [bookmark](#state.SelectionBookmark) for this selection,\n// which is a value that can be mapped without having access to a\n// current document, and later resolved to a real selection for a\n// given document again. (This is used mostly by the history to\n// track and restore old selections.) The default implementation of\n// this method just converts the selection to a text selection and\n// returns the bookmark for that.\nSelection.prototype.getBookmark = function getBookmark () {\n return TextSelection.between(this.$anchor, this.$head).getBookmark()\n};\n\nObject.defineProperties( Selection.prototype, prototypeAccessors );\n\n// :: bool\n// Controls whether, when a selection of this type is active in the\n// browser, the selected range should be visible to the user. Defaults\n// to `true`.\nSelection.prototype.visible = true;\n\n// SelectionBookmark:: interface\n// A lightweight, document-independent representation of a selection.\n// You can define a custom bookmark type for a custom selection class\n// to make the history handle it well.\n//\n// map:: (mapping: Mapping) → SelectionBookmark\n// Map the bookmark through a set of changes.\n//\n// resolve:: (doc: Node) → Selection\n// Resolve the bookmark to a real selection again. This may need to\n// do some error checking and may fall back to a default (usually\n// [`TextSelection.between`](#state.TextSelection^between)) if\n// mapping made the bookmark invalid.\n\n// ::- Represents a selected range in a document.\nvar SelectionRange = function SelectionRange($from, $to) {\n // :: ResolvedPos\n // The lower bound of the range.\n this.$from = $from;\n // :: ResolvedPos\n // The upper bound of the range.\n this.$to = $to;\n};\n\n// ::- A text selection represents a classical editor selection, with\n// a head (the moving side) and anchor (immobile side), both of which\n// point into textblock nodes. It can be empty (a regular cursor\n// position).\nvar TextSelection = /*@__PURE__*/(function (Selection) {\n function TextSelection($anchor, $head) {\n if ( $head === void 0 ) $head = $anchor;\n\n Selection.call(this, $anchor, $head);\n }\n\n if ( Selection ) TextSelection.__proto__ = Selection;\n TextSelection.prototype = Object.create( Selection && Selection.prototype );\n TextSelection.prototype.constructor = TextSelection;\n\n var prototypeAccessors$1 = { $cursor: { configurable: true } };\n\n // :: ?ResolvedPos\n // Returns a resolved position if this is a cursor selection (an\n // empty text selection), and null otherwise.\n prototypeAccessors$1.$cursor.get = function () { return this.$anchor.pos == this.$head.pos ? this.$head : null };\n\n TextSelection.prototype.map = function map (doc, mapping) {\n var $head = doc.resolve(mapping.map(this.head));\n if (!$head.parent.inlineContent) { return Selection.near($head) }\n var $anchor = doc.resolve(mapping.map(this.anchor));\n return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head)\n };\n\n TextSelection.prototype.replace = function replace (tr, content) {\n if ( content === void 0 ) content = Slice.empty;\n\n Selection.prototype.replace.call(this, tr, content);\n if (content == Slice.empty) {\n var marks = this.$from.marksAcross(this.$to);\n if (marks) { tr.ensureMarks(marks); }\n }\n };\n\n TextSelection.prototype.eq = function eq (other) {\n return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head\n };\n\n TextSelection.prototype.getBookmark = function getBookmark () {\n return new TextBookmark(this.anchor, this.head)\n };\n\n TextSelection.prototype.toJSON = function toJSON () {\n return {type: \"text\", anchor: this.anchor, head: this.head}\n };\n\n TextSelection.fromJSON = function fromJSON (doc, json) {\n if (typeof json.anchor != \"number\" || typeof json.head != \"number\")\n { throw new RangeError(\"Invalid input for TextSelection.fromJSON\") }\n return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head))\n };\n\n // :: (Node, number, ?number) → TextSelection\n // Create a text selection from non-resolved positions.\n TextSelection.create = function create (doc, anchor, head) {\n if ( head === void 0 ) head = anchor;\n\n var $anchor = doc.resolve(anchor);\n return new this($anchor, head == anchor ? $anchor : doc.resolve(head))\n };\n\n // :: (ResolvedPos, ResolvedPos, ?number) → Selection\n // Return a text selection that spans the given positions or, if\n // they aren't text positions, find a text selection near them.\n // `bias` determines whether the method searches forward (default)\n // or backwards (negative number) first. Will fall back to calling\n // [`Selection.near`](#state.Selection^near) when the document\n // doesn't contain a valid text position.\n TextSelection.between = function between ($anchor, $head, bias) {\n var dPos = $anchor.pos - $head.pos;\n if (!bias || dPos) { bias = dPos >= 0 ? 1 : -1; }\n if (!$head.parent.inlineContent) {\n var found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);\n if (found) { $head = found.$head; }\n else { return Selection.near($head, bias) }\n }\n if (!$anchor.parent.inlineContent) {\n if (dPos == 0) {\n $anchor = $head;\n } else {\n $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;\n if (($anchor.pos < $head.pos) != (dPos < 0)) { $anchor = $head; }\n }\n }\n return new TextSelection($anchor, $head)\n };\n\n Object.defineProperties( TextSelection.prototype, prototypeAccessors$1 );\n\n return TextSelection;\n}(Selection));\n\nSelection.jsonID(\"text\", TextSelection);\n\nvar TextBookmark = function TextBookmark(anchor, head) {\n this.anchor = anchor;\n this.head = head;\n};\nTextBookmark.prototype.map = function map (mapping) {\n return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head))\n};\nTextBookmark.prototype.resolve = function resolve (doc) {\n return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head))\n};\n\n// ::- A node selection is a selection that points at a single node.\n// All nodes marked [selectable](#model.NodeSpec.selectable) can be\n// the target of a node selection. In such a selection, `from` and\n// `to` point directly before and after the selected node, `anchor`\n// equals `from`, and `head` equals `to`..\nvar NodeSelection = /*@__PURE__*/(function (Selection) {\n function NodeSelection($pos) {\n var node = $pos.nodeAfter;\n var $end = $pos.node(0).resolve($pos.pos + node.nodeSize);\n Selection.call(this, $pos, $end);\n // :: Node The selected node.\n this.node = node;\n }\n\n if ( Selection ) NodeSelection.__proto__ = Selection;\n NodeSelection.prototype = Object.create( Selection && Selection.prototype );\n NodeSelection.prototype.constructor = NodeSelection;\n\n NodeSelection.prototype.map = function map (doc, mapping) {\n var ref = mapping.mapResult(this.anchor);\n var deleted = ref.deleted;\n var pos = ref.pos;\n var $pos = doc.resolve(pos);\n if (deleted) { return Selection.near($pos) }\n return new NodeSelection($pos)\n };\n\n NodeSelection.prototype.content = function content () {\n return new Slice(Fragment.from(this.node), 0, 0)\n };\n\n NodeSelection.prototype.eq = function eq (other) {\n return other instanceof NodeSelection && other.anchor == this.anchor\n };\n\n NodeSelection.prototype.toJSON = function toJSON () {\n return {type: \"node\", anchor: this.anchor}\n };\n\n NodeSelection.prototype.getBookmark = function getBookmark () { return new NodeBookmark(this.anchor) };\n\n NodeSelection.fromJSON = function fromJSON (doc, json) {\n if (typeof json.anchor != \"number\")\n { throw new RangeError(\"Invalid input for NodeSelection.fromJSON\") }\n return new NodeSelection(doc.resolve(json.anchor))\n };\n\n // :: (Node, number) → NodeSelection\n // Create a node selection from non-resolved positions.\n NodeSelection.create = function create (doc, from) {\n return new this(doc.resolve(from))\n };\n\n // :: (Node) → bool\n // Determines whether the given node may be selected as a node\n // selection.\n NodeSelection.isSelectable = function isSelectable (node) {\n return !node.isText && node.type.spec.selectable !== false\n };\n\n return NodeSelection;\n}(Selection));\n\nNodeSelection.prototype.visible = false;\n\nSelection.jsonID(\"node\", NodeSelection);\n\nvar NodeBookmark = function NodeBookmark(anchor) {\n this.anchor = anchor;\n};\nNodeBookmark.prototype.map = function map (mapping) {\n var ref = mapping.mapResult(this.anchor);\n var deleted = ref.deleted;\n var pos = ref.pos;\n return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos)\n};\nNodeBookmark.prototype.resolve = function resolve (doc) {\n var $pos = doc.resolve(this.anchor), node = $pos.nodeAfter;\n if (node && NodeSelection.isSelectable(node)) { return new NodeSelection($pos) }\n return Selection.near($pos)\n};\n\n// ::- A selection type that represents selecting the whole document\n// (which can not necessarily be expressed with a text selection, when\n// there are for example leaf block nodes at the start or end of the\n// document).\nvar AllSelection = /*@__PURE__*/(function (Selection) {\n function AllSelection(doc) {\n Selection.call(this, doc.resolve(0), doc.resolve(doc.content.size));\n }\n\n if ( Selection ) AllSelection.__proto__ = Selection;\n AllSelection.prototype = Object.create( Selection && Selection.prototype );\n AllSelection.prototype.constructor = AllSelection;\n\n AllSelection.prototype.replace = function replace (tr, content) {\n if ( content === void 0 ) content = Slice.empty;\n\n if (content == Slice.empty) {\n tr.delete(0, tr.doc.content.size);\n var sel = Selection.atStart(tr.doc);\n if (!sel.eq(tr.selection)) { tr.setSelection(sel); }\n } else {\n Selection.prototype.replace.call(this, tr, content);\n }\n };\n\n AllSelection.prototype.toJSON = function toJSON () { return {type: \"all\"} };\n\n AllSelection.fromJSON = function fromJSON (doc) { return new AllSelection(doc) };\n\n AllSelection.prototype.map = function map (doc) { return new AllSelection(doc) };\n\n AllSelection.prototype.eq = function eq (other) { return other instanceof AllSelection };\n\n AllSelection.prototype.getBookmark = function getBookmark () { return AllBookmark };\n\n return AllSelection;\n}(Selection));\n\nSelection.jsonID(\"all\", AllSelection);\n\nvar AllBookmark = {\n map: function map() { return this },\n resolve: function resolve(doc) { return new AllSelection(doc) }\n};\n\n// FIXME we'll need some awareness of text direction when scanning for selections\n\n// Try to find a selection inside the given node. `pos` points at the\n// position where the search starts. When `text` is true, only return\n// text selections.\nfunction findSelectionIn(doc, node, pos, index, dir, text) {\n if (node.inlineContent) { return TextSelection.create(doc, pos) }\n for (var i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {\n var child = node.child(i);\n if (!child.isAtom) {\n var inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);\n if (inner) { return inner }\n } else if (!text && NodeSelection.isSelectable(child)) {\n return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0))\n }\n pos += child.nodeSize * dir;\n }\n}\n\nfunction selectionToInsertionEnd(tr, startLen, bias) {\n var last = tr.steps.length - 1;\n if (last < startLen) { return }\n var step = tr.steps[last];\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) { return }\n var map = tr.mapping.maps[last], end;\n map.forEach(function (_from, _to, _newFrom, newTo) { if (end == null) { end = newTo; } });\n tr.setSelection(Selection.near(tr.doc.resolve(end), bias));\n}\n\nvar UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;\n\n// ::- An editor state transaction, which can be applied to a state to\n// create an updated state. Use\n// [`EditorState.tr`](#state.EditorState.tr) to create an instance.\n//\n// Transactions track changes to the document (they are a subclass of\n// [`Transform`](#transform.Transform)), but also other state changes,\n// like selection updates and adjustments of the set of [stored\n// marks](#state.EditorState.storedMarks). In addition, you can store\n// metadata properties in a transaction, which are extra pieces of\n// information that client code or plugins can use to describe what a\n// transacion represents, so that they can update their [own\n// state](#state.StateField) accordingly.\n//\n// The [editor view](#view.EditorView) uses a few metadata properties:\n// it will attach a property `\"pointer\"` with the value `true` to\n// selection transactions directly caused by mouse or touch input, and\n// a `\"uiEvent\"` property of that may be `\"paste\"`, `\"cut\"`, or `\"drop\"`.\nvar Transaction = /*@__PURE__*/(function (Transform) {\n function Transaction(state) {\n Transform.call(this, state.doc);\n // :: number\n // The timestamp associated with this transaction, in the same\n // format as `Date.now()`.\n this.time = Date.now();\n this.curSelection = state.selection;\n // The step count for which the current selection is valid.\n this.curSelectionFor = 0;\n // :: ?[Mark]\n // The stored marks set by this transaction, if any.\n this.storedMarks = state.storedMarks;\n // Bitfield to track which aspects of the state were updated by\n // this transaction.\n this.updated = 0;\n // Object used to store metadata properties for the transaction.\n this.meta = Object.create(null);\n }\n\n if ( Transform ) Transaction.__proto__ = Transform;\n Transaction.prototype = Object.create( Transform && Transform.prototype );\n Transaction.prototype.constructor = Transaction;\n\n var prototypeAccessors = { selection: { configurable: true },selectionSet: { configurable: true },storedMarksSet: { configurable: true },isGeneric: { configurable: true },scrolledIntoView: { configurable: true } };\n\n // :: Selection\n // The transaction's current selection. This defaults to the editor\n // selection [mapped](#state.Selection.map) through the steps in the\n // transaction, but can be overwritten with\n // [`setSelection`](#state.Transaction.setSelection).\n prototypeAccessors.selection.get = function () {\n if (this.curSelectionFor < this.steps.length) {\n this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));\n this.curSelectionFor = this.steps.length;\n }\n return this.curSelection\n };\n\n // :: (Selection) → Transaction\n // Update the transaction's current selection. Will determine the\n // selection that the editor gets when the transaction is applied.\n Transaction.prototype.setSelection = function setSelection (selection) {\n if (selection.$from.doc != this.doc)\n { throw new RangeError(\"Selection passed to setSelection must point at the current document\") }\n this.curSelection = selection;\n this.curSelectionFor = this.steps.length;\n this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;\n this.storedMarks = null;\n return this\n };\n\n // :: bool\n // Whether the selection was explicitly updated by this transaction.\n prototypeAccessors.selectionSet.get = function () {\n return (this.updated & UPDATED_SEL) > 0\n };\n\n // :: (?[Mark]) → Transaction\n // Set the current stored marks.\n Transaction.prototype.setStoredMarks = function setStoredMarks (marks) {\n this.storedMarks = marks;\n this.updated |= UPDATED_MARKS;\n return this\n };\n\n // :: ([Mark]) → Transaction\n // Make sure the current stored marks or, if that is null, the marks\n // at the selection, match the given set of marks. Does nothing if\n // this is already the case.\n Transaction.prototype.ensureMarks = function ensureMarks (marks) {\n if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))\n { this.setStoredMarks(marks); }\n return this\n };\n\n // :: (Mark) → Transaction\n // Add a mark to the set of stored marks.\n Transaction.prototype.addStoredMark = function addStoredMark (mark) {\n return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()))\n };\n\n // :: (union) → Transaction\n // Remove a mark or mark type from the set of stored marks.\n Transaction.prototype.removeStoredMark = function removeStoredMark (mark) {\n return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()))\n };\n\n // :: bool\n // Whether the stored marks were explicitly set for this transaction.\n prototypeAccessors.storedMarksSet.get = function () {\n return (this.updated & UPDATED_MARKS) > 0\n };\n\n Transaction.prototype.addStep = function addStep (step, doc) {\n Transform.prototype.addStep.call(this, step, doc);\n this.updated = this.updated & ~UPDATED_MARKS;\n this.storedMarks = null;\n };\n\n // :: (number) → Transaction\n // Update the timestamp for the transaction.\n Transaction.prototype.setTime = function setTime (time) {\n this.time = time;\n return this\n };\n\n // :: (Slice) → Transaction\n // Replace the current selection with the given slice.\n Transaction.prototype.replaceSelection = function replaceSelection (slice) {\n this.selection.replace(this, slice);\n return this\n };\n\n // :: (Node, ?bool) → Transaction\n // Replace the selection with the given node. When `inheritMarks` is\n // true and the content is inline, it inherits the marks from the\n // place where it is inserted.\n Transaction.prototype.replaceSelectionWith = function replaceSelectionWith (node, inheritMarks) {\n var selection = this.selection;\n if (inheritMarks !== false)\n { node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : (selection.$from.marksAcross(selection.$to) || Mark.none))); }\n selection.replaceWith(this, node);\n return this\n };\n\n // :: () → Transaction\n // Delete the selection.\n Transaction.prototype.deleteSelection = function deleteSelection () {\n this.selection.replace(this);\n return this\n };\n\n // :: (string, from: ?number, to: ?number) → Transaction\n // Replace the given range, or the selection if no range is given,\n // with a text node containing the given string.\n Transaction.prototype.insertText = function insertText (text, from, to) {\n if ( to === void 0 ) to = from;\n\n var schema = this.doc.type.schema;\n if (from == null) {\n if (!text) { return this.deleteSelection() }\n return this.replaceSelectionWith(schema.text(text), true)\n } else {\n if (!text) { return this.deleteRange(from, to) }\n var marks = this.storedMarks;\n if (!marks) {\n var $from = this.doc.resolve(from);\n marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));\n }\n this.replaceRangeWith(from, to, schema.text(text, marks));\n if (!this.selection.empty) { this.setSelection(Selection.near(this.selection.$to)); }\n return this\n }\n };\n\n // :: (union, any) → Transaction\n // Store a metadata property in this transaction, keyed either by\n // name or by plugin.\n Transaction.prototype.setMeta = function setMeta (key, value) {\n this.meta[typeof key == \"string\" ? key : key.key] = value;\n return this\n };\n\n // :: (union) → any\n // Retrieve a metadata property for a given name or plugin.\n Transaction.prototype.getMeta = function getMeta (key) {\n return this.meta[typeof key == \"string\" ? key : key.key]\n };\n\n // :: bool\n // Returns true if this transaction doesn't contain any metadata,\n // and can thus safely be extended.\n prototypeAccessors.isGeneric.get = function () {\n for (var _ in this.meta) { return false }\n return true\n };\n\n // :: () → Transaction\n // Indicate that the editor should scroll the selection into view\n // when updated to the state produced by this transaction.\n Transaction.prototype.scrollIntoView = function scrollIntoView () {\n this.updated |= UPDATED_SCROLL;\n return this\n };\n\n prototypeAccessors.scrolledIntoView.get = function () {\n return (this.updated & UPDATED_SCROLL) > 0\n };\n\n Object.defineProperties( Transaction.prototype, prototypeAccessors );\n\n return Transaction;\n}(Transform));\n\nfunction bind(f, self) {\n return !self || !f ? f : f.bind(self)\n}\n\nvar FieldDesc = function FieldDesc(name, desc, self) {\n this.name = name;\n this.init = bind(desc.init, self);\n this.apply = bind(desc.apply, self);\n};\n\nvar baseFields = [\n new FieldDesc(\"doc\", {\n init: function init(config) { return config.doc || config.schema.topNodeType.createAndFill() },\n apply: function apply(tr) { return tr.doc }\n }),\n\n new FieldDesc(\"selection\", {\n init: function init(config, instance) { return config.selection || Selection.atStart(instance.doc) },\n apply: function apply(tr) { return tr.selection }\n }),\n\n new FieldDesc(\"storedMarks\", {\n init: function init(config) { return config.storedMarks || null },\n apply: function apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null }\n }),\n\n new FieldDesc(\"scrollToSelection\", {\n init: function init() { return 0 },\n apply: function apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev }\n })\n];\n\n// Object wrapping the part of a state object that stays the same\n// across transactions. Stored in the state's `config` property.\nvar Configuration = function Configuration(schema, plugins) {\n var this$1 = this;\n\n this.schema = schema;\n this.fields = baseFields.concat();\n this.plugins = [];\n this.pluginsByKey = Object.create(null);\n if (plugins) { plugins.forEach(function (plugin) {\n if (this$1.pluginsByKey[plugin.key])\n { throw new RangeError(\"Adding different instances of a keyed plugin (\" + plugin.key + \")\") }\n this$1.plugins.push(plugin);\n this$1.pluginsByKey[plugin.key] = plugin;\n if (plugin.spec.state)\n { this$1.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin)); }\n }); }\n};\n\n// ::- The state of a ProseMirror editor is represented by an object\n// of this type. A state is a persistent data structure—it isn't\n// updated, but rather a new state value is computed from an old one\n// using the [`apply`](#state.EditorState.apply) method.\n//\n// A state holds a number of built-in fields, and plugins can\n// [define](#state.PluginSpec.state) additional fields.\nvar EditorState = function EditorState(config) {\n this.config = config;\n};\n\nvar prototypeAccessors$1 = { schema: { configurable: true },plugins: { configurable: true },tr: { configurable: true } };\n\n// doc:: Node\n// The current document.\n\n// selection:: Selection\n// The selection.\n\n// storedMarks:: ?[Mark]\n// A set of marks to apply to the next input. Will be null when\n// no explicit marks have been set.\n\n// :: Schema\n// The schema of the state's document.\nprototypeAccessors$1.schema.get = function () {\n return this.config.schema\n};\n\n// :: [Plugin]\n// The plugins that are active in this state.\nprototypeAccessors$1.plugins.get = function () {\n return this.config.plugins\n};\n\n// :: (Transaction) → EditorState\n// Apply the given transaction to produce a new state.\nEditorState.prototype.apply = function apply (tr) {\n return this.applyTransaction(tr).state\n};\n\n// : (Transaction) → bool\nEditorState.prototype.filterTransaction = function filterTransaction (tr, ignore) {\n if ( ignore === void 0 ) ignore = -1;\n\n for (var i = 0; i < this.config.plugins.length; i++) { if (i != ignore) {\n var plugin = this.config.plugins[i];\n if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this))\n { return false }\n } }\n return true\n};\n\n// :: (Transaction) → {state: EditorState, transactions: [Transaction]}\n// Verbose variant of [`apply`](#state.EditorState.apply) that\n// returns the precise transactions that were applied (which might\n// be influenced by the [transaction\n// hooks](#state.PluginSpec.filterTransaction) of\n// plugins) along with the new state.\nEditorState.prototype.applyTransaction = function applyTransaction (rootTr) {\n if (!this.filterTransaction(rootTr)) { return {state: this, transactions: []} }\n\n var trs = [rootTr], newState = this.applyInner(rootTr), seen = null;\n // This loop repeatedly gives plugins a chance to respond to\n // transactions as new transactions are added, making sure to only\n // pass the transactions the plugin did not see before.\n for (;;) {\n var haveNew = false;\n for (var i = 0; i < this.config.plugins.length; i++) {\n var plugin = this.config.plugins[i];\n if (plugin.spec.appendTransaction) {\n var n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;\n var tr = n < trs.length &&\n plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);\n if (tr && newState.filterTransaction(tr, i)) {\n tr.setMeta(\"appendedTransaction\", rootTr);\n if (!seen) {\n seen = [];\n for (var j = 0; j < this.config.plugins.length; j++)\n { seen.push(j < i ? {state: newState, n: trs.length} : {state: this, n: 0}); }\n }\n trs.push(tr);\n newState = newState.applyInner(tr);\n haveNew = true;\n }\n if (seen) { seen[i] = {state: newState, n: trs.length}; }\n }\n }\n if (!haveNew) { return {state: newState, transactions: trs} }\n }\n};\n\n// : (Transaction) → EditorState\nEditorState.prototype.applyInner = function applyInner (tr) {\n if (!tr.before.eq(this.doc)) { throw new RangeError(\"Applying a mismatched transaction\") }\n var newInstance = new EditorState(this.config), fields = this.config.fields;\n for (var i = 0; i < fields.length; i++) {\n var field = fields[i];\n newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);\n }\n for (var i$1 = 0; i$1 < applyListeners.length; i$1++) { applyListeners[i$1](this, tr, newInstance); }\n return newInstance\n};\n\n// :: Transaction\n// Start a [transaction](#state.Transaction) from this state.\nprototypeAccessors$1.tr.get = function () { return new Transaction(this) };\n\n// :: (Object) → EditorState\n// Create a new state.\n//\n// config::- Configuration options. Must contain `schema` or `doc` (or both).\n//\n// schema:: ?Schema\n// The schema to use.\n//\n// doc:: ?Node\n// The starting document.\n//\n// selection:: ?Selection\n// A valid selection in the document.\n//\n// storedMarks:: ?[Mark]\n// The initial set of [stored marks](#state.EditorState.storedMarks).\n//\n// plugins:: ?[Plugin]\n// The plugins that should be active in this state.\nEditorState.create = function create (config) {\n var $config = new Configuration(config.schema || config.doc.type.schema, config.plugins);\n var instance = new EditorState($config);\n for (var i = 0; i < $config.fields.length; i++)\n { instance[$config.fields[i].name] = $config.fields[i].init(config, instance); }\n return instance\n};\n\n// :: (Object) → EditorState\n// Create a new state based on this one, but with an adjusted set of\n// active plugins. State fields that exist in both sets of plugins\n// are kept unchanged. Those that no longer exist are dropped, and\n// those that are new are initialized using their\n// [`init`](#state.StateField.init) method, passing in the new\n// configuration object..\n//\n// config::- configuration options\n//\n// schema:: ?Schema\n// New schema to use.\n//\n// plugins:: ?[Plugin]\n// New set of active plugins.\nEditorState.prototype.reconfigure = function reconfigure (config) {\n var $config = new Configuration(config.schema || this.schema, config.plugins);\n var fields = $config.fields, instance = new EditorState($config);\n for (var i = 0; i < fields.length; i++) {\n var name = fields[i].name;\n instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);\n }\n return instance\n};\n\n// :: (?union, string, number>) → Object\n// Serialize this state to JSON. If you want to serialize the state\n// of plugins, pass an object mapping property names to use in the\n// resulting JSON object to plugin objects. The argument may also be\n// a string or number, in which case it is ignored, to support the\n// way `JSON.stringify` calls `toString` methods.\nEditorState.prototype.toJSON = function toJSON (pluginFields) {\n var result = {doc: this.doc.toJSON(), selection: this.selection.toJSON()};\n if (this.storedMarks) { result.storedMarks = this.storedMarks.map(function (m) { return m.toJSON(); }); }\n if (pluginFields && typeof pluginFields == 'object') { for (var prop in pluginFields) {\n if (prop == \"doc\" || prop == \"selection\")\n { throw new RangeError(\"The JSON fields `doc` and `selection` are reserved\") }\n var plugin = pluginFields[prop], state = plugin.spec.state;\n if (state && state.toJSON) { result[prop] = state.toJSON.call(plugin, this[plugin.key]); }\n } }\n return result\n};\n\n// :: (Object, Object, ?Object) → EditorState\n// Deserialize a JSON representation of a state. `config` should\n// have at least a `schema` field, and should contain array of\n// plugins to initialize the state with. `pluginFields` can be used\n// to deserialize the state of plugins, by associating plugin\n// instances with the property names they use in the JSON object.\n//\n// config::- configuration options\n//\n// schema:: Schema\n// The schema to use.\n//\n// plugins:: ?[Plugin]\n// The set of active plugins.\nEditorState.fromJSON = function fromJSON (config, json, pluginFields) {\n if (!json) { throw new RangeError(\"Invalid input for EditorState.fromJSON\") }\n if (!config.schema) { throw new RangeError(\"Required config field 'schema' missing\") }\n var $config = new Configuration(config.schema, config.plugins);\n var instance = new EditorState($config);\n $config.fields.forEach(function (field) {\n if (field.name == \"doc\") {\n instance.doc = Node.fromJSON(config.schema, json.doc);\n } else if (field.name == \"selection\") {\n instance.selection = Selection.fromJSON(instance.doc, json.selection);\n } else if (field.name == \"storedMarks\") {\n if (json.storedMarks) { instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON); }\n } else {\n if (pluginFields) { for (var prop in pluginFields) {\n var plugin = pluginFields[prop], state = plugin.spec.state;\n if (plugin.key == field.name && state && state.fromJSON &&\n Object.prototype.hasOwnProperty.call(json, prop)) {\n // This field belongs to a plugin mapped to a JSON field, read it from there.\n instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);\n return\n }\n } }\n instance[field.name] = field.init(config, instance);\n }\n });\n return instance\n};\n\n// Kludge to allow the view to track mappings between different\n// instances of a state.\n//\n// FIXME this is no longer needed as of prosemirror-view 1.9.0,\n// though due to backwards-compat we should probably keep it around\n// for a while (if only as a no-op)\nEditorState.addApplyListener = function addApplyListener (f) {\n applyListeners.push(f);\n};\nEditorState.removeApplyListener = function removeApplyListener (f) {\n var found = applyListeners.indexOf(f);\n if (found > -1) { applyListeners.splice(found, 1); }\n};\n\nObject.defineProperties( EditorState.prototype, prototypeAccessors$1 );\n\nvar applyListeners = [];\n\n// PluginSpec:: interface\n//\n// This is the type passed to the [`Plugin`](#state.Plugin)\n// constructor. It provides a definition for a plugin.\n//\n// props:: ?EditorProps\n// The [view props](#view.EditorProps) added by this plugin. Props\n// that are functions will be bound to have the plugin instance as\n// their `this` binding.\n//\n// state:: ?StateField\n// Allows a plugin to define a [state field](#state.StateField), an\n// extra slot in the state object in which it can keep its own data.\n//\n// key:: ?PluginKey\n// Can be used to make this a keyed plugin. You can have only one\n// plugin with a given key in a given state, but it is possible to\n// access the plugin's configuration and state through the key,\n// without having access to the plugin instance object.\n//\n// view:: ?(EditorView) → Object\n// When the plugin needs to interact with the editor view, or\n// set something up in the DOM, use this field. The function\n// will be called when the plugin's state is associated with an\n// editor view.\n//\n// return::-\n// Should return an object with the following optional\n// properties:\n//\n// update:: ?(view: EditorView, prevState: EditorState)\n// Called whenever the view's state is updated.\n//\n// destroy:: ?()\n// Called when the view is destroyed or receives a state\n// with different plugins.\n//\n// filterTransaction:: ?(Transaction, EditorState) → bool\n// When present, this will be called before a transaction is\n// applied by the state, allowing the plugin to cancel it (by\n// returning false).\n//\n// appendTransaction:: ?(transactions: [Transaction], oldState: EditorState, newState: EditorState) → ?Transaction\n// Allows the plugin to append another transaction to be applied\n// after the given array of transactions. When another plugin\n// appends a transaction after this was called, it is called again\n// with the new state and new transactions—but only the new\n// transactions, i.e. it won't be passed transactions that it\n// already saw.\n\nfunction bindProps(obj, self, target) {\n for (var prop in obj) {\n var val = obj[prop];\n if (val instanceof Function) { val = val.bind(self); }\n else if (prop == \"handleDOMEvents\") { val = bindProps(val, self, {}); }\n target[prop] = val;\n }\n return target\n}\n\n// ::- Plugins bundle functionality that can be added to an editor.\n// They are part of the [editor state](#state.EditorState) and\n// may influence that state and the view that contains it.\nvar Plugin = function Plugin(spec) {\n // :: EditorProps\n // The [props](#view.EditorProps) exported by this plugin.\n this.props = {};\n if (spec.props) { bindProps(spec.props, this, this.props); }\n // :: Object\n // The plugin's [spec object](#state.PluginSpec).\n this.spec = spec;\n this.key = spec.key ? spec.key.key : createKey(\"plugin\");\n};\n\n// :: (EditorState) → any\n// Extract the plugin's state field from an editor state.\nPlugin.prototype.getState = function getState (state) { return state[this.key] };\n\n// StateField:: interface\n// A plugin spec may provide a state field (under its\n// [`state`](#state.PluginSpec.state) property) of this type, which\n// describes the state it wants to keep. Functions provided here are\n// always called with the plugin instance as their `this` binding.\n//\n// init:: (config: Object, instance: EditorState) → T\n// Initialize the value of the field. `config` will be the object\n// passed to [`EditorState.create`](#state.EditorState^create). Note\n// that `instance` is a half-initialized state instance, and will\n// not have values for plugin fields initialized after this one.\n//\n// apply:: (tr: Transaction, value: T, oldState: EditorState, newState: EditorState) → T\n// Apply the given transaction to this state field, producing a new\n// field value. Note that the `newState` argument is again a partially\n// constructed state does not yet contain the state from plugins\n// coming after this one.\n//\n// toJSON:: ?(value: T) → *\n// Convert this field to JSON. Optional, can be left off to disable\n// JSON serialization for the field.\n//\n// fromJSON:: ?(config: Object, value: *, state: EditorState) → T\n// Deserialize the JSON representation of this field. Note that the\n// `state` argument is again a half-initialized state.\n\nvar keys = Object.create(null);\n\nfunction createKey(name) {\n if (name in keys) { return name + \"$\" + ++keys[name] }\n keys[name] = 0;\n return name + \"$\"\n}\n\n// ::- A key is used to [tag](#state.PluginSpec.key)\n// plugins in a way that makes it possible to find them, given an\n// editor state. Assigning a key does mean only one plugin of that\n// type can be active in a state.\nvar PluginKey = function PluginKey(name) {\nif ( name === void 0 ) name = \"key\";\n this.key = createKey(name); };\n\n// :: (EditorState) → ?Plugin\n// Get the active plugin with this key, if any, from an editor\n// state.\nPluginKey.prototype.get = function get (state) { return state.config.pluginsByKey[this.key] };\n\n// :: (EditorState) → ?any\n// Get the plugin's state from an editor state.\nPluginKey.prototype.getState = function getState (state) { return state[this.key] };\n\nexport { AllSelection, EditorState, NodeSelection, Plugin, PluginKey, Selection, SelectionRange, TextSelection, Transaction };\n//# sourceMappingURL=index.es.js.map\n","import { TextSelection, NodeSelection, Selection } from 'prosemirror-state';\nimport { DOMSerializer, Fragment, Mark, DOMParser, Slice } from 'prosemirror-model';\nimport { dropPoint } from 'prosemirror-transform';\n\nvar result = {};\n\nif (typeof navigator != \"undefined\" && typeof document != \"undefined\") {\n var ie_edge = /Edge\\/(\\d+)/.exec(navigator.userAgent);\n var ie_upto10 = /MSIE \\d/.test(navigator.userAgent);\n var ie_11up = /Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(navigator.userAgent);\n\n result.mac = /Mac/.test(navigator.platform);\n var ie = result.ie = !!(ie_upto10 || ie_11up || ie_edge);\n result.ie_version = ie_upto10 ? document.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : null;\n result.gecko = !ie && /gecko\\/(\\d+)/i.test(navigator.userAgent);\n result.gecko_version = result.gecko && +(/Firefox\\/(\\d+)/.exec(navigator.userAgent) || [0, 0])[1];\n var chrome = !ie && /Chrome\\/(\\d+)/.exec(navigator.userAgent);\n result.chrome = !!chrome;\n result.chrome_version = chrome && +chrome[1];\n result.ios = !ie && /AppleWebKit/.test(navigator.userAgent) && /Mobile\\/\\w+/.test(navigator.userAgent);\n result.android = /Android \\d/.test(navigator.userAgent);\n result.webkit = \"webkitFontSmoothing\" in document.documentElement.style;\n result.safari = /Apple Computer/.test(navigator.vendor);\n result.webkit_version = result.webkit && +(/\\bAppleWebKit\\/(\\d+)/.exec(navigator.userAgent) || [0, 0])[1];\n}\n\nvar domIndex = function(node) {\n for (var index = 0;; index++) {\n node = node.previousSibling;\n if (!node) { return index }\n }\n};\n\nvar parentNode = function(node) {\n var parent = node.parentNode;\n return parent && parent.nodeType == 11 ? parent.host : parent\n};\n\nvar reusedRange = null;\n\n// Note that this will always return the same range, because DOM range\n// objects are every expensive, and keep slowing down subsequent DOM\n// updates, for some reason.\nvar textRange = function(node, from, to) {\n var range = reusedRange || (reusedRange = document.createRange());\n range.setEnd(node, to == null ? node.nodeValue.length : to);\n range.setStart(node, from || 0);\n return range\n};\n\n// Scans forward and backward through DOM positions equivalent to the\n// given one to see if the two are in the same place (i.e. after a\n// text node vs at the end of that text node)\nvar isEquivalentPosition = function(node, off, targetNode, targetOff) {\n return targetNode && (scanFor(node, off, targetNode, targetOff, -1) ||\n scanFor(node, off, targetNode, targetOff, 1))\n};\n\nvar atomElements = /^(img|br|input|textarea|hr)$/i;\n\nfunction scanFor(node, off, targetNode, targetOff, dir) {\n for (;;) {\n if (node == targetNode && off == targetOff) { return true }\n if (off == (dir < 0 ? 0 : nodeSize(node))) {\n var parent = node.parentNode;\n if (parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == \"false\")\n { return false }\n off = domIndex(node) + (dir < 0 ? 0 : 1);\n node = parent;\n } else if (node.nodeType == 1) {\n node = node.childNodes[off + (dir < 0 ? -1 : 0)];\n if (node.contentEditable == \"false\") { return false }\n off = dir < 0 ? nodeSize(node) : 0;\n } else {\n return false\n }\n }\n}\n\nfunction nodeSize(node) {\n return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length\n}\n\nfunction isOnEdge(node, offset, parent) {\n for (var atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd;) {\n if (node == parent) { return true }\n var index = domIndex(node);\n node = node.parentNode;\n if (!node) { return false }\n atStart = atStart && index == 0;\n atEnd = atEnd && index == nodeSize(node);\n }\n}\n\nfunction hasBlockDesc(dom) {\n var desc;\n for (var cur = dom; cur; cur = cur.parentNode) { if (desc = cur.pmViewDesc) { break } }\n return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom)\n}\n\n// Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523\n// (isCollapsed inappropriately returns true in shadow dom)\nvar selectionCollapsed = function(domSel) {\n var collapsed = domSel.isCollapsed;\n if (collapsed && result.chrome && domSel.rangeCount && !domSel.getRangeAt(0).collapsed)\n { collapsed = false; }\n return collapsed\n};\n\nfunction keyEvent(keyCode, key) {\n var event = document.createEvent(\"Event\");\n event.initEvent(\"keydown\", true, true);\n event.keyCode = keyCode;\n event.key = event.code = key;\n return event\n}\n\nfunction windowRect(doc) {\n return {left: 0, right: doc.documentElement.clientWidth,\n top: 0, bottom: doc.documentElement.clientHeight}\n}\n\nfunction getSide(value, side) {\n return typeof value == \"number\" ? value : value[side]\n}\n\nfunction clientRect(node) {\n var rect = node.getBoundingClientRect();\n // Make sure scrollbar width isn't included in the rectangle\n return {left: rect.left, right: rect.left + node.clientWidth,\n top: rect.top, bottom: rect.top + node.clientHeight}\n}\n\nfunction scrollRectIntoView(view, rect, startDOM) {\n var scrollThreshold = view.someProp(\"scrollThreshold\") || 0, scrollMargin = view.someProp(\"scrollMargin\") || 5;\n var doc = view.dom.ownerDocument;\n for (var parent = startDOM || view.dom;; parent = parentNode(parent)) {\n if (!parent) { break }\n if (parent.nodeType != 1) { continue }\n var atTop = parent == doc.body || parent.nodeType != 1;\n var bounding = atTop ? windowRect(doc) : clientRect(parent);\n var moveX = 0, moveY = 0;\n if (rect.top < bounding.top + getSide(scrollThreshold, \"top\"))\n { moveY = -(bounding.top - rect.top + getSide(scrollMargin, \"top\")); }\n else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, \"bottom\"))\n { moveY = rect.bottom - bounding.bottom + getSide(scrollMargin, \"bottom\"); }\n if (rect.left < bounding.left + getSide(scrollThreshold, \"left\"))\n { moveX = -(bounding.left - rect.left + getSide(scrollMargin, \"left\")); }\n else if (rect.right > bounding.right - getSide(scrollThreshold, \"right\"))\n { moveX = rect.right - bounding.right + getSide(scrollMargin, \"right\"); }\n if (moveX || moveY) {\n if (atTop) {\n doc.defaultView.scrollBy(moveX, moveY);\n } else {\n var startX = parent.scrollLeft, startY = parent.scrollTop;\n if (moveY) { parent.scrollTop += moveY; }\n if (moveX) { parent.scrollLeft += moveX; }\n var dX = parent.scrollLeft - startX, dY = parent.scrollTop - startY;\n rect = {left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY};\n }\n }\n if (atTop) { break }\n }\n}\n\n// Store the scroll position of the editor's parent nodes, along with\n// the top position of an element near the top of the editor, which\n// will be used to make sure the visible viewport remains stable even\n// when the size of the content above changes.\nfunction storeScrollPos(view) {\n var rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top);\n var refDOM, refTop;\n for (var x = (rect.left + rect.right) / 2, y = startY + 1;\n y < Math.min(innerHeight, rect.bottom); y += 5) {\n var dom = view.root.elementFromPoint(x, y);\n if (dom == view.dom || !view.dom.contains(dom)) { continue }\n var localRect = dom.getBoundingClientRect();\n if (localRect.top >= startY - 20) {\n refDOM = dom;\n refTop = localRect.top;\n break\n }\n }\n return {refDOM: refDOM, refTop: refTop, stack: scrollStack(view.dom)}\n}\n\nfunction scrollStack(dom) {\n var stack = [], doc = dom.ownerDocument;\n for (; dom; dom = parentNode(dom)) {\n stack.push({dom: dom, top: dom.scrollTop, left: dom.scrollLeft});\n if (dom == doc) { break }\n }\n return stack\n}\n\n// Reset the scroll position of the editor's parent nodes to that what\n// it was before, when storeScrollPos was called.\nfunction resetScrollPos(ref) {\n var refDOM = ref.refDOM;\n var refTop = ref.refTop;\n var stack = ref.stack;\n\n var newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;\n restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);\n}\n\nfunction restoreScrollStack(stack, dTop) {\n for (var i = 0; i < stack.length; i++) {\n var ref = stack[i];\n var dom = ref.dom;\n var top = ref.top;\n var left = ref.left;\n if (dom.scrollTop != top + dTop) { dom.scrollTop = top + dTop; }\n if (dom.scrollLeft != left) { dom.scrollLeft = left; }\n }\n}\n\nvar preventScrollSupported = null;\n// Feature-detects support for .focus({preventScroll: true}), and uses\n// a fallback kludge when not supported.\nfunction focusPreventScroll(dom) {\n if (dom.setActive) { return dom.setActive() } // in IE\n if (preventScrollSupported) { return dom.focus(preventScrollSupported) }\n\n var stored = scrollStack(dom);\n dom.focus(preventScrollSupported == null ? {\n get preventScroll() {\n preventScrollSupported = {preventScroll: true};\n return true\n }\n } : undefined);\n if (!preventScrollSupported) {\n preventScrollSupported = false;\n restoreScrollStack(stored, 0);\n }\n}\n\nfunction findOffsetInNode(node, coords) {\n var closest, dxClosest = 2e8, coordsClosest, offset = 0;\n var rowBot = coords.top, rowTop = coords.top;\n for (var child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {\n var rects = (void 0);\n if (child.nodeType == 1) { rects = child.getClientRects(); }\n else if (child.nodeType == 3) { rects = textRange(child).getClientRects(); }\n else { continue }\n\n for (var i = 0; i < rects.length; i++) {\n var rect = rects[i];\n if (rect.top <= rowBot && rect.bottom >= rowTop) {\n rowBot = Math.max(rect.bottom, rowBot);\n rowTop = Math.min(rect.top, rowTop);\n var dx = rect.left > coords.left ? rect.left - coords.left\n : rect.right < coords.left ? coords.left - rect.right : 0;\n if (dx < dxClosest) {\n closest = child;\n dxClosest = dx;\n coordsClosest = dx && closest.nodeType == 3 ? {left: rect.right < coords.left ? rect.right : rect.left, top: coords.top} : coords;\n if (child.nodeType == 1 && dx)\n { offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0); }\n continue\n }\n }\n if (!closest && (coords.left >= rect.right && coords.top >= rect.top ||\n coords.left >= rect.left && coords.top >= rect.bottom))\n { offset = childIndex + 1; }\n }\n }\n if (closest && closest.nodeType == 3) { return findOffsetInText(closest, coordsClosest) }\n if (!closest || (dxClosest && closest.nodeType == 1)) { return {node: node, offset: offset} }\n return findOffsetInNode(closest, coordsClosest)\n}\n\nfunction findOffsetInText(node, coords) {\n var len = node.nodeValue.length;\n var range = document.createRange();\n for (var i = 0; i < len; i++) {\n range.setEnd(node, i + 1);\n range.setStart(node, i);\n var rect = singleRect(range, 1);\n if (rect.top == rect.bottom) { continue }\n if (inRect(coords, rect))\n { return {node: node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0)} }\n }\n return {node: node, offset: 0}\n}\n\nfunction inRect(coords, rect) {\n return coords.left >= rect.left - 1 && coords.left <= rect.right + 1&&\n coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1\n}\n\nfunction targetKludge(dom, coords) {\n var parent = dom.parentNode;\n if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left)\n { return parent }\n return dom\n}\n\nfunction posFromElement(view, elt, coords) {\n var ref = findOffsetInNode(elt, coords);\n var node = ref.node;\n var offset = ref.offset;\n var bias = -1;\n if (node.nodeType == 1 && !node.firstChild) {\n var rect = node.getBoundingClientRect();\n bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1;\n }\n return view.docView.posFromDOM(node, offset, bias)\n}\n\nfunction posFromCaret(view, node, offset, coords) {\n // Browser (in caretPosition/RangeFromPoint) will agressively\n // normalize towards nearby inline nodes. Since we are interested in\n // positions between block nodes too, we first walk up the hierarchy\n // of nodes to see if there are block nodes that the coordinates\n // fall outside of. If so, we take the position before/after that\n // block. If not, we call `posFromDOM` on the raw node/offset.\n var outside = -1;\n for (var cur = node;;) {\n if (cur == view.dom) { break }\n var desc = view.docView.nearestDesc(cur, true);\n if (!desc) { return null }\n if (desc.node.isBlock && desc.parent) {\n var rect = desc.dom.getBoundingClientRect();\n if (rect.left > coords.left || rect.top > coords.top) { outside = desc.posBefore; }\n else if (rect.right < coords.left || rect.bottom < coords.top) { outside = desc.posAfter; }\n else { break }\n }\n cur = desc.dom.parentNode;\n }\n return outside > -1 ? outside : view.docView.posFromDOM(node, offset)\n}\n\nfunction elementFromPoint(element, coords, box) {\n var len = element.childNodes.length;\n if (len && box.top < box.bottom) {\n for (var startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI;;) {\n var child = element.childNodes[i];\n if (child.nodeType == 1) {\n var rects = child.getClientRects();\n for (var j = 0; j < rects.length; j++) {\n var rect = rects[j];\n if (inRect(coords, rect)) { return elementFromPoint(child, coords, rect) }\n }\n }\n if ((i = (i + 1) % len) == startI) { break }\n }\n }\n return element\n}\n\n// Given an x,y position on the editor, get the position in the document.\nfunction posAtCoords(view, coords) {\n var assign, assign$1;\n\n var root = view.root, node, offset;\n if (root.caretPositionFromPoint) {\n try { // Firefox throws for this call in hard-to-predict circumstances (#994)\n var pos$1 = root.caretPositionFromPoint(coords.left, coords.top);\n if (pos$1) { ((assign = pos$1, node = assign.offsetNode, offset = assign.offset)); }\n } catch (_) {}\n }\n if (!node && root.caretRangeFromPoint) {\n var range = root.caretRangeFromPoint(coords.left, coords.top);\n if (range) { ((assign$1 = range, node = assign$1.startContainer, offset = assign$1.startOffset)); }\n }\n\n var elt = root.elementFromPoint(coords.left, coords.top + 1), pos;\n if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) {\n var box = view.dom.getBoundingClientRect();\n if (!inRect(coords, box)) { return null }\n elt = elementFromPoint(view.dom, coords, box);\n if (!elt) { return null }\n }\n // Safari's caretRangeFromPoint returns nonsense when on a draggable element\n if (result.safari && elt.draggable) { node = offset = null; }\n elt = targetKludge(elt, coords);\n if (node) {\n if (result.gecko && node.nodeType == 1) {\n // Firefox will sometimes return offsets into nodes, which\n // have no actual children, from caretPositionFromPoint (#953)\n offset = Math.min(offset, node.childNodes.length);\n // It'll also move the returned position before image nodes,\n // even if those are behind it.\n if (offset < node.childNodes.length) {\n var next = node.childNodes[offset], box$1;\n if (next.nodeName == \"IMG\" && (box$1 = next.getBoundingClientRect()).right <= coords.left &&\n box$1.bottom > coords.top)\n { offset++; }\n }\n }\n // Suspiciously specific kludge to work around caret*FromPoint\n // never returning a position at the end of the document\n if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 &&\n coords.top > node.lastChild.getBoundingClientRect().bottom)\n { pos = view.state.doc.content.size; }\n // Ignore positions directly after a BR, since caret*FromPoint\n // 'round up' positions that would be more accurately placed\n // before the BR node.\n else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != \"BR\")\n { pos = posFromCaret(view, node, offset, coords); }\n }\n if (pos == null) { pos = posFromElement(view, elt, coords); }\n\n var desc = view.docView.nearestDesc(elt, true);\n return {pos: pos, inside: desc ? desc.posAtStart - desc.border : -1}\n}\n\nfunction singleRect(object, bias) {\n var rects = object.getClientRects();\n return !rects.length ? object.getBoundingClientRect() : rects[bias < 0 ? 0 : rects.length - 1]\n}\n\nvar BIDI = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/;\n\n// : (EditorView, number, number) → {left: number, top: number, right: number, bottom: number}\n// Given a position in the document model, get a bounding box of the\n// character at that position, relative to the window.\nfunction coordsAtPos(view, pos, side) {\n var ref = view.docView.domFromPos(pos);\n var node = ref.node;\n var offset = ref.offset;\n var $pos = view.state.doc.resolve(pos), inline = $pos.parent.inlineContent;\n\n // These browsers support querying empty text ranges. Prefer that in\n // bidi context.\n var supportEmptyRange = result.webkit || result.gecko;\n if (node.nodeType == 3 && supportEmptyRange && BIDI.test(node.nodeValue)) {\n var rect = singleRect(textRange(node, offset, offset), side);\n // Firefox returns bad results (the position before the space)\n // when querying a position directly after line-broken\n // whitespace. Detect this situation and and kludge around it\n if (result.gecko && offset && /\\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) {\n var rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1);\n if (rectBefore.top == rect.top) {\n var rectAfter = singleRect(textRange(node, offset, offset + 1), -1);\n if (rectAfter.top != rect.top)\n { return flattenV(rectAfter, rectAfter.left < rectBefore.left) }\n }\n }\n return rect\n }\n\n // Move up the DOM as far as possible when in inline context.\n if (inline) {\n var parent = $pos.depth ? view.docView.domAfterPos($pos.before()) : view.dom;\n while (side < 0 && !offset && node != parent) {\n offset = domIndex(node);\n node = node.parentNode;\n }\n while (side >= 0 && offset == nodeSize(node) && node != parent) {\n offset = domIndex(node) + 1;\n node = node.parentNode;\n }\n }\n\n if (node.nodeType == 3) {\n if (side < 0) { return flattenV(singleRect(textRange(node, offset - 1, offset), 1), false) }\n return flattenV(singleRect(textRange(node, offset, offset + 1), -1), true)\n }\n\n // Return a horizontal line in block context\n if (!inline) {\n if (offset && (side < 0 || offset == nodeSize(node))) {\n var before = node.childNodes[offset - 1];\n if (before.nodeType == 1) { return flattenH(before.getBoundingClientRect(), false) }\n }\n if (offset < nodeSize(node)) {\n var after = node.childNodes[offset];\n if (after.nodeType == 1) { return flattenH(after.getBoundingClientRect(), true) }\n }\n return flattenH(node.getBoundingClientRect(), side >= 0)\n }\n\n // Inline, not in text node (this is not Bidi-safe)\n if (offset && (side < 0 || offset == nodeSize(node))) {\n var before$1 = node.childNodes[offset - 1];\n var target = before$1.nodeType == 3 ? textRange(before$1, nodeSize(before$1) - (supportEmptyRange ? 0 : 1))\n // BR nodes tend to only return the rectangle before them\n : before$1.nodeType == 1 && before$1.nodeName != \"BR\" ? before$1 : null;\n if (target) { return flattenV(singleRect(target, 1), false) }\n }\n if (offset < nodeSize(node)) {\n var after$1 = node.childNodes[offset];\n var target$1 = after$1.nodeType == 3 ? textRange(after$1, 0, (supportEmptyRange ? 0 : 1))\n : after$1.nodeType == 1 ? after$1 : null;\n if (target$1) { return flattenV(singleRect(target$1, -1), true) }\n }\n // All else failed, just try to get a rectangle for the target node\n return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, -side), side >= 0)\n}\n\nfunction flattenV(rect, left) {\n if (rect.width == 0) { return rect }\n var x = left ? rect.left : rect.right;\n return {top: rect.top, bottom: rect.bottom, left: x, right: x}\n}\n\nfunction flattenH(rect, top) {\n if (rect.height == 0) { return rect }\n var y = top ? rect.top : rect.bottom;\n return {top: y, bottom: y, left: rect.left, right: rect.right}\n}\n\nfunction withFlushedState(view, state, f) {\n var viewState = view.state, active = view.root.activeElement;\n if (viewState != state) { view.updateState(state); }\n if (active != view.dom) { view.focus(); }\n try {\n return f()\n } finally {\n if (viewState != state) { view.updateState(viewState); }\n if (active != view.dom && active) { active.focus(); }\n }\n}\n\n// : (EditorView, number, number)\n// Whether vertical position motion in a given direction\n// from a position would leave a text block.\nfunction endOfTextblockVertical(view, state, dir) {\n var sel = state.selection;\n var $pos = dir == \"up\" ? sel.$anchor.min(sel.$head) : sel.$anchor.max(sel.$head);\n return withFlushedState(view, state, function () {\n var ref = view.docView.domFromPos($pos.pos);\n var dom = ref.node;\n for (;;) {\n var nearest = view.docView.nearestDesc(dom, true);\n if (!nearest) { break }\n if (nearest.node.isBlock) { dom = nearest.dom; break }\n dom = nearest.dom.parentNode;\n }\n var coords = coordsAtPos(view, $pos.pos, 1);\n for (var child = dom.firstChild; child; child = child.nextSibling) {\n var boxes = (void 0);\n if (child.nodeType == 1) { boxes = child.getClientRects(); }\n else if (child.nodeType == 3) { boxes = textRange(child, 0, child.nodeValue.length).getClientRects(); }\n else { continue }\n for (var i = 0; i < boxes.length; i++) {\n var box = boxes[i];\n if (box.bottom > box.top && (dir == \"up\" ? box.bottom < coords.top + 1 : box.top > coords.bottom - 1))\n { return false }\n }\n }\n return true\n })\n}\n\nvar maybeRTL = /[\\u0590-\\u08ac]/;\n\nfunction endOfTextblockHorizontal(view, state, dir) {\n var ref = state.selection;\n var $head = ref.$head;\n if (!$head.parent.isTextblock) { return false }\n var offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size;\n var sel = getSelection();\n // If the textblock is all LTR, or the browser doesn't support\n // Selection.modify (Edge), fall back to a primitive approach\n if (!maybeRTL.test($head.parent.textContent) || !sel.modify)\n { return dir == \"left\" || dir == \"backward\" ? atStart : atEnd }\n\n return withFlushedState(view, state, function () {\n // This is a huge hack, but appears to be the best we can\n // currently do: use `Selection.modify` to move the selection by\n // one character, and see if that moves the cursor out of the\n // textblock (or doesn't move it at all, when at the start/end of\n // the document).\n var oldRange = sel.getRangeAt(0), oldNode = sel.focusNode, oldOff = sel.focusOffset;\n var oldBidiLevel = sel.caretBidiLevel; // Only for Firefox\n sel.modify(\"move\", dir, \"character\");\n var parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;\n var result = !parentDOM.contains(sel.focusNode.nodeType == 1 ? sel.focusNode : sel.focusNode.parentNode) ||\n (oldNode == sel.focusNode && oldOff == sel.focusOffset);\n // Restore the previous selection\n sel.removeAllRanges();\n sel.addRange(oldRange);\n if (oldBidiLevel != null) { sel.caretBidiLevel = oldBidiLevel; }\n return result\n })\n}\n\nvar cachedState = null, cachedDir = null, cachedResult = false;\nfunction endOfTextblock(view, state, dir) {\n if (cachedState == state && cachedDir == dir) { return cachedResult }\n cachedState = state; cachedDir = dir;\n return cachedResult = dir == \"up\" || dir == \"down\"\n ? endOfTextblockVertical(view, state, dir)\n : endOfTextblockHorizontal(view, state, dir)\n}\n\n// NodeView:: interface\n//\n// By default, document nodes are rendered using the result of the\n// [`toDOM`](#model.NodeSpec.toDOM) method of their spec, and managed\n// entirely by the editor. For some use cases, such as embedded\n// node-specific editing interfaces, you want more control over\n// the behavior of a node's in-editor representation, and need to\n// [define](#view.EditorProps.nodeViews) a custom node view.\n//\n// Mark views only support `dom` and `contentDOM`, and don't support\n// any of the node view methods.\n//\n// Objects returned as node views must conform to this interface.\n//\n// dom:: ?dom.Node\n// The outer DOM node that represents the document node. When not\n// given, the default strategy is used to create a DOM node.\n//\n// contentDOM:: ?dom.Node\n// The DOM node that should hold the node's content. Only meaningful\n// if the node view also defines a `dom` property and if its node\n// type is not a leaf node type. When this is present, ProseMirror\n// will take care of rendering the node's children into it. When it\n// is not present, the node view itself is responsible for rendering\n// (or deciding not to render) its child nodes.\n//\n// update:: ?(node: Node, decorations: [Decoration]) → bool\n// When given, this will be called when the view is updating itself.\n// It will be given a node (possibly of a different type), and an\n// array of active decorations (which are automatically drawn, and\n// the node view may ignore if it isn't interested in them), and\n// should return true if it was able to update to that node, and\n// false otherwise. If the node view has a `contentDOM` property (or\n// no `dom` property), updating its child nodes will be handled by\n// ProseMirror.\n//\n// selectNode:: ?()\n// Can be used to override the way the node's selected status (as a\n// node selection) is displayed.\n//\n// deselectNode:: ?()\n// When defining a `selectNode` method, you should also provide a\n// `deselectNode` method to remove the effect again.\n//\n// setSelection:: ?(anchor: number, head: number, root: dom.Document)\n// This will be called to handle setting the selection inside the\n// node. The `anchor` and `head` positions are relative to the start\n// of the node. By default, a DOM selection will be created between\n// the DOM positions corresponding to those positions, but if you\n// override it you can do something else.\n//\n// stopEvent:: ?(event: dom.Event) → bool\n// Can be used to prevent the editor view from trying to handle some\n// or all DOM events that bubble up from the node view. Events for\n// which this returns true are not handled by the editor.\n//\n// ignoreMutation:: ?(dom.MutationRecord) → bool\n// Called when a DOM\n// [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)\n// or a selection change happens within the view. When the change is\n// a selection change, the record will have a `type` property of\n// `\"selection\"` (which doesn't occur for native mutation records).\n// Return false if the editor should re-read the selection or\n// re-parse the range around the mutation, true if it can safely be\n// ignored.\n//\n// destroy:: ?()\n// Called when the node view is removed from the editor or the whole\n// editor is destroyed.\n\n// View descriptions are data structures that describe the DOM that is\n// used to represent the editor's content. They are used for:\n//\n// - Incremental redrawing when the document changes\n//\n// - Figuring out what part of the document a given DOM position\n// corresponds to\n//\n// - Wiring in custom implementations of the editing interface for a\n// given node\n//\n// They form a doubly-linked mutable tree, starting at `view.docView`.\n\nvar NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3;\n\n// Superclass for the various kinds of descriptions. Defines their\n// basic structure and shared methods.\nvar ViewDesc = function ViewDesc(parent, children, dom, contentDOM) {\n this.parent = parent;\n this.children = children;\n this.dom = dom;\n // An expando property on the DOM node provides a link back to its\n // description.\n dom.pmViewDesc = this;\n // This is the node that holds the child views. It may be null for\n // descs that don't have children.\n this.contentDOM = contentDOM;\n this.dirty = NOT_DIRTY;\n};\n\nvar prototypeAccessors = { beforePosition: { configurable: true },size: { configurable: true },border: { configurable: true },posBefore: { configurable: true },posAtStart: { configurable: true },posAfter: { configurable: true },posAtEnd: { configurable: true },contentLost: { configurable: true } };\n\n// Used to check whether a given description corresponds to a\n// widget/mark/node.\nViewDesc.prototype.matchesWidget = function matchesWidget () { return false };\nViewDesc.prototype.matchesMark = function matchesMark () { return false };\nViewDesc.prototype.matchesNode = function matchesNode () { return false };\nViewDesc.prototype.matchesHack = function matchesHack () { return false };\n\nprototypeAccessors.beforePosition.get = function () { return false };\n\n// : () → ?ParseRule\n// When parsing in-editor content (in domchange.js), we allow\n// descriptions to determine the parse rules that should be used to\n// parse them.\nViewDesc.prototype.parseRule = function parseRule () { return null };\n\n// : (dom.Event) → bool\n// Used by the editor's event handler to ignore events that come\n// from certain descs.\nViewDesc.prototype.stopEvent = function stopEvent () { return false };\n\n// The size of the content represented by this desc.\nprototypeAccessors.size.get = function () {\n var size = 0;\n for (var i = 0; i < this.children.length; i++) { size += this.children[i].size; }\n return size\n};\n\n// For block nodes, this represents the space taken up by their\n// start/end tokens.\nprototypeAccessors.border.get = function () { return 0 };\n\nViewDesc.prototype.destroy = function destroy () {\n this.parent = null;\n if (this.dom.pmViewDesc == this) { this.dom.pmViewDesc = null; }\n for (var i = 0; i < this.children.length; i++)\n { this.children[i].destroy(); }\n};\n\nViewDesc.prototype.posBeforeChild = function posBeforeChild (child) {\n for (var i = 0, pos = this.posAtStart; i < this.children.length; i++) {\n var cur = this.children[i];\n if (cur == child) { return pos }\n pos += cur.size;\n }\n};\n\nprototypeAccessors.posBefore.get = function () {\n return this.parent.posBeforeChild(this)\n};\n\nprototypeAccessors.posAtStart.get = function () {\n return this.parent ? this.parent.posBeforeChild(this) + this.border : 0\n};\n\nprototypeAccessors.posAfter.get = function () {\n return this.posBefore + this.size\n};\n\nprototypeAccessors.posAtEnd.get = function () {\n return this.posAtStart + this.size - 2 * this.border\n};\n\n// : (dom.Node, number, ?number) → number\nViewDesc.prototype.localPosFromDOM = function localPosFromDOM (dom, offset, bias) {\n // If the DOM position is in the content, use the child desc after\n // it to figure out a position.\n if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) {\n if (bias < 0) {\n var domBefore, desc;\n if (dom == this.contentDOM) {\n domBefore = dom.childNodes[offset - 1];\n } else {\n while (dom.parentNode != this.contentDOM) { dom = dom.parentNode; }\n domBefore = dom.previousSibling;\n }\n while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this)) { domBefore = domBefore.previousSibling; }\n return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart\n } else {\n var domAfter, desc$1;\n if (dom == this.contentDOM) {\n domAfter = dom.childNodes[offset];\n } else {\n while (dom.parentNode != this.contentDOM) { dom = dom.parentNode; }\n domAfter = dom.nextSibling;\n }\n while (domAfter && !((desc$1 = domAfter.pmViewDesc) && desc$1.parent == this)) { domAfter = domAfter.nextSibling; }\n return domAfter ? this.posBeforeChild(desc$1) : this.posAtEnd\n }\n }\n // Otherwise, use various heuristics, falling back on the bias\n // parameter, to determine whether to return the position at the\n // start or at the end of this view desc.\n var atEnd;\n if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {\n atEnd = dom.compareDocumentPosition(this.contentDOM) & 2;\n } else if (this.dom.firstChild) {\n if (offset == 0) { for (var search = dom;; search = search.parentNode) {\n if (search == this.dom) { atEnd = false; break }\n if (search.parentNode.firstChild != search) { break }\n } }\n if (atEnd == null && offset == dom.childNodes.length) { for (var search$1 = dom;; search$1 = search$1.parentNode) {\n if (search$1 == this.dom) { atEnd = true; break }\n if (search$1.parentNode.lastChild != search$1) { break }\n } }\n }\n return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart\n};\n\n// Scan up the dom finding the first desc that is a descendant of\n// this one.\nViewDesc.prototype.nearestDesc = function nearestDesc (dom, onlyNodes) {\n for (var first = true, cur = dom; cur; cur = cur.parentNode) {\n var desc = this.getDesc(cur);\n if (desc && (!onlyNodes || desc.node)) {\n // If dom is outside of this desc's nodeDOM, don't count it.\n if (first && desc.nodeDOM &&\n !(desc.nodeDOM.nodeType == 1 ? desc.nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : desc.nodeDOM == dom))\n { first = false; }\n else\n { return desc }\n }\n }\n};\n\nViewDesc.prototype.getDesc = function getDesc (dom) {\n var desc = dom.pmViewDesc;\n for (var cur = desc; cur; cur = cur.parent) { if (cur == this) { return desc } }\n};\n\nViewDesc.prototype.posFromDOM = function posFromDOM (dom, offset, bias) {\n for (var scan = dom; scan; scan = scan.parentNode) {\n var desc = this.getDesc(scan);\n if (desc) { return desc.localPosFromDOM(dom, offset, bias) }\n }\n return -1\n};\n\n// : (number) → ?NodeViewDesc\n// Find the desc for the node after the given pos, if any. (When a\n// parent node overrode rendering, there might not be one.)\nViewDesc.prototype.descAt = function descAt (pos) {\n for (var i = 0, offset = 0; i < this.children.length; i++) {\n var child = this.children[i], end = offset + child.size;\n if (offset == pos && end != offset) {\n while (!child.border && child.children.length) { child = child.children[0]; }\n return child\n }\n if (pos < end) { return child.descAt(pos - offset - child.border) }\n offset = end;\n }\n};\n\n// : (number) → {node: dom.Node, offset: number}\nViewDesc.prototype.domFromPos = function domFromPos (pos) {\n if (!this.contentDOM) { return {node: this.dom, offset: 0} }\n for (var offset = 0, i = 0;; i++) {\n if (offset == pos) {\n while (i < this.children.length && (this.children[i].beforePosition || this.children[i].dom.parentNode != this.contentDOM)) { i++; }\n return {node: this.contentDOM,\n offset: i == this.children.length ? this.contentDOM.childNodes.length : domIndex(this.children[i].dom)}\n }\n if (i == this.children.length) { throw new Error(\"Invalid position \" + pos) }\n var child = this.children[i], end = offset + child.size;\n if (pos < end) { return child.domFromPos(pos - offset - child.border) }\n offset = end;\n }\n};\n\n// Used to find a DOM range in a single parent for a given changed\n// range.\nViewDesc.prototype.parseRange = function parseRange (from, to, base) {\n if ( base === void 0 ) base = 0;\n\n if (this.children.length == 0)\n { return {node: this.contentDOM, from: from, to: to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length} }\n\n var fromOffset = -1, toOffset = -1;\n for (var offset = base, i = 0;; i++) {\n var child = this.children[i], end = offset + child.size;\n if (fromOffset == -1 && from <= end) {\n var childBase = offset + child.border;\n // FIXME maybe descend mark views to parse a narrower range?\n if (from >= childBase && to <= end - child.border && child.node &&\n child.contentDOM && this.contentDOM.contains(child.contentDOM))\n { return child.parseRange(from, to, childBase) }\n\n from = offset;\n for (var j = i; j > 0; j--) {\n var prev = this.children[j - 1];\n if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {\n fromOffset = domIndex(prev.dom) + 1;\n break\n }\n from -= prev.size;\n }\n if (fromOffset == -1) { fromOffset = 0; }\n }\n if (fromOffset > -1 && (end > to || i == this.children.length - 1)) {\n to = end;\n for (var j$1 = i + 1; j$1 < this.children.length; j$1++) {\n var next = this.children[j$1];\n if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {\n toOffset = domIndex(next.dom);\n break\n }\n to += next.size;\n }\n if (toOffset == -1) { toOffset = this.contentDOM.childNodes.length; }\n break\n }\n offset = end;\n }\n return {node: this.contentDOM, from: from, to: to, fromOffset: fromOffset, toOffset: toOffset}\n};\n\nViewDesc.prototype.emptyChildAt = function emptyChildAt (side) {\n if (this.border || !this.contentDOM || !this.children.length) { return false }\n var child = this.children[side < 0 ? 0 : this.children.length - 1];\n return child.size == 0 || child.emptyChildAt(side)\n};\n\n// : (number) → dom.Node\nViewDesc.prototype.domAfterPos = function domAfterPos (pos) {\n var ref = this.domFromPos(pos);\n var node = ref.node;\n var offset = ref.offset;\n if (node.nodeType != 1 || offset == node.childNodes.length)\n { throw new RangeError(\"No node after pos \" + pos) }\n return node.childNodes[offset]\n};\n\n// : (number, number, dom.Document)\n// View descs are responsible for setting any selection that falls\n// entirely inside of them, so that custom implementations can do\n// custom things with the selection. Note that this falls apart when\n// a selection starts in such a node and ends in another, in which\n// case we just use whatever domFromPos produces as a best effort.\nViewDesc.prototype.setSelection = function setSelection (anchor, head, root, force) {\n // If the selection falls entirely in a child, give it to that child\n var from = Math.min(anchor, head), to = Math.max(anchor, head);\n for (var i = 0, offset = 0; i < this.children.length; i++) {\n var child = this.children[i], end = offset + child.size;\n if (from > offset && to < end)\n { return child.setSelection(anchor - offset - child.border, head - offset - child.border, root, force) }\n offset = end;\n }\n\n var anchorDOM = this.domFromPos(anchor), headDOM = this.domFromPos(head);\n var domSel = root.getSelection();\n\n var brKludge = false;\n // On Firefox, using Selection.collapse to put the cursor after a\n // BR node for some reason doesn't always work (#1073). On Safari,\n // the cursor sometimes inexplicable visually lags behind its\n // reported position in such situations (#1092).\n if ((result.gecko || result.safari) && anchor == head) {\n var prev = anchorDOM.node.childNodes[anchorDOM.offset - 1];\n brKludge = prev && (prev.nodeName == \"BR\" || prev.contentEditable == \"false\");\n }\n\n if (!(force || brKludge && result.safari) &&\n isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset) &&\n isEquivalentPosition(headDOM.node, headDOM.offset, domSel.focusNode, domSel.focusOffset))\n { return }\n\n // Selection.extend can be used to create an 'inverted' selection\n // (one where the focus is before the anchor), but not all\n // browsers support it yet.\n var domSelExtended = false;\n if ((domSel.extend || anchor == head) && !brKludge) {\n domSel.collapse(anchorDOM.node, anchorDOM.offset);\n try {\n if (anchor != head) { domSel.extend(headDOM.node, headDOM.offset); }\n domSelExtended = true;\n } catch (err) {\n // In some cases with Chrome the selection is empty after calling\n // collapse, even when it should be valid. This appears to be a bug, but\n // it is difficult to isolate. If this happens fallback to the old path\n // without using extend.\n if (!(err instanceof DOMException)) { throw err }\n // declare global: DOMException\n }\n }\n if (!domSelExtended) {\n if (anchor > head) { var tmp = anchorDOM; anchorDOM = headDOM; headDOM = tmp; }\n var range = document.createRange();\n range.setEnd(headDOM.node, headDOM.offset);\n range.setStart(anchorDOM.node, anchorDOM.offset);\n domSel.removeAllRanges();\n domSel.addRange(range);\n }\n};\n\n// : (dom.MutationRecord) → bool\nViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) {\n return !this.contentDOM && mutation.type != \"selection\"\n};\n\nprototypeAccessors.contentLost.get = function () {\n return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM)\n};\n\n// Remove a subtree of the element tree that has been touched\n// by a DOM change, so that the next update will redraw it.\nViewDesc.prototype.markDirty = function markDirty (from, to) {\n for (var offset = 0, i = 0; i < this.children.length; i++) {\n var child = this.children[i], end = offset + child.size;\n if (offset == end ? from <= end && to >= offset : from < end && to > offset) {\n var startInside = offset + child.border, endInside = end - child.border;\n if (from >= startInside && to <= endInside) {\n this.dirty = from == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY;\n if (from == startInside && to == endInside &&\n (child.contentLost || child.dom.parentNode != this.contentDOM)) { child.dirty = NODE_DIRTY; }\n else { child.markDirty(from - startInside, to - startInside); }\n return\n } else {\n child.dirty = NODE_DIRTY;\n }\n }\n offset = end;\n }\n this.dirty = CONTENT_DIRTY;\n};\n\nViewDesc.prototype.markParentsDirty = function markParentsDirty () {\n var level = 1;\n for (var node = this.parent; node; node = node.parent, level++) {\n var dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;\n if (node.dirty < dirty) { node.dirty = dirty; }\n }\n};\n\nObject.defineProperties( ViewDesc.prototype, prototypeAccessors );\n\n// Reused array to avoid allocating fresh arrays for things that will\n// stay empty anyway.\nvar nothing = [];\n\n// A widget desc represents a widget decoration, which is a DOM node\n// drawn between the document nodes.\nvar WidgetViewDesc = /*@__PURE__*/(function (ViewDesc) {\n function WidgetViewDesc(parent, widget, view, pos) {\n var self, dom = widget.type.toDOM;\n if (typeof dom == \"function\") { dom = dom(view, function () {\n if (!self) { return pos }\n if (self.parent) { return self.parent.posBeforeChild(self) }\n }); }\n if (!widget.type.spec.raw) {\n if (dom.nodeType != 1) {\n var wrap = document.createElement(\"span\");\n wrap.appendChild(dom);\n dom = wrap;\n }\n dom.contentEditable = false;\n dom.classList.add(\"ProseMirror-widget\");\n }\n ViewDesc.call(this, parent, nothing, dom, null);\n this.widget = widget;\n self = this;\n }\n\n if ( ViewDesc ) WidgetViewDesc.__proto__ = ViewDesc;\n WidgetViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype );\n WidgetViewDesc.prototype.constructor = WidgetViewDesc;\n\n var prototypeAccessors$1 = { beforePosition: { configurable: true } };\n\n prototypeAccessors$1.beforePosition.get = function () {\n return this.widget.type.side < 0\n };\n\n WidgetViewDesc.prototype.matchesWidget = function matchesWidget (widget) {\n return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type)\n };\n\n WidgetViewDesc.prototype.parseRule = function parseRule () { return {ignore: true} };\n\n WidgetViewDesc.prototype.stopEvent = function stopEvent (event) {\n var stop = this.widget.spec.stopEvent;\n return stop ? stop(event) : false\n };\n\n WidgetViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) {\n return mutation.type != \"selection\" || this.widget.spec.ignoreSelection\n };\n\n Object.defineProperties( WidgetViewDesc.prototype, prototypeAccessors$1 );\n\n return WidgetViewDesc;\n}(ViewDesc));\n\nvar CompositionViewDesc = /*@__PURE__*/(function (ViewDesc) {\n function CompositionViewDesc(parent, dom, textDOM, text) {\n ViewDesc.call(this, parent, nothing, dom, null);\n this.textDOM = textDOM;\n this.text = text;\n }\n\n if ( ViewDesc ) CompositionViewDesc.__proto__ = ViewDesc;\n CompositionViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype );\n CompositionViewDesc.prototype.constructor = CompositionViewDesc;\n\n var prototypeAccessors$2 = { size: { configurable: true } };\n\n prototypeAccessors$2.size.get = function () { return this.text.length };\n\n CompositionViewDesc.prototype.localPosFromDOM = function localPosFromDOM (dom, offset) {\n if (dom != this.textDOM) { return this.posAtStart + (offset ? this.size : 0) }\n return this.posAtStart + offset\n };\n\n CompositionViewDesc.prototype.domFromPos = function domFromPos (pos) {\n return {node: this.textDOM, offset: pos}\n };\n\n CompositionViewDesc.prototype.ignoreMutation = function ignoreMutation (mut) {\n return mut.type === 'characterData' && mut.target.nodeValue == mut.oldValue\n };\n\n Object.defineProperties( CompositionViewDesc.prototype, prototypeAccessors$2 );\n\n return CompositionViewDesc;\n}(ViewDesc));\n\n// A mark desc represents a mark. May have multiple children,\n// depending on how the mark is split. Note that marks are drawn using\n// a fixed nesting order, for simplicity and predictability, so in\n// some cases they will be split more often than would appear\n// necessary.\nvar MarkViewDesc = /*@__PURE__*/(function (ViewDesc) {\n function MarkViewDesc(parent, mark, dom, contentDOM) {\n ViewDesc.call(this, parent, [], dom, contentDOM);\n this.mark = mark;\n }\n\n if ( ViewDesc ) MarkViewDesc.__proto__ = ViewDesc;\n MarkViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype );\n MarkViewDesc.prototype.constructor = MarkViewDesc;\n\n MarkViewDesc.create = function create (parent, mark, inline, view) {\n var custom = view.nodeViews[mark.type.name];\n var spec = custom && custom(mark, view, inline);\n if (!spec || !spec.dom)\n { spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline)); }\n return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom)\n };\n\n MarkViewDesc.prototype.parseRule = function parseRule () { return {mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM} };\n\n MarkViewDesc.prototype.matchesMark = function matchesMark (mark) { return this.dirty != NODE_DIRTY && this.mark.eq(mark) };\n\n MarkViewDesc.prototype.markDirty = function markDirty (from, to) {\n ViewDesc.prototype.markDirty.call(this, from, to);\n // Move dirty info to nearest node view\n if (this.dirty != NOT_DIRTY) {\n var parent = this.parent;\n while (!parent.node) { parent = parent.parent; }\n if (parent.dirty < this.dirty) { parent.dirty = this.dirty; }\n this.dirty = NOT_DIRTY;\n }\n };\n\n MarkViewDesc.prototype.slice = function slice (from, to, view) {\n var copy = MarkViewDesc.create(this.parent, this.mark, true, view);\n var nodes = this.children, size = this.size;\n if (to < size) { nodes = replaceNodes(nodes, to, size, view); }\n if (from > 0) { nodes = replaceNodes(nodes, 0, from, view); }\n for (var i = 0; i < nodes.length; i++) { nodes[i].parent = copy; }\n copy.children = nodes;\n return copy\n };\n\n return MarkViewDesc;\n}(ViewDesc));\n\n// Node view descs are the main, most common type of view desc, and\n// correspond to an actual node in the document. Unlike mark descs,\n// they populate their child array themselves.\nvar NodeViewDesc = /*@__PURE__*/(function (ViewDesc) {\n function NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) {\n ViewDesc.call(this, parent, node.isLeaf ? nothing : [], dom, contentDOM);\n this.nodeDOM = nodeDOM;\n this.node = node;\n this.outerDeco = outerDeco;\n this.innerDeco = innerDeco;\n if (contentDOM) { this.updateChildren(view, pos); }\n }\n\n if ( ViewDesc ) NodeViewDesc.__proto__ = ViewDesc;\n NodeViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype );\n NodeViewDesc.prototype.constructor = NodeViewDesc;\n\n var prototypeAccessors$3 = { size: { configurable: true },border: { configurable: true } };\n\n // By default, a node is rendered using the `toDOM` method from the\n // node type spec. But client code can use the `nodeViews` spec to\n // supply a custom node view, which can influence various aspects of\n // the way the node works.\n //\n // (Using subclassing for this was intentionally decided against,\n // since it'd require exposing a whole slew of finnicky\n // implementation details to the user code that they probably will\n // never need.)\n NodeViewDesc.create = function create (parent, node, outerDeco, innerDeco, view, pos) {\n var assign;\n\n var custom = view.nodeViews[node.type.name], descObj;\n var spec = custom && custom(node, view, function () {\n // (This is a function that allows the custom view to find its\n // own position)\n if (!descObj) { return pos }\n if (descObj.parent) { return descObj.parent.posBeforeChild(descObj) }\n }, outerDeco);\n\n var dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;\n if (node.isText) {\n if (!dom) { dom = document.createTextNode(node.text); }\n else if (dom.nodeType != 3) { throw new RangeError(\"Text must be rendered as a DOM text node\") }\n } else if (!dom) {\n((assign = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node)), dom = assign.dom, contentDOM = assign.contentDOM));\n }\n if (!contentDOM && !node.isText && dom.nodeName != \"BR\") { // Chrome gets confused by
\n if (!dom.hasAttribute(\"contenteditable\")) { dom.contentEditable = false; }\n if (node.type.spec.draggable) { dom.draggable = true; }\n }\n\n var nodeDOM = dom;\n dom = applyOuterDeco(dom, outerDeco, node);\n\n if (spec)\n { return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM,\n spec, view, pos + 1) }\n else if (node.isText)\n { return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) }\n else\n { return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos + 1) }\n };\n\n NodeViewDesc.prototype.parseRule = function parseRule () {\n var this$1 = this;\n\n // Experimental kludge to allow opt-in re-parsing of nodes\n if (this.node.type.spec.reparseInView) { return null }\n // FIXME the assumption that this can always return the current\n // attrs means that if the user somehow manages to change the\n // attrs in the dom, that won't be picked up. Not entirely sure\n // whether this is a problem\n var rule = {node: this.node.type.name, attrs: this.node.attrs};\n if (this.node.type.spec.code) { rule.preserveWhitespace = \"full\"; }\n if (this.contentDOM && !this.contentLost) { rule.contentElement = this.contentDOM; }\n else { rule.getContent = function () { return this$1.contentDOM ? Fragment.empty : this$1.node.content; }; }\n return rule\n };\n\n NodeViewDesc.prototype.matchesNode = function matchesNode (node, outerDeco, innerDeco) {\n return this.dirty == NOT_DIRTY && node.eq(this.node) &&\n sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco)\n };\n\n prototypeAccessors$3.size.get = function () { return this.node.nodeSize };\n\n prototypeAccessors$3.border.get = function () { return this.node.isLeaf ? 0 : 1 };\n\n // Syncs `this.children` to match `this.node.content` and the local\n // decorations, possibly introducing nesting for marks. Then, in a\n // separate step, syncs the DOM inside `this.contentDOM` to\n // `this.children`.\n NodeViewDesc.prototype.updateChildren = function updateChildren (view, pos) {\n var this$1 = this;\n\n var inline = this.node.inlineContent, off = pos;\n var composition = inline && view.composing && this.localCompositionNode(view, pos);\n var updater = new ViewTreeUpdater(this, composition && composition.node);\n iterDeco(this.node, this.innerDeco, function (widget, i, insideNode) {\n if (widget.spec.marks)\n { updater.syncToMarks(widget.spec.marks, inline, view); }\n else if (widget.type.side >= 0 && !insideNode)\n { updater.syncToMarks(i == this$1.node.childCount ? Mark.none : this$1.node.child(i).marks, inline, view); }\n // If the next node is a desc matching this widget, reuse it,\n // otherwise insert the widget as a new view desc.\n updater.placeWidget(widget, view, off);\n }, function (child, outerDeco, innerDeco, i) {\n // Make sure the wrapping mark descs match the node's marks.\n updater.syncToMarks(child.marks, inline, view);\n // Either find an existing desc that exactly matches this node,\n // and drop the descs before it.\n updater.findNodeMatch(child, outerDeco, innerDeco, i) ||\n // Or try updating the next desc to reflect this node.\n updater.updateNextNode(child, outerDeco, innerDeco, view, i) ||\n // Or just add it as a new desc.\n updater.addNode(child, outerDeco, innerDeco, view, off);\n off += child.nodeSize;\n });\n // Drop all remaining descs after the current position.\n updater.syncToMarks(nothing, inline, view);\n if (this.node.isTextblock) { updater.addTextblockHacks(); }\n updater.destroyRest();\n\n // Sync the DOM if anything changed\n if (updater.changed || this.dirty == CONTENT_DIRTY) {\n // May have to protect focused DOM from being changed if a composition is active\n if (composition) { this.protectLocalComposition(view, composition); }\n renderDescs(this.contentDOM, this.children, view);\n if (result.ios) { iosHacks(this.dom); }\n }\n };\n\n NodeViewDesc.prototype.localCompositionNode = function localCompositionNode (view, pos) {\n // Only do something if both the selection and a focused text node\n // are inside of this node, and the node isn't already part of a\n // view that's a child of this view\n var ref = view.state.selection;\n var from = ref.from;\n var to = ref.to;\n if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size) { return }\n var sel = view.root.getSelection();\n var textNode = nearbyTextNode(sel.focusNode, sel.focusOffset);\n if (!textNode || !this.dom.contains(textNode.parentNode)) { return }\n\n // Find the text in the focused node in the node, stop if it's not\n // there (may have been modified through other means, in which\n // case it should overwritten)\n var text = textNode.nodeValue;\n var textPos = findTextInFragment(this.node.content, text, from - pos, to - pos);\n\n return textPos < 0 ? null : {node: textNode, pos: textPos, text: text}\n };\n\n NodeViewDesc.prototype.protectLocalComposition = function protectLocalComposition (view, ref) {\n var node = ref.node;\n var pos = ref.pos;\n var text = ref.text;\n\n // The node is already part of a local view desc, leave it there\n if (this.getDesc(node)) { return }\n\n // Create a composition view for the orphaned nodes\n var topNode = node;\n for (;; topNode = topNode.parentNode) {\n if (topNode.parentNode == this.contentDOM) { break }\n while (topNode.previousSibling) { topNode.parentNode.removeChild(topNode.previousSibling); }\n while (topNode.nextSibling) { topNode.parentNode.removeChild(topNode.nextSibling); }\n if (topNode.pmViewDesc) { topNode.pmViewDesc = null; }\n }\n var desc = new CompositionViewDesc(this, topNode, node, text);\n view.compositionNodes.push(desc);\n\n // Patch up this.children to contain the composition view\n this.children = replaceNodes(this.children, pos, pos + text.length, view, desc);\n };\n\n // : (Node, [Decoration], DecorationSet, EditorView) → bool\n // If this desc be updated to match the given node decoration,\n // do so and return true.\n NodeViewDesc.prototype.update = function update (node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY ||\n !node.sameMarkup(this.node)) { return false }\n this.updateInner(node, outerDeco, innerDeco, view);\n return true\n };\n\n NodeViewDesc.prototype.updateInner = function updateInner (node, outerDeco, innerDeco, view) {\n this.updateOuterDeco(outerDeco);\n this.node = node;\n this.innerDeco = innerDeco;\n if (this.contentDOM) { this.updateChildren(view, this.posAtStart); }\n this.dirty = NOT_DIRTY;\n };\n\n NodeViewDesc.prototype.updateOuterDeco = function updateOuterDeco (outerDeco) {\n if (sameOuterDeco(outerDeco, this.outerDeco)) { return }\n var needsWrap = this.nodeDOM.nodeType != 1;\n var oldDOM = this.dom;\n this.dom = patchOuterDeco(this.dom, this.nodeDOM,\n computeOuterDeco(this.outerDeco, this.node, needsWrap),\n computeOuterDeco(outerDeco, this.node, needsWrap));\n if (this.dom != oldDOM) {\n oldDOM.pmViewDesc = null;\n this.dom.pmViewDesc = this;\n }\n this.outerDeco = outerDeco;\n };\n\n // Mark this node as being the selected node.\n NodeViewDesc.prototype.selectNode = function selectNode () {\n this.nodeDOM.classList.add(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable) { this.dom.draggable = true; }\n };\n\n // Remove selected node marking from this node.\n NodeViewDesc.prototype.deselectNode = function deselectNode () {\n this.nodeDOM.classList.remove(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable) { this.dom.removeAttribute(\"draggable\"); }\n };\n\n Object.defineProperties( NodeViewDesc.prototype, prototypeAccessors$3 );\n\n return NodeViewDesc;\n}(ViewDesc));\n\n// Create a view desc for the top-level document node, to be exported\n// and used by the view class.\nfunction docViewDesc(doc, outerDeco, innerDeco, dom, view) {\n applyOuterDeco(dom, outerDeco, doc);\n return new NodeViewDesc(null, doc, outerDeco, innerDeco, dom, dom, dom, view, 0)\n}\n\nvar TextViewDesc = /*@__PURE__*/(function (NodeViewDesc) {\n function TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) {\n NodeViewDesc.call(this, parent, node, outerDeco, innerDeco, dom, null, nodeDOM, view);\n }\n\n if ( NodeViewDesc ) TextViewDesc.__proto__ = NodeViewDesc;\n TextViewDesc.prototype = Object.create( NodeViewDesc && NodeViewDesc.prototype );\n TextViewDesc.prototype.constructor = TextViewDesc;\n\n TextViewDesc.prototype.parseRule = function parseRule () {\n var skip = this.nodeDOM.parentNode;\n while (skip && skip != this.dom && !skip.pmIsDeco) { skip = skip.parentNode; }\n return {skip: skip || true}\n };\n\n TextViewDesc.prototype.update = function update (node, outerDeco, _, view) {\n if (this.dirty == NODE_DIRTY || (this.dirty != NOT_DIRTY && !this.inParent()) ||\n !node.sameMarkup(this.node)) { return false }\n this.updateOuterDeco(outerDeco);\n if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {\n this.nodeDOM.nodeValue = node.text;\n if (view.trackWrites == this.nodeDOM) { view.trackWrites = null; }\n }\n this.node = node;\n this.dirty = NOT_DIRTY;\n return true\n };\n\n TextViewDesc.prototype.inParent = function inParent () {\n var parentDOM = this.parent.contentDOM;\n for (var n = this.nodeDOM; n; n = n.parentNode) { if (n == parentDOM) { return true } }\n return false\n };\n\n TextViewDesc.prototype.domFromPos = function domFromPos (pos) {\n return {node: this.nodeDOM, offset: pos}\n };\n\n TextViewDesc.prototype.localPosFromDOM = function localPosFromDOM (dom, offset, bias) {\n if (dom == this.nodeDOM) { return this.posAtStart + Math.min(offset, this.node.text.length) }\n return NodeViewDesc.prototype.localPosFromDOM.call(this, dom, offset, bias)\n };\n\n TextViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) {\n return mutation.type != \"characterData\" && mutation.type != \"selection\"\n };\n\n TextViewDesc.prototype.slice = function slice (from, to, view) {\n var node = this.node.cut(from, to), dom = document.createTextNode(node.text);\n return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view)\n };\n\n return TextViewDesc;\n}(NodeViewDesc));\n\n// A dummy desc used to tag trailing BR or span nodes created to work\n// around contentEditable terribleness.\nvar BRHackViewDesc = /*@__PURE__*/(function (ViewDesc) {\n function BRHackViewDesc () {\n ViewDesc.apply(this, arguments);\n }\n\n if ( ViewDesc ) BRHackViewDesc.__proto__ = ViewDesc;\n BRHackViewDesc.prototype = Object.create( ViewDesc && ViewDesc.prototype );\n BRHackViewDesc.prototype.constructor = BRHackViewDesc;\n\n BRHackViewDesc.prototype.parseRule = function parseRule () { return {ignore: true} };\n BRHackViewDesc.prototype.matchesHack = function matchesHack () { return this.dirty == NOT_DIRTY };\n\n return BRHackViewDesc;\n}(ViewDesc));\n\n// A separate subclass is used for customized node views, so that the\n// extra checks only have to be made for nodes that are actually\n// customized.\nvar CustomNodeViewDesc = /*@__PURE__*/(function (NodeViewDesc) {\n function CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) {\n NodeViewDesc.call(this, parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos);\n this.spec = spec;\n }\n\n if ( NodeViewDesc ) CustomNodeViewDesc.__proto__ = NodeViewDesc;\n CustomNodeViewDesc.prototype = Object.create( NodeViewDesc && NodeViewDesc.prototype );\n CustomNodeViewDesc.prototype.constructor = CustomNodeViewDesc;\n\n // A custom `update` method gets to decide whether the update goes\n // through. If it does, and there's a `contentDOM` node, our logic\n // updates the children.\n CustomNodeViewDesc.prototype.update = function update (node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY) { return false }\n if (this.spec.update) {\n var result = this.spec.update(node, outerDeco);\n if (result) { this.updateInner(node, outerDeco, innerDeco, view); }\n return result\n } else if (!this.contentDOM && !node.isLeaf) {\n return false\n } else {\n return NodeViewDesc.prototype.update.call(this, node, outerDeco, innerDeco, view)\n }\n };\n\n CustomNodeViewDesc.prototype.selectNode = function selectNode () {\n this.spec.selectNode ? this.spec.selectNode() : NodeViewDesc.prototype.selectNode.call(this);\n };\n\n CustomNodeViewDesc.prototype.deselectNode = function deselectNode () {\n this.spec.deselectNode ? this.spec.deselectNode() : NodeViewDesc.prototype.deselectNode.call(this);\n };\n\n CustomNodeViewDesc.prototype.setSelection = function setSelection (anchor, head, root, force) {\n this.spec.setSelection ? this.spec.setSelection(anchor, head, root)\n : NodeViewDesc.prototype.setSelection.call(this, anchor, head, root, force);\n };\n\n CustomNodeViewDesc.prototype.destroy = function destroy () {\n if (this.spec.destroy) { this.spec.destroy(); }\n NodeViewDesc.prototype.destroy.call(this);\n };\n\n CustomNodeViewDesc.prototype.stopEvent = function stopEvent (event) {\n return this.spec.stopEvent ? this.spec.stopEvent(event) : false\n };\n\n CustomNodeViewDesc.prototype.ignoreMutation = function ignoreMutation (mutation) {\n return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : NodeViewDesc.prototype.ignoreMutation.call(this, mutation)\n };\n\n return CustomNodeViewDesc;\n}(NodeViewDesc));\n\n// : (dom.Node, [ViewDesc])\n// Sync the content of the given DOM node with the nodes associated\n// with the given array of view descs, recursing into mark descs\n// because this should sync the subtree for a whole node at a time.\nfunction renderDescs(parentDOM, descs, view) {\n var dom = parentDOM.firstChild, written = false;\n for (var i = 0; i < descs.length; i++) {\n var desc = descs[i], childDOM = desc.dom;\n if (childDOM.parentNode == parentDOM) {\n while (childDOM != dom) { dom = rm(dom); written = true; }\n dom = dom.nextSibling;\n } else {\n written = true;\n parentDOM.insertBefore(childDOM, dom);\n }\n if (desc instanceof MarkViewDesc) {\n var pos = dom ? dom.previousSibling : parentDOM.lastChild;\n renderDescs(desc.contentDOM, desc.children, view);\n dom = pos ? pos.nextSibling : parentDOM.firstChild;\n }\n }\n while (dom) { dom = rm(dom); written = true; }\n if (written && view.trackWrites == parentDOM) { view.trackWrites = null; }\n}\n\nfunction OuterDecoLevel(nodeName) {\n if (nodeName) { this.nodeName = nodeName; }\n}\nOuterDecoLevel.prototype = Object.create(null);\n\nvar noDeco = [new OuterDecoLevel];\n\nfunction computeOuterDeco(outerDeco, node, needsWrap) {\n if (outerDeco.length == 0) { return noDeco }\n\n var top = needsWrap ? noDeco[0] : new OuterDecoLevel, result = [top];\n\n for (var i = 0; i < outerDeco.length; i++) {\n var attrs = outerDeco[i].type.attrs, cur = top;\n if (!attrs) { continue }\n if (attrs.nodeName)\n { result.push(cur = new OuterDecoLevel(attrs.nodeName)); }\n\n for (var name in attrs) {\n var val = attrs[name];\n if (val == null) { continue }\n if (needsWrap && result.length == 1)\n { result.push(cur = top = new OuterDecoLevel(node.isInline ? \"span\" : \"div\")); }\n if (name == \"class\") { cur.class = (cur.class ? cur.class + \" \" : \"\") + val; }\n else if (name == \"style\") { cur.style = (cur.style ? cur.style + \";\" : \"\") + val; }\n else if (name != \"nodeName\") { cur[name] = val; }\n }\n }\n\n return result\n}\n\nfunction patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {\n // Shortcut for trivial case\n if (prevComputed == noDeco && curComputed == noDeco) { return nodeDOM }\n\n var curDOM = nodeDOM;\n for (var i = 0; i < curComputed.length; i++) {\n var deco = curComputed[i], prev = prevComputed[i];\n if (i) {\n var parent = (void 0);\n if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM &&\n (parent = curDOM.parentNode) && parent.tagName.toLowerCase() == deco.nodeName) {\n curDOM = parent;\n } else {\n parent = document.createElement(deco.nodeName);\n parent.pmIsDeco = true;\n parent.appendChild(curDOM);\n prev = noDeco[0];\n curDOM = parent;\n }\n }\n patchAttributes(curDOM, prev || noDeco[0], deco);\n }\n return curDOM\n}\n\nfunction patchAttributes(dom, prev, cur) {\n for (var name in prev)\n { if (name != \"class\" && name != \"style\" && name != \"nodeName\" && !(name in cur))\n { dom.removeAttribute(name); } }\n for (var name$1 in cur)\n { if (name$1 != \"class\" && name$1 != \"style\" && name$1 != \"nodeName\" && cur[name$1] != prev[name$1])\n { dom.setAttribute(name$1, cur[name$1]); } }\n if (prev.class != cur.class) {\n var prevList = prev.class ? prev.class.split(\" \") : nothing;\n var curList = cur.class ? cur.class.split(\" \") : nothing;\n for (var i = 0; i < prevList.length; i++) { if (curList.indexOf(prevList[i]) == -1)\n { dom.classList.remove(prevList[i]); } }\n for (var i$1 = 0; i$1 < curList.length; i$1++) { if (prevList.indexOf(curList[i$1]) == -1)\n { dom.classList.add(curList[i$1]); } }\n }\n if (prev.style != cur.style) {\n if (prev.style) {\n var prop = /\\s*([\\w\\-\\xa1-\\uffff]+)\\s*:(?:\"(?:\\\\.|[^\"])*\"|'(?:\\\\.|[^'])*'|\\(.*?\\)|[^;])*/g, m;\n while (m = prop.exec(prev.style))\n { dom.style.removeProperty(m[1]); }\n }\n if (cur.style)\n { dom.style.cssText += cur.style; }\n }\n}\n\nfunction applyOuterDeco(dom, deco, node) {\n return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1))\n}\n\n// : ([Decoration], [Decoration]) → bool\nfunction sameOuterDeco(a, b) {\n if (a.length != b.length) { return false }\n for (var i = 0; i < a.length; i++) { if (!a[i].type.eq(b[i].type)) { return false } }\n return true\n}\n\n// Remove a DOM node and return its next sibling.\nfunction rm(dom) {\n var next = dom.nextSibling;\n dom.parentNode.removeChild(dom);\n return next\n}\n\n// Helper class for incrementally updating a tree of mark descs and\n// the widget and node descs inside of them.\nvar ViewTreeUpdater = function ViewTreeUpdater(top, lockedNode) {\n this.top = top;\n this.lock = lockedNode;\n // Index into `this.top`'s child array, represents the current\n // update position.\n this.index = 0;\n // When entering a mark, the current top and index are pushed\n // onto this.\n this.stack = [];\n // Tracks whether anything was changed\n this.changed = false;\n\n var pre = preMatch(top.node.content, top.children);\n this.preMatched = pre.nodes;\n this.preMatchOffset = pre.offset;\n};\n\nViewTreeUpdater.prototype.getPreMatch = function getPreMatch (index) {\n return index >= this.preMatchOffset ? this.preMatched[index - this.preMatchOffset] : null\n};\n\n// Destroy and remove the children between the given indices in\n// `this.top`.\nViewTreeUpdater.prototype.destroyBetween = function destroyBetween (start, end) {\n if (start == end) { return }\n for (var i = start; i < end; i++) { this.top.children[i].destroy(); }\n this.top.children.splice(start, end - start);\n this.changed = true;\n};\n\n// Destroy all remaining children in `this.top`.\nViewTreeUpdater.prototype.destroyRest = function destroyRest () {\n this.destroyBetween(this.index, this.top.children.length);\n};\n\n// : ([Mark], EditorView)\n// Sync the current stack of mark descs with the given array of\n// marks, reusing existing mark descs when possible.\nViewTreeUpdater.prototype.syncToMarks = function syncToMarks (marks, inline, view) {\n var keep = 0, depth = this.stack.length >> 1;\n var maxKeep = Math.min(depth, marks.length);\n while (keep < maxKeep &&\n (keep == depth - 1 ? this.top : this.stack[(keep + 1) << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)\n { keep++; }\n\n while (keep < depth) {\n this.destroyRest();\n this.top.dirty = NOT_DIRTY;\n this.index = this.stack.pop();\n this.top = this.stack.pop();\n depth--;\n }\n while (depth < marks.length) {\n this.stack.push(this.top, this.index + 1);\n var found = -1;\n for (var i = this.index; i < Math.min(this.index + 3, this.top.children.length); i++) {\n if (this.top.children[i].matchesMark(marks[depth])) { found = i; break }\n }\n if (found > -1) {\n if (found > this.index) {\n this.changed = true;\n this.destroyBetween(this.index, found);\n }\n this.top = this.top.children[this.index];\n } else {\n var markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view);\n this.top.children.splice(this.index, 0, markDesc);\n this.top = markDesc;\n this.changed = true;\n }\n this.index = 0;\n depth++;\n }\n};\n\n// : (Node, [Decoration], DecorationSet) → bool\n// Try to find a node desc matching the given data. Skip over it and\n// return true when successful.\nViewTreeUpdater.prototype.findNodeMatch = function findNodeMatch (node, outerDeco, innerDeco, index) {\n var found = -1, preMatch = index < 0 ? undefined : this.getPreMatch(index), children = this.top.children;\n if (preMatch && preMatch.matchesNode(node, outerDeco, innerDeco)) {\n found = children.indexOf(preMatch);\n } else {\n for (var i = this.index, e = Math.min(children.length, i + 5); i < e; i++) {\n var child = children[i];\n if (child.matchesNode(node, outerDeco, innerDeco) && this.preMatched.indexOf(child) < 0) {\n found = i;\n break\n }\n }\n }\n if (found < 0) { return false }\n this.destroyBetween(this.index, found);\n this.index++;\n return true\n};\n\n// : (Node, [Decoration], DecorationSet, EditorView, Fragment, number) → bool\n// Try to update the next node, if any, to the given data. Checks\n// pre-matches to avoid overwriting nodes that could still be used.\nViewTreeUpdater.prototype.updateNextNode = function updateNextNode (node, outerDeco, innerDeco, view, index) {\n for (var i = this.index; i < this.top.children.length; i++) {\n var next = this.top.children[i];\n if (next instanceof NodeViewDesc) {\n var preMatch = this.preMatched.indexOf(next);\n if (preMatch > -1 && preMatch + this.preMatchOffset != index) { return false }\n var nextDOM = next.dom;\n\n // Can't update if nextDOM is or contains this.lock, except if\n // it's a text node whose content already matches the new text\n // and whose decorations match the new ones.\n var locked = this.lock && (nextDOM == this.lock || nextDOM.nodeType == 1 && nextDOM.contains(this.lock.parentNode)) &&\n !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text &&\n next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco));\n if (!locked && next.update(node, outerDeco, innerDeco, view)) {\n this.destroyBetween(this.index, i);\n if (next.dom != nextDOM) { this.changed = true; }\n this.index++;\n return true\n }\n break\n }\n }\n return false\n};\n\n// : (Node, [Decoration], DecorationSet, EditorView)\n// Insert the node as a newly created node desc.\nViewTreeUpdater.prototype.addNode = function addNode (node, outerDeco, innerDeco, view, pos) {\n this.top.children.splice(this.index++, 0, NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos));\n this.changed = true;\n};\n\nViewTreeUpdater.prototype.placeWidget = function placeWidget (widget, view, pos) {\n var next = this.index < this.top.children.length ? this.top.children[this.index] : null;\n if (next && next.matchesWidget(widget) && (widget == next.widget || !next.widget.type.toDOM.parentNode)) {\n this.index++;\n } else {\n var desc = new WidgetViewDesc(this.top, widget, view, pos);\n this.top.children.splice(this.index++, 0, desc);\n this.changed = true;\n }\n};\n\n// Make sure a textblock looks and behaves correctly in\n// contentEditable.\nViewTreeUpdater.prototype.addTextblockHacks = function addTextblockHacks () {\n var lastChild = this.top.children[this.index - 1];\n while (lastChild instanceof MarkViewDesc) { lastChild = lastChild.children[lastChild.children.length - 1]; }\n\n if (!lastChild || // Empty textblock\n !(lastChild instanceof TextViewDesc) ||\n /\\n$/.test(lastChild.node.text)) {\n if (this.index < this.top.children.length && this.top.children[this.index].matchesHack()) {\n this.index++;\n } else {\n var dom = document.createElement(\"br\");\n this.top.children.splice(this.index++, 0, new BRHackViewDesc(this.top, nothing, dom, null));\n this.changed = true;\n }\n }\n};\n\n// : (Fragment, [ViewDesc]) → [ViewDesc]\n// Iterate from the end of the fragment and array of descs to find\n// directly matching ones, in order to avoid overeagerly reusing\n// those for other nodes. Returns an array whose positions correspond\n// to node positions in the fragment, and whose elements are either\n// descs matched to the child at that index, or empty.\nfunction preMatch(frag, descs) {\n var result = [], end = frag.childCount;\n for (var i = descs.length - 1; end > 0 && i >= 0; i--) {\n var desc = descs[i], node = desc.node;\n if (!node) { continue }\n if (node != frag.child(end - 1)) { break }\n result.push(desc);\n --end;\n }\n return {nodes: result.reverse(), offset: end}\n}\n\nfunction compareSide(a, b) { return a.type.side - b.type.side }\n\n// : (ViewDesc, DecorationSet, (Decoration, number), (Node, [Decoration], DecorationSet, number))\n// This function abstracts iterating over the nodes and decorations in\n// a fragment. Calls `onNode` for each node, with its local and child\n// decorations. Splits text nodes when there is a decoration starting\n// or ending inside of them. Calls `onWidget` for each widget.\nfunction iterDeco(parent, deco, onWidget, onNode) {\n var locals = deco.locals(parent), offset = 0;\n // Simple, cheap variant for when there are no local decorations\n if (locals.length == 0) {\n for (var i = 0; i < parent.childCount; i++) {\n var child = parent.child(i);\n onNode(child, locals, deco.forChild(offset, child), i);\n offset += child.nodeSize;\n }\n return\n }\n\n var decoIndex = 0, active = [], restNode = null;\n for (var parentIndex = 0;;) {\n if (decoIndex < locals.length && locals[decoIndex].to == offset) {\n var widget = locals[decoIndex++], widgets = (void 0);\n while (decoIndex < locals.length && locals[decoIndex].to == offset)\n { (widgets || (widgets = [widget])).push(locals[decoIndex++]); }\n if (widgets) {\n widgets.sort(compareSide);\n for (var i$1 = 0; i$1 < widgets.length; i$1++) { onWidget(widgets[i$1], parentIndex, !!restNode); }\n } else {\n onWidget(widget, parentIndex, !!restNode);\n }\n }\n\n var child$1 = (void 0), index = (void 0);\n if (restNode) {\n index = -1;\n child$1 = restNode;\n restNode = null;\n } else if (parentIndex < parent.childCount) {\n index = parentIndex;\n child$1 = parent.child(parentIndex++);\n } else {\n break\n }\n\n for (var i$2 = 0; i$2 < active.length; i$2++) { if (active[i$2].to <= offset) { active.splice(i$2--, 1); } }\n while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)\n { active.push(locals[decoIndex++]); }\n\n var end = offset + child$1.nodeSize;\n if (child$1.isText) {\n var cutAt = end;\n if (decoIndex < locals.length && locals[decoIndex].from < cutAt) { cutAt = locals[decoIndex].from; }\n for (var i$3 = 0; i$3 < active.length; i$3++) { if (active[i$3].to < cutAt) { cutAt = active[i$3].to; } }\n if (cutAt < end) {\n restNode = child$1.cut(cutAt - offset);\n child$1 = child$1.cut(0, cutAt - offset);\n end = cutAt;\n index = -1;\n }\n }\n\n var outerDeco = !active.length ? nothing\n : child$1.isInline && !child$1.isLeaf ? active.filter(function (d) { return !d.inline; })\n : active.slice();\n onNode(child$1, outerDeco, deco.forChild(offset, child$1), index);\n offset = end;\n }\n}\n\n// List markers in Mobile Safari will mysteriously disappear\n// sometimes. This works around that.\nfunction iosHacks(dom) {\n if (dom.nodeName == \"UL\" || dom.nodeName == \"OL\") {\n var oldCSS = dom.style.cssText;\n dom.style.cssText = oldCSS + \"; list-style: square !important\";\n window.getComputedStyle(dom).listStyle;\n dom.style.cssText = oldCSS;\n }\n}\n\nfunction nearbyTextNode(node, offset) {\n for (;;) {\n if (node.nodeType == 3) { return node }\n if (node.nodeType == 1 && offset > 0) {\n if (node.childNodes.length > offset && node.childNodes[offset].nodeType == 3)\n { return node.childNodes[offset] }\n node = node.childNodes[offset - 1];\n offset = nodeSize(node);\n } else if (node.nodeType == 1 && offset < node.childNodes.length) {\n node = node.childNodes[offset];\n offset = 0;\n } else {\n return null\n }\n }\n}\n\n// Find a piece of text in an inline fragment, overlapping from-to\nfunction findTextInFragment(frag, text, from, to) {\n for (var i = 0, pos = 0; i < frag.childCount && pos <= to;) {\n var child = frag.child(i++), childStart = pos;\n pos += child.nodeSize;\n if (!child.isText) { continue }\n var str = child.text;\n while (i < frag.childCount) {\n var next = frag.child(i++);\n pos += next.nodeSize;\n if (!next.isText) { break }\n str += next.text;\n }\n if (pos >= from) {\n var found = str.lastIndexOf(text, to - childStart);\n if (found >= 0 && found + text.length + childStart >= from)\n { return childStart + found }\n }\n }\n return -1\n}\n\n// Replace range from-to in an array of view descs with replacement\n// (may be null to just delete). This goes very much against the grain\n// of the rest of this code, which tends to create nodes with the\n// right shape in one go, rather than messing with them after\n// creation, but is necessary in the composition hack.\nfunction replaceNodes(nodes, from, to, view, replacement) {\n var result = [];\n for (var i = 0, off = 0; i < nodes.length; i++) {\n var child = nodes[i], start = off, end = off += child.size;\n if (start >= to || end <= from) {\n result.push(child);\n } else {\n if (start < from) { result.push(child.slice(0, from - start, view)); }\n if (replacement) {\n result.push(replacement);\n replacement = null;\n }\n if (end > to) { result.push(child.slice(to - start, child.size, view)); }\n }\n }\n return result\n}\n\nfunction selectionFromDOM(view, origin) {\n var domSel = view.root.getSelection(), doc = view.state.doc;\n if (!domSel.focusNode) { return null }\n var nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;\n var head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);\n if (head < 0) { return null }\n var $head = doc.resolve(head), $anchor, selection;\n if (selectionCollapsed(domSel)) {\n $anchor = $head;\n while (nearestDesc && !nearestDesc.node) { nearestDesc = nearestDesc.parent; }\n if (nearestDesc && nearestDesc.node.isAtom && NodeSelection.isSelectable(nearestDesc.node) && nearestDesc.parent\n && !(nearestDesc.node.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {\n var pos = nearestDesc.posBefore;\n selection = new NodeSelection(head == pos ? $head : doc.resolve(pos));\n }\n } else {\n var anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);\n if (anchor < 0) { return null }\n $anchor = doc.resolve(anchor);\n }\n\n if (!selection) {\n var bias = origin == \"pointer\" || (view.state.selection.head < $head.pos && !inWidget) ? 1 : -1;\n selection = selectionBetween(view, $anchor, $head, bias);\n }\n return selection\n}\n\nfunction selectionToDOM(view, force) {\n var sel = view.state.selection;\n syncNodeSelection(view, sel);\n\n if (view.editable ? !view.hasFocus() :\n !(hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom))) { return }\n\n view.domObserver.disconnectSelection();\n\n if (view.cursorWrapper) {\n selectCursorWrapper(view);\n } else {\n var anchor = sel.anchor;\n var head = sel.head;\n var resetEditableFrom, resetEditableTo;\n if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) {\n if (!sel.$from.parent.inlineContent)\n { resetEditableFrom = temporarilyEditableNear(view, sel.from); }\n if (!sel.empty && !sel.$from.parent.inlineContent)\n { resetEditableTo = temporarilyEditableNear(view, sel.to); }\n }\n view.docView.setSelection(anchor, head, view.root, force);\n if (brokenSelectBetweenUneditable) {\n if (resetEditableFrom) { resetEditable(resetEditableFrom); }\n if (resetEditableTo) { resetEditable(resetEditableTo); }\n }\n if (sel.visible) {\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n } else {\n view.dom.classList.add(\"ProseMirror-hideselection\");\n if (\"onselectionchange\" in document) { removeClassOnSelectionChange(view); }\n }\n }\n\n view.domObserver.setCurSelection();\n view.domObserver.connectSelection();\n}\n\n// Kludge to work around Webkit not allowing a selection to start/end\n// between non-editable block nodes. We briefly make something\n// editable, set the selection, then set it uneditable again.\n\nvar brokenSelectBetweenUneditable = result.safari || result.chrome && result.chrome_version < 63;\n\nfunction temporarilyEditableNear(view, pos) {\n var ref = view.docView.domFromPos(pos);\n var node = ref.node;\n var offset = ref.offset;\n var after = offset < node.childNodes.length ? node.childNodes[offset] : null;\n var before = offset ? node.childNodes[offset - 1] : null;\n if (result.safari && after && after.contentEditable == \"false\") { return setEditable(after) }\n if ((!after || after.contentEditable == \"false\") && (!before || before.contentEditable == \"false\")) {\n if (after) { return setEditable(after) }\n else if (before) { return setEditable(before) }\n }\n}\n\nfunction setEditable(element) {\n element.contentEditable = \"true\";\n if (result.safari && element.draggable) { element.draggable = false; element.wasDraggable = true; }\n return element\n}\n\nfunction resetEditable(element) {\n element.contentEditable = \"false\";\n if (element.wasDraggable) { element.draggable = true; element.wasDraggable = null; }\n}\n\nfunction removeClassOnSelectionChange(view) {\n var doc = view.dom.ownerDocument;\n doc.removeEventListener(\"selectionchange\", view.hideSelectionGuard);\n var domSel = view.root.getSelection();\n var node = domSel.anchorNode, offset = domSel.anchorOffset;\n doc.addEventListener(\"selectionchange\", view.hideSelectionGuard = function () {\n if (domSel.anchorNode != node || domSel.anchorOffset != offset) {\n doc.removeEventListener(\"selectionchange\", view.hideSelectionGuard);\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n }\n });\n}\n\nfunction selectCursorWrapper(view) {\n var domSel = view.root.getSelection(), range = document.createRange();\n var node = view.cursorWrapper.dom, img = node.nodeName == \"IMG\";\n if (img) { range.setEnd(node.parentNode, domIndex(node) + 1); }\n else { range.setEnd(node, 0); }\n range.collapse(false);\n domSel.removeAllRanges();\n domSel.addRange(range);\n // Kludge to kill 'control selection' in IE11 when selecting an\n // invisible cursor wrapper, since that would result in those weird\n // resize handles and a selection that considers the absolutely\n // positioned wrapper, rather than the root editable node, the\n // focused element.\n if (!img && !view.state.selection.visible && result.ie && result.ie_version <= 11) {\n node.disabled = true;\n node.disabled = false;\n }\n}\n\nfunction syncNodeSelection(view, sel) {\n if (sel instanceof NodeSelection) {\n var desc = view.docView.descAt(sel.from);\n if (desc != view.lastSelectedViewDesc) {\n clearNodeSelection(view);\n if (desc) { desc.selectNode(); }\n view.lastSelectedViewDesc = desc;\n }\n } else {\n clearNodeSelection(view);\n }\n}\n\n// Clear all DOM statefulness of the last node selection.\nfunction clearNodeSelection(view) {\n if (view.lastSelectedViewDesc) {\n if (view.lastSelectedViewDesc.parent)\n { view.lastSelectedViewDesc.deselectNode(); }\n view.lastSelectedViewDesc = null;\n }\n}\n\nfunction selectionBetween(view, $anchor, $head, bias) {\n return view.someProp(\"createSelectionBetween\", function (f) { return f(view, $anchor, $head); })\n || TextSelection.between($anchor, $head, bias)\n}\n\nfunction hasFocusAndSelection(view) {\n if (view.editable && view.root.activeElement != view.dom) { return false }\n return hasSelection(view)\n}\n\nfunction hasSelection(view) {\n var sel = view.root.getSelection();\n if (!sel.anchorNode) { return false }\n try {\n // Firefox will raise 'permission denied' errors when accessing\n // properties of `sel.anchorNode` when it's in a generated CSS\n // element.\n return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) &&\n (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode))\n } catch(_) {\n return false\n }\n}\n\nfunction anchorInRightPlace(view) {\n var anchorDOM = view.docView.domFromPos(view.state.selection.anchor);\n var domSel = view.root.getSelection();\n return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset)\n}\n\nfunction moveSelectionBlock(state, dir) {\n var ref = state.selection;\n var $anchor = ref.$anchor;\n var $head = ref.$head;\n var $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);\n var $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;\n return $start && Selection.findFrom($start, dir)\n}\n\nfunction apply(view, sel) {\n view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());\n return true\n}\n\nfunction selectHorizontally(view, dir, mods) {\n var sel = view.state.selection;\n if (sel instanceof TextSelection) {\n if (!sel.empty || mods.indexOf(\"s\") > -1) {\n return false\n } else if (view.endOfTextblock(dir > 0 ? \"right\" : \"left\")) {\n var next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection)) { return apply(view, next) }\n return false\n } else if (!(result.mac && mods.indexOf(\"m\") > -1)) {\n var $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;\n if (!node || node.isText) { return false }\n var nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos;\n if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM)) { return false }\n if (NodeSelection.isSelectable(node)) {\n return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head))\n } else if (result.webkit) {\n // Chrome and Safari will introduce extra pointless cursor\n // positions around inline uneditable nodes, so we have to\n // take over and move the cursor past them (#937)\n return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize)))\n } else {\n return false\n }\n }\n } else if (sel instanceof NodeSelection && sel.node.isInline) {\n return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from))\n } else {\n var next$1 = moveSelectionBlock(view.state, dir);\n if (next$1) { return apply(view, next$1) }\n return false\n }\n}\n\nfunction nodeLen(node) {\n return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length\n}\n\nfunction isIgnorable(dom) {\n var desc = dom.pmViewDesc;\n return desc && desc.size == 0 && (dom.nextSibling || dom.nodeName != \"BR\")\n}\n\n// Make sure the cursor isn't directly after one or more ignored\n// nodes, which will confuse the browser's cursor motion logic.\nfunction skipIgnoredNodesLeft(view) {\n var sel = view.root.getSelection();\n var node = sel.focusNode, offset = sel.focusOffset;\n if (!node) { return }\n var moveNode, moveOffset, force = false;\n // Gecko will do odd things when the selection is directly in front\n // of a non-editable node, so in that case, move it into the next\n // node if possible. Issue prosemirror/prosemirror#832.\n if (result.gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset])) { force = true; }\n for (;;) {\n if (offset > 0) {\n if (node.nodeType != 1) {\n break\n } else {\n var before = node.childNodes[offset - 1];\n if (isIgnorable(before)) {\n moveNode = node;\n moveOffset = --offset;\n } else if (before.nodeType == 3) {\n node = before;\n offset = node.nodeValue.length;\n } else { break }\n }\n } else if (isBlockNode(node)) {\n break\n } else {\n var prev = node.previousSibling;\n while (prev && isIgnorable(prev)) {\n moveNode = node.parentNode;\n moveOffset = domIndex(prev);\n prev = prev.previousSibling;\n }\n if (!prev) {\n node = node.parentNode;\n if (node == view.dom) { break }\n offset = 0;\n } else {\n node = prev;\n offset = nodeLen(node);\n }\n }\n }\n if (force) { setSelFocus(view, sel, node, offset); }\n else if (moveNode) { setSelFocus(view, sel, moveNode, moveOffset); }\n}\n\n// Make sure the cursor isn't directly before one or more ignored\n// nodes.\nfunction skipIgnoredNodesRight(view) {\n var sel = view.root.getSelection();\n var node = sel.focusNode, offset = sel.focusOffset;\n if (!node) { return }\n var len = nodeLen(node);\n var moveNode, moveOffset;\n for (;;) {\n if (offset < len) {\n if (node.nodeType != 1) { break }\n var after = node.childNodes[offset];\n if (isIgnorable(after)) {\n moveNode = node;\n moveOffset = ++offset;\n }\n else { break }\n } else if (isBlockNode(node)) {\n break\n } else {\n var next = node.nextSibling;\n while (next && isIgnorable(next)) {\n moveNode = next.parentNode;\n moveOffset = domIndex(next) + 1;\n next = next.nextSibling;\n }\n if (!next) {\n node = node.parentNode;\n if (node == view.dom) { break }\n offset = len = 0;\n } else {\n node = next;\n offset = 0;\n len = nodeLen(node);\n }\n }\n }\n if (moveNode) { setSelFocus(view, sel, moveNode, moveOffset); }\n}\n\nfunction isBlockNode(dom) {\n var desc = dom.pmViewDesc;\n return desc && desc.node && desc.node.isBlock\n}\n\nfunction setSelFocus(view, sel, node, offset) {\n if (selectionCollapsed(sel)) {\n var range = document.createRange();\n range.setEnd(node, offset);\n range.setStart(node, offset);\n sel.removeAllRanges();\n sel.addRange(range);\n } else if (sel.extend) {\n sel.extend(node, offset);\n }\n view.domObserver.setCurSelection();\n var state = view.state;\n // If no state update ends up happening, reset the selection.\n setTimeout(function () {\n if (view.state == state) { selectionToDOM(view); }\n }, 50);\n}\n\n// : (EditorState, number)\n// Check whether vertical selection motion would involve node\n// selections. If so, apply it (if not, the result is left to the\n// browser)\nfunction selectVertically(view, dir, mods) {\n var sel = view.state.selection;\n if (sel instanceof TextSelection && !sel.empty || mods.indexOf(\"s\") > -1) { return false }\n if (result.mac && mods.indexOf(\"m\") > -1) { return false }\n var $from = sel.$from;\n var $to = sel.$to;\n\n if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? \"up\" : \"down\")) {\n var next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection))\n { return apply(view, next) }\n }\n if (!$from.parent.inlineContent) {\n var beyond = Selection.findFrom(dir < 0 ? $from : $to, dir);\n return beyond ? apply(view, beyond) : true\n }\n return false\n}\n\nfunction stopNativeHorizontalDelete(view, dir) {\n if (!(view.state.selection instanceof TextSelection)) { return true }\n var ref = view.state.selection;\n var $head = ref.$head;\n var $anchor = ref.$anchor;\n var empty = ref.empty;\n if (!$head.sameParent($anchor)) { return true }\n if (!empty) { return false }\n if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\")) { return true }\n var nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);\n if (nextNode && !nextNode.isText) {\n var tr = view.state.tr;\n if (dir < 0) { tr.delete($head.pos - nextNode.nodeSize, $head.pos); }\n else { tr.delete($head.pos, $head.pos + nextNode.nodeSize); }\n view.dispatch(tr);\n return true\n }\n return false\n}\n\nfunction switchEditable(view, node, state) {\n view.domObserver.stop();\n node.contentEditable = state;\n view.domObserver.start();\n}\n\n// Issue #867 / #1090 / https://bugs.chromium.org/p/chromium/issues/detail?id=903821\n// In which Safari (and at some point in the past, Chrome) does really\n// wrong things when the down arrow is pressed when the cursor is\n// directly at the start of a textblock and has an uneditable node\n// after it\nfunction safariDownArrowBug(view) {\n if (!result.safari || view.state.selection.$head.parentOffset > 0) { return }\n var ref = view.root.getSelection();\n var focusNode = ref.focusNode;\n var focusOffset = ref.focusOffset;\n if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 &&\n focusNode.firstChild && focusNode.firstChild.contentEditable == \"false\") {\n var child = focusNode.firstChild;\n switchEditable(view, child, true);\n setTimeout(function () { return switchEditable(view, child, false); }, 20);\n }\n}\n\n// A backdrop key mapping used to make sure we always suppress keys\n// that have a dangerous default effect, even if the commands they are\n// bound to return false, and to make sure that cursor-motion keys\n// find a cursor (as opposed to a node selection) when pressed. For\n// cursor-motion keys, the code in the handlers also takes care of\n// block selections.\n\nfunction getMods(event) {\n var result = \"\";\n if (event.ctrlKey) { result += \"c\"; }\n if (event.metaKey) { result += \"m\"; }\n if (event.altKey) { result += \"a\"; }\n if (event.shiftKey) { result += \"s\"; }\n return result\n}\n\nfunction captureKeyDown(view, event) {\n var code = event.keyCode, mods = getMods(event);\n if (code == 8 || (result.mac && code == 72 && mods == \"c\")) { // Backspace, Ctrl-h on Mac\n return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodesLeft(view)\n } else if (code == 46 || (result.mac && code == 68 && mods == \"c\")) { // Delete, Ctrl-d on Mac\n return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodesRight(view)\n } else if (code == 13 || code == 27) { // Enter, Esc\n return true\n } else if (code == 37) { // Left arrow\n return selectHorizontally(view, -1, mods) || skipIgnoredNodesLeft(view)\n } else if (code == 39) { // Right arrow\n return selectHorizontally(view, 1, mods) || skipIgnoredNodesRight(view)\n } else if (code == 38) { // Up arrow\n return selectVertically(view, -1, mods) || skipIgnoredNodesLeft(view)\n } else if (code == 40) { // Down arrow\n return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodesRight(view)\n } else if (mods == (result.mac ? \"m\" : \"c\") &&\n (code == 66 || code == 73 || code == 89 || code == 90)) { // Mod-[biyz]\n return true\n }\n return false\n}\n\n// Note that all referencing and parsing is done with the\n// start-of-operation selection and document, since that's the one\n// that the DOM represents. If any changes came in in the meantime,\n// the modification is mapped over those before it is applied, in\n// readDOMChange.\n\nfunction parseBetween(view, from_, to_) {\n var ref = view.docView.parseRange(from_, to_);\n var parent = ref.node;\n var fromOffset = ref.fromOffset;\n var toOffset = ref.toOffset;\n var from = ref.from;\n var to = ref.to;\n\n var domSel = view.root.getSelection(), find = null, anchor = domSel.anchorNode;\n if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) {\n find = [{node: anchor, offset: domSel.anchorOffset}];\n if (!selectionCollapsed(domSel))\n { find.push({node: domSel.focusNode, offset: domSel.focusOffset}); }\n }\n // Work around issue in Chrome where backspacing sometimes replaces\n // the deleted content with a random BR node (issues #799, #831)\n if (result.chrome && view.lastKeyCode === 8) {\n for (var off = toOffset; off > fromOffset; off--) {\n var node = parent.childNodes[off - 1], desc = node.pmViewDesc;\n if (node.nodeType == \"BR\" && !desc) { toOffset = off; break }\n if (!desc || desc.size) { break }\n }\n }\n var startDoc = view.state.doc;\n var parser = view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n var $from = startDoc.resolve(from);\n\n var sel = null, doc = parser.parse(parent, {\n topNode: $from.parent,\n topMatch: $from.parent.contentMatchAt($from.index()),\n topOpen: true,\n from: fromOffset,\n to: toOffset,\n preserveWhitespace: $from.parent.type.spec.code ? \"full\" : true,\n editableContent: true,\n findPositions: find,\n ruleFromNode: ruleFromNode,\n context: $from\n });\n if (find && find[0].pos != null) {\n var anchor$1 = find[0].pos, head = find[1] && find[1].pos;\n if (head == null) { head = anchor$1; }\n sel = {anchor: anchor$1 + from, head: head + from};\n }\n return {doc: doc, sel: sel, from: from, to: to}\n}\n\nfunction ruleFromNode(dom) {\n var desc = dom.pmViewDesc;\n if (desc) {\n return desc.parseRule()\n } else if (dom.nodeName == \"BR\" && dom.parentNode) {\n // Safari replaces the list item or table cell with a BR\n // directly in the list node (?!) if you delete the last\n // character in a list item or table cell (#708, #862)\n if (result.safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {\n var skip = document.createElement(\"div\");\n skip.appendChild(document.createElement(\"li\"));\n return {skip: skip}\n } else if (dom.parentNode.lastChild == dom || result.safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {\n return {ignore: true}\n }\n } else if (dom.nodeName == \"IMG\" && dom.getAttribute(\"mark-placeholder\")) {\n return {ignore: true}\n }\n}\n\nfunction readDOMChange(view, from, to, typeOver, addedNodes) {\n if (from < 0) {\n var origin = view.lastSelectionTime > Date.now() - 50 ? view.lastSelectionOrigin : null;\n var newSel = selectionFromDOM(view, origin);\n if (newSel && !view.state.selection.eq(newSel)) {\n var tr$1 = view.state.tr.setSelection(newSel);\n if (origin == \"pointer\") { tr$1.setMeta(\"pointer\", true); }\n else if (origin == \"key\") { tr$1.scrollIntoView(); }\n view.dispatch(tr$1);\n }\n return\n }\n\n var $before = view.state.doc.resolve(from);\n var shared = $before.sharedDepth(to);\n from = $before.before(shared + 1);\n to = view.state.doc.resolve(to).after(shared + 1);\n\n var sel = view.state.selection;\n var parse = parseBetween(view, from, to);\n\n var doc = view.state.doc, compare = doc.slice(parse.from, parse.to);\n var preferredPos, preferredSide;\n // Prefer anchoring to end when Backspace is pressed\n if (view.lastKeyCode === 8 && Date.now() - 100 < view.lastKeyCodeTime) {\n preferredPos = view.state.selection.to;\n preferredSide = \"end\";\n } else {\n preferredPos = view.state.selection.from;\n preferredSide = \"start\";\n }\n view.lastKeyCode = null;\n\n var change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide);\n if (!change) {\n if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) &&\n !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) {\n change = {start: sel.from, endA: sel.to, endB: sel.to};\n } else {\n if (parse.sel) {\n var sel$1 = resolveSelection(view, view.state.doc, parse.sel);\n if (sel$1 && !sel$1.eq(view.state.selection)) { view.dispatch(view.state.tr.setSelection(sel$1)); }\n }\n return\n }\n }\n view.domChangeCount++;\n // Handle the case where overwriting a selection by typing matches\n // the start or end of the selected content, creating a change\n // that's smaller than what was actually overwritten.\n if (view.state.selection.from < view.state.selection.to &&\n change.start == change.endB &&\n view.state.selection instanceof TextSelection) {\n if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2) {\n change.start = view.state.selection.from;\n } else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2) {\n change.endB += (view.state.selection.to - change.endA);\n change.endA = view.state.selection.to;\n }\n }\n\n // IE11 will insert a non-breaking space _ahead_ of the space after\n // the cursor space when adding a space before another space. When\n // that happened, adjust the change to cover the space instead.\n if (result.ie && result.ie_version <= 11 && change.endB == change.start + 1 &&\n change.endA == change.start && change.start > parse.from &&\n parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == \" \\u00a0\") {\n change.start--;\n change.endA--;\n change.endB--;\n }\n\n var $from = parse.doc.resolveNoCache(change.start - parse.from);\n var $to = parse.doc.resolveNoCache(change.endB - parse.from);\n var inlineChange = $from.sameParent($to) && $from.parent.inlineContent;\n var nextSel;\n // If this looks like the effect of pressing Enter (or was recorded\n // as being an iOS enter press), just dispatch an Enter key instead.\n if (((result.ios && view.lastIOSEnter > Date.now() - 225 &&\n (!inlineChange || addedNodes.some(function (n) { return n.nodeName == \"DIV\" || n.nodeName == \"P\"; }))) ||\n (!inlineChange && $from.pos < parse.doc.content.size &&\n (nextSel = Selection.findFrom(parse.doc.resolve($from.pos + 1), 1, true)) &&\n nextSel.head == $to.pos)) &&\n view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(13, \"Enter\")); })) {\n view.lastIOSEnter = 0;\n return\n }\n // Same for backspace\n if (view.state.selection.anchor > change.start &&\n looksLikeJoin(doc, change.start, change.endA, $from, $to) &&\n view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(8, \"Backspace\")); })) {\n if (result.android && result.chrome) { view.domObserver.suppressSelectionUpdates(); } // #820\n return\n }\n\n // This tries to detect Android virtual keyboard\n // enter-and-pick-suggestion action. That sometimes (see issue\n // #1059) first fires a DOM mutation, before moving the selection to\n // the newly created block. And then, because ProseMirror cleans up\n // the DOM selection, it gives up moving the selection entirely,\n // leaving the cursor in the wrong place. When that happens, we drop\n // the new paragraph from the initial change, and fire a simulated\n // enter key afterwards.\n if (result.android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth &&\n parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) {\n change.endB -= 2;\n $to = parse.doc.resolveNoCache(change.endB - parse.from);\n setTimeout(function () {\n view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(13, \"Enter\")); });\n }, 20);\n }\n\n var chFrom = change.start, chTo = change.endA;\n\n var tr, storedMarks, markChange, $from1;\n if (inlineChange) {\n if ($from.pos == $to.pos) { // Deletion\n // IE11 sometimes weirdly moves the DOM selection around after\n // backspacing out the first element in a textblock\n if (result.ie && result.ie_version <= 11 && $from.parentOffset == 0) {\n view.domObserver.suppressSelectionUpdates();\n setTimeout(function () { return selectionToDOM(view); }, 20);\n }\n tr = view.state.tr.delete(chFrom, chTo);\n storedMarks = doc.resolve(change.start).marksAcross(doc.resolve(change.endA));\n } else if ( // Adding or removing a mark\n change.endA == change.endB && ($from1 = doc.resolve(change.start)) &&\n (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset),\n $from1.parent.content.cut($from1.parentOffset, change.endA - $from1.start())))\n ) {\n tr = view.state.tr;\n if (markChange.type == \"add\") { tr.addMark(chFrom, chTo, markChange.mark); }\n else { tr.removeMark(chFrom, chTo, markChange.mark); }\n } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {\n // Both positions in the same text node -- simply insert text\n var text = $from.parent.textBetween($from.parentOffset, $to.parentOffset);\n if (view.someProp(\"handleTextInput\", function (f) { return f(view, chFrom, chTo, text); })) { return }\n tr = view.state.tr.insertText(text, chFrom, chTo);\n }\n }\n\n if (!tr)\n { tr = view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from)); }\n if (parse.sel) {\n var sel$2 = resolveSelection(view, tr.doc, parse.sel);\n // Chrome Android will sometimes, during composition, report the\n // selection in the wrong place. If it looks like that is\n // happening, don't update the selection.\n // Edge just doesn't move the cursor forward when you start typing\n // in an empty block or between br nodes.\n if (sel$2 && !(result.chrome && result.android && view.composing && sel$2.empty &&\n (sel$2.head == chFrom || sel$2.head == tr.mapping.map(chTo) - 1) ||\n result.ie && sel$2.empty && sel$2.head == chFrom))\n { tr.setSelection(sel$2); }\n }\n if (storedMarks) { tr.ensureMarks(storedMarks); }\n view.dispatch(tr.scrollIntoView());\n}\n\nfunction resolveSelection(view, doc, parsedSel) {\n if (Math.max(parsedSel.anchor, parsedSel.head) > doc.content.size) { return null }\n return selectionBetween(view, doc.resolve(parsedSel.anchor), doc.resolve(parsedSel.head))\n}\n\n// : (Fragment, Fragment) → ?{mark: Mark, type: string}\n// Given two same-length, non-empty fragments of inline content,\n// determine whether the first could be created from the second by\n// removing or adding a single mark type.\nfunction isMarkChange(cur, prev) {\n var curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;\n var added = curMarks, removed = prevMarks, type, mark, update;\n for (var i = 0; i < prevMarks.length; i++) { added = prevMarks[i].removeFromSet(added); }\n for (var i$1 = 0; i$1 < curMarks.length; i$1++) { removed = curMarks[i$1].removeFromSet(removed); }\n if (added.length == 1 && removed.length == 0) {\n mark = added[0];\n type = \"add\";\n update = function (node) { return node.mark(mark.addToSet(node.marks)); };\n } else if (added.length == 0 && removed.length == 1) {\n mark = removed[0];\n type = \"remove\";\n update = function (node) { return node.mark(mark.removeFromSet(node.marks)); };\n } else {\n return null\n }\n var updated = [];\n for (var i$2 = 0; i$2 < prev.childCount; i$2++) { updated.push(update(prev.child(i$2))); }\n if (Fragment.from(updated).eq(cur)) { return {mark: mark, type: type} }\n}\n\nfunction looksLikeJoin(old, start, end, $newStart, $newEnd) {\n if (!$newStart.parent.isTextblock ||\n // The content must have shrunk\n end - start <= $newEnd.pos - $newStart.pos ||\n // newEnd must point directly at or after the end of the block that newStart points into\n skipClosingAndOpening($newStart, true, false) < $newEnd.pos)\n { return false }\n\n var $start = old.resolve(start);\n // Start must be at the end of a block\n if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock)\n { return false }\n var $next = old.resolve(skipClosingAndOpening($start, true, true));\n // The next textblock must start before end and end near it\n if (!$next.parent.isTextblock || $next.pos > end ||\n skipClosingAndOpening($next, true, false) < end)\n { return false }\n\n // The fragments after the join point must match\n return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content)\n}\n\nfunction skipClosingAndOpening($pos, fromEnd, mayOpen) {\n var depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos;\n while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {\n depth--;\n end++;\n fromEnd = false;\n }\n if (mayOpen) {\n var next = $pos.node(depth).maybeChild($pos.indexAfter(depth));\n while (next && !next.isLeaf) {\n next = next.firstChild;\n end++;\n }\n }\n return end\n}\n\nfunction findDiff(a, b, pos, preferredPos, preferredSide) {\n var start = a.findDiffStart(b, pos);\n if (start == null) { return null }\n var ref = a.findDiffEnd(b, pos + a.size, pos + b.size);\n var endA = ref.a;\n var endB = ref.b;\n if (preferredSide == \"end\") {\n var adjust = Math.max(0, start - Math.min(endA, endB));\n preferredPos -= endA + adjust - start;\n }\n if (endA < start && a.size < b.size) {\n var move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0;\n start -= move;\n endB = start + (endB - endA);\n endA = start;\n } else if (endB < start) {\n var move$1 = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0;\n start -= move$1;\n endA = start + (endA - endB);\n endB = start;\n }\n return {start: start, endA: endA, endB: endB}\n}\n\nfunction serializeForClipboard(view, slice) {\n var context = [];\n var content = slice.content;\n var openStart = slice.openStart;\n var openEnd = slice.openEnd;\n while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {\n openStart--;\n openEnd--;\n var node = content.firstChild;\n context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null);\n content = node.content;\n }\n\n var serializer = view.someProp(\"clipboardSerializer\") || DOMSerializer.fromSchema(view.state.schema);\n var doc = detachedDoc(), wrap = doc.createElement(\"div\");\n wrap.appendChild(serializer.serializeFragment(content, {document: doc}));\n\n var firstChild = wrap.firstChild, needsWrap;\n while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {\n for (var i = needsWrap.length - 1; i >= 0; i--) {\n var wrapper = doc.createElement(needsWrap[i]);\n while (wrap.firstChild) { wrapper.appendChild(wrap.firstChild); }\n wrap.appendChild(wrapper);\n }\n firstChild = wrap.firstChild;\n }\n\n if (firstChild && firstChild.nodeType == 1)\n { firstChild.setAttribute(\"data-pm-slice\", (openStart + \" \" + openEnd + \" \" + (JSON.stringify(context)))); }\n\n var text = view.someProp(\"clipboardTextSerializer\", function (f) { return f(slice); }) ||\n slice.content.textBetween(0, slice.content.size, \"\\n\\n\");\n\n return {dom: wrap, text: text}\n}\n\n// : (EditorView, string, string, ?bool, ResolvedPos) → ?Slice\n// Read a slice of content from the clipboard (or drop data).\nfunction parseFromClipboard(view, text, html, plainText, $context) {\n var dom, inCode = $context.parent.type.spec.code, slice;\n if (!html && !text) { return null }\n var asText = text && (plainText || inCode || !html);\n if (asText) {\n view.someProp(\"transformPastedText\", function (f) { text = f(text, inCode || plainText); });\n if (inCode) { return new Slice(Fragment.from(view.state.schema.text(text)), 0, 0) }\n var parsed = view.someProp(\"clipboardTextParser\", function (f) { return f(text, $context, plainText); });\n if (parsed) {\n slice = parsed;\n } else {\n dom = document.createElement(\"div\");\n text.trim().split(/(?:\\r\\n?|\\n)+/).forEach(function (block) {\n dom.appendChild(document.createElement(\"p\")).textContent = block;\n });\n }\n } else {\n view.someProp(\"transformPastedHTML\", function (f) { html = f(html); });\n dom = readHTML(html);\n }\n\n var contextNode = dom && dom.querySelector(\"[data-pm-slice]\");\n var sliceData = contextNode && /^(\\d+) (\\d+) (.*)/.exec(contextNode.getAttribute(\"data-pm-slice\"));\n if (!slice) {\n var parser = view.someProp(\"clipboardParser\") || view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n slice = parser.parseSlice(dom, {preserveWhitespace: !!(asText || sliceData), context: $context});\n }\n if (sliceData)\n { slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[3]); }\n else // HTML wasn't created by ProseMirror. Make sure top-level siblings are coherent\n { slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), false); }\n\n view.someProp(\"transformPasted\", function (f) { slice = f(slice); });\n return slice\n}\n\n// Takes a slice parsed with parseSlice, which means there hasn't been\n// any content-expression checking done on the top nodes, tries to\n// find a parent node in the current context that might fit the nodes,\n// and if successful, rebuilds the slice so that it fits into that parent.\n//\n// This addresses the problem that Transform.replace expects a\n// coherent slice, and will fail to place a set of siblings that don't\n// fit anywhere in the schema.\nfunction normalizeSiblings(fragment, $context) {\n if (fragment.childCount < 2) { return fragment }\n var loop = function ( d ) {\n var parent = $context.node(d);\n var match = parent.contentMatchAt($context.index(d));\n var lastWrap = (void 0), result = [];\n fragment.forEach(function (node) {\n if (!result) { return }\n var wrap = match.findWrapping(node.type), inLast;\n if (!wrap) { return result = null }\n if (inLast = result.length && lastWrap.length && addToSibling(wrap, lastWrap, node, result[result.length - 1], 0)) {\n result[result.length - 1] = inLast;\n } else {\n if (result.length) { result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length); }\n var wrapped = withWrappers(node, wrap);\n result.push(wrapped);\n match = match.matchType(wrapped.type, wrapped.attrs);\n lastWrap = wrap;\n }\n });\n if (result) { return { v: Fragment.from(result) } }\n };\n\n for (var d = $context.depth; d >= 0; d--) {\n var returned = loop( d );\n\n if ( returned ) return returned.v;\n }\n return fragment\n}\n\nfunction withWrappers(node, wrap, from) {\n if ( from === void 0 ) from = 0;\n\n for (var i = wrap.length - 1; i >= from; i--)\n { node = wrap[i].create(null, Fragment.from(node)); }\n return node\n}\n\n// Used to group adjacent nodes wrapped in similar parents by\n// normalizeSiblings into the same parent node\nfunction addToSibling(wrap, lastWrap, node, sibling, depth) {\n if (depth < wrap.length && depth < lastWrap.length && wrap[depth] == lastWrap[depth]) {\n var inner = addToSibling(wrap, lastWrap, node, sibling.lastChild, depth + 1);\n if (inner) { return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner)) }\n var match = sibling.contentMatchAt(sibling.childCount);\n if (match.matchType(depth == wrap.length - 1 ? node.type : wrap[depth + 1]))\n { return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap, depth + 1)))) }\n }\n}\n\nfunction closeRight(node, depth) {\n if (depth == 0) { return node }\n var fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1));\n var fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true);\n return node.copy(fragment.append(fill))\n}\n\nfunction closeRange(fragment, side, from, to, depth, openEnd) {\n var node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content;\n if (depth < to - 1) { inner = closeRange(inner, side, from, to, depth + 1, openEnd); }\n if (depth >= from)\n { inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, fragment.childCount > 1 || openEnd <= depth).append(inner)\n : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true)); }\n return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner))\n}\n\nfunction closeSlice(slice, openStart, openEnd) {\n if (openStart < slice.openStart)\n { slice = new Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd); }\n if (openEnd < slice.openEnd)\n { slice = new Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd); }\n return slice\n}\n\n// Trick from jQuery -- some elements must be wrapped in other\n// elements for innerHTML to work. I.e. if you do `div.innerHTML =\n// \"..\"` the table cells are ignored.\nvar wrapMap = {\n thead: [\"table\"],\n tbody: [\"table\"],\n tfoot: [\"table\"],\n caption: [\"table\"],\n colgroup: [\"table\"],\n col: [\"table\", \"colgroup\"],\n tr: [\"table\", \"tbody\"],\n td: [\"table\", \"tbody\", \"tr\"],\n th: [\"table\", \"tbody\", \"tr\"]\n};\n\nvar _detachedDoc = null;\nfunction detachedDoc() {\n return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument(\"title\"))\n}\n\nfunction readHTML(html) {\n var metas = /(\\s*]*>)*/.exec(html);\n if (metas) { html = html.slice(metas[0].length); }\n var elt = detachedDoc().createElement(\"div\");\n var firstTag = /(?:]*>)*<([a-z][^>\\s]+)/i.exec(html), wrap, depth = 0;\n if (wrap = firstTag && wrapMap[firstTag[1].toLowerCase()]) {\n html = wrap.map(function (n) { return \"<\" + n + \">\"; }).join(\"\") + html + wrap.map(function (n) { return \"\"; }).reverse().join(\"\");\n depth = wrap.length;\n }\n elt.innerHTML = html;\n for (var i = 0; i < depth; i++) { elt = elt.firstChild; }\n return elt\n}\n\nfunction addContext(slice, context) {\n if (!slice.size) { return slice }\n var schema = slice.content.firstChild.type.schema, array;\n try { array = JSON.parse(context); }\n catch(e) { return slice }\n var content = slice.content;\n var openStart = slice.openStart;\n var openEnd = slice.openEnd;\n for (var i = array.length - 2; i >= 0; i -= 2) {\n var type = schema.nodes[array[i]];\n if (!type || type.hasRequiredAttrs()) { break }\n content = Fragment.from(type.create(array[i + 1], content));\n openStart++; openEnd++;\n }\n return new Slice(content, openStart, openEnd)\n}\n\nvar observeOptions = {\n childList: true,\n characterData: true,\n characterDataOldValue: true,\n attributes: true,\n attributeOldValue: true,\n subtree: true\n};\n// IE11 has very broken mutation observers, so we also listen to DOMCharacterDataModified\nvar useCharData = result.ie && result.ie_version <= 11;\n\nvar SelectionState = function SelectionState() {\n this.anchorNode = this.anchorOffset = this.focusNode = this.focusOffset = null;\n};\n\nSelectionState.prototype.set = function set (sel) {\n this.anchorNode = sel.anchorNode; this.anchorOffset = sel.anchorOffset;\n this.focusNode = sel.focusNode; this.focusOffset = sel.focusOffset;\n};\n\nSelectionState.prototype.eq = function eq (sel) {\n return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset &&\n sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset\n};\n\nvar DOMObserver = function DOMObserver(view, handleDOMChange) {\n var this$1 = this;\n\n this.view = view;\n this.handleDOMChange = handleDOMChange;\n this.queue = [];\n this.flushingSoon = -1;\n this.observer = window.MutationObserver &&\n new window.MutationObserver(function (mutations) {\n for (var i = 0; i < mutations.length; i++) { this$1.queue.push(mutations[i]); }\n // IE11 will sometimes (on backspacing out a single character\n // text node after a BR node) call the observer callback\n // before actually updating the DOM, which will cause\n // ProseMirror to miss the change (see #930)\n if (result.ie && result.ie_version <= 11 && mutations.some(\n function (m) { return m.type == \"childList\" && m.removedNodes.length ||\n m.type == \"characterData\" && m.oldValue.length > m.target.nodeValue.length; }))\n { this$1.flushSoon(); }\n else\n { this$1.flush(); }\n });\n this.currentSelection = new SelectionState;\n if (useCharData) {\n this.onCharData = function (e) {\n this$1.queue.push({target: e.target, type: \"characterData\", oldValue: e.prevValue});\n this$1.flushSoon();\n };\n }\n this.onSelectionChange = this.onSelectionChange.bind(this);\n this.suppressingSelectionUpdates = false;\n};\n\nDOMObserver.prototype.flushSoon = function flushSoon () {\n var this$1 = this;\n\n if (this.flushingSoon < 0)\n { this.flushingSoon = window.setTimeout(function () { this$1.flushingSoon = -1; this$1.flush(); }, 20); }\n};\n\nDOMObserver.prototype.forceFlush = function forceFlush () {\n if (this.flushingSoon > -1) {\n window.clearTimeout(this.flushingSoon);\n this.flushingSoon = -1;\n this.flush();\n }\n};\n\nDOMObserver.prototype.start = function start () {\n if (this.observer)\n { this.observer.observe(this.view.dom, observeOptions); }\n if (useCharData)\n { this.view.dom.addEventListener(\"DOMCharacterDataModified\", this.onCharData); }\n this.connectSelection();\n};\n\nDOMObserver.prototype.stop = function stop () {\n var this$1 = this;\n\n if (this.observer) {\n var take = this.observer.takeRecords();\n if (take.length) {\n for (var i = 0; i < take.length; i++) { this.queue.push(take[i]); }\n window.setTimeout(function () { return this$1.flush(); }, 20);\n }\n this.observer.disconnect();\n }\n if (useCharData) { this.view.dom.removeEventListener(\"DOMCharacterDataModified\", this.onCharData); }\n this.disconnectSelection();\n};\n\nDOMObserver.prototype.connectSelection = function connectSelection () {\n this.view.dom.ownerDocument.addEventListener(\"selectionchange\", this.onSelectionChange);\n};\n\nDOMObserver.prototype.disconnectSelection = function disconnectSelection () {\n this.view.dom.ownerDocument.removeEventListener(\"selectionchange\", this.onSelectionChange);\n};\n\nDOMObserver.prototype.suppressSelectionUpdates = function suppressSelectionUpdates () {\n var this$1 = this;\n\n this.suppressingSelectionUpdates = true;\n setTimeout(function () { return this$1.suppressingSelectionUpdates = false; }, 50);\n};\n\nDOMObserver.prototype.onSelectionChange = function onSelectionChange () {\n if (!hasFocusAndSelection(this.view)) { return }\n if (this.suppressingSelectionUpdates) { return selectionToDOM(this.view) }\n // Deletions on IE11 fire their events in the wrong order, giving\n // us a selection change event before the DOM changes are\n // reported.\n if (result.ie && result.ie_version <= 11 && !this.view.state.selection.empty) {\n var sel = this.view.root.getSelection();\n // Selection.isCollapsed isn't reliable on IE\n if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))\n { return this.flushSoon() }\n }\n this.flush();\n};\n\nDOMObserver.prototype.setCurSelection = function setCurSelection () {\n this.currentSelection.set(this.view.root.getSelection());\n};\n\nDOMObserver.prototype.ignoreSelectionChange = function ignoreSelectionChange (sel) {\n if (sel.rangeCount == 0) { return true }\n var container = sel.getRangeAt(0).commonAncestorContainer;\n var desc = this.view.docView.nearestDesc(container);\n if (desc && desc.ignoreMutation({type: \"selection\", target: container.nodeType == 3 ? container.parentNode : container})) {\n this.setCurSelection();\n return true\n }\n};\n\nDOMObserver.prototype.flush = function flush () {\n if (!this.view.docView || this.flushingSoon > -1) { return }\n var mutations = this.observer ? this.observer.takeRecords() : [];\n if (this.queue.length) {\n mutations = this.queue.concat(mutations);\n this.queue.length = 0;\n }\n\n var sel = this.view.root.getSelection();\n var newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasSelection(this.view) && !this.ignoreSelectionChange(sel);\n\n var from = -1, to = -1, typeOver = false, added = [];\n if (this.view.editable) {\n for (var i = 0; i < mutations.length; i++) {\n var result$1 = this.registerMutation(mutations[i], added);\n if (result$1) {\n from = from < 0 ? result$1.from : Math.min(result$1.from, from);\n to = to < 0 ? result$1.to : Math.max(result$1.to, to);\n if (result$1.typeOver) { typeOver = true; }\n }\n }\n }\n\n if (result.gecko && added.length > 1) {\n var brs = added.filter(function (n) { return n.nodeName == \"BR\"; });\n if (brs.length == 2) {\n var a = brs[0];\n var b = brs[1];\n if (a.parentNode && a.parentNode.parentNode == b.parentNode) { b.remove(); }\n else { a.remove(); }\n }\n }\n\n if (from > -1 || newSel) {\n if (from > -1) {\n this.view.docView.markDirty(from, to);\n checkCSS(this.view);\n }\n this.handleDOMChange(from, to, typeOver, added);\n if (this.view.docView.dirty) { this.view.updateState(this.view.state); }\n else if (!this.currentSelection.eq(sel)) { selectionToDOM(this.view); }\n }\n};\n\nDOMObserver.prototype.registerMutation = function registerMutation (mut, added) {\n // Ignore mutations inside nodes that were already noted as inserted\n if (added.indexOf(mut.target) > -1) { return null }\n var desc = this.view.docView.nearestDesc(mut.target);\n if (mut.type == \"attributes\" &&\n (desc == this.view.docView || mut.attributeName == \"contenteditable\" ||\n // Firefox sometimes fires spurious events for null/empty styles\n (mut.attributeName == \"style\" && !mut.oldValue && !mut.target.getAttribute(\"style\"))))\n { return null }\n if (!desc || desc.ignoreMutation(mut)) { return null }\n\n if (mut.type == \"childList\") {\n var prev = mut.previousSibling, next = mut.nextSibling;\n if (result.ie && result.ie_version <= 11 && mut.addedNodes.length) {\n // IE11 gives us incorrect next/prev siblings for some\n // insertions, so if there are added nodes, recompute those\n for (var i = 0; i < mut.addedNodes.length; i++) {\n var ref = mut.addedNodes[i];\n var previousSibling = ref.previousSibling;\n var nextSibling = ref.nextSibling;\n if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0) { prev = previousSibling; }\n if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0) { next = nextSibling; }\n }\n }\n var fromOffset = prev && prev.parentNode == mut.target\n ? domIndex(prev) + 1 : 0;\n var from = desc.localPosFromDOM(mut.target, fromOffset, -1);\n var toOffset = next && next.parentNode == mut.target\n ? domIndex(next) : mut.target.childNodes.length;\n for (var i$1 = 0; i$1 < mut.addedNodes.length; i$1++) { added.push(mut.addedNodes[i$1]); }\n var to = desc.localPosFromDOM(mut.target, toOffset, 1);\n return {from: from, to: to}\n } else if (mut.type == \"attributes\") {\n return {from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border}\n } else { // \"characterData\"\n return {\n from: desc.posAtStart,\n to: desc.posAtEnd,\n // An event was generated for a text change that didn't change\n // any text. Mark the dom change to fall back to assuming the\n // selection was typed over with an identical value if it can't\n // find another change.\n typeOver: mut.target.nodeValue == mut.oldValue\n }\n }\n};\n\nvar cssChecked = false;\n\nfunction checkCSS(view) {\n if (cssChecked) { return }\n cssChecked = true;\n if (getComputedStyle(view.dom).whiteSpace == \"normal\")\n { console[\"warn\"](\"ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.\"); }\n}\n\n// A collection of DOM events that occur within the editor, and callback functions\n// to invoke when the event fires.\nvar handlers = {}, editHandlers = {};\n\nfunction initInput(view) {\n view.shiftKey = false;\n view.mouseDown = null;\n view.lastKeyCode = null;\n view.lastKeyCodeTime = 0;\n view.lastClick = {time: 0, x: 0, y: 0, type: \"\"};\n view.lastSelectionOrigin = null;\n view.lastSelectionTime = 0;\n\n view.lastIOSEnter = 0;\n view.lastIOSEnterFallbackTimeout = null;\n\n view.composing = false;\n view.composingTimeout = null;\n view.compositionNodes = [];\n view.compositionEndedAt = -2e8;\n\n view.domObserver = new DOMObserver(view, function (from, to, typeOver, added) { return readDOMChange(view, from, to, typeOver, added); });\n view.domObserver.start();\n // Used by hacks like the beforeinput handler to check whether anything happened in the DOM\n view.domChangeCount = 0;\n\n view.eventHandlers = Object.create(null);\n var loop = function ( event ) {\n var handler = handlers[event];\n view.dom.addEventListener(event, view.eventHandlers[event] = function (event) {\n if (eventBelongsToView(view, event) && !runCustomHandler(view, event) &&\n (view.editable || !(event.type in editHandlers)))\n { handler(view, event); }\n });\n };\n\n for (var event in handlers) loop( event );\n // On Safari, for reasons beyond my understanding, adding an input\n // event handler makes an issue where the composition vanishes when\n // you press enter go away.\n if (result.safari) { view.dom.addEventListener(\"input\", function () { return null; }); }\n\n ensureListeners(view);\n}\n\nfunction setSelectionOrigin(view, origin) {\n view.lastSelectionOrigin = origin;\n view.lastSelectionTime = Date.now();\n}\n\nfunction destroyInput(view) {\n view.domObserver.stop();\n for (var type in view.eventHandlers)\n { view.dom.removeEventListener(type, view.eventHandlers[type]); }\n clearTimeout(view.composingTimeout);\n clearTimeout(view.lastIOSEnterFallbackTimeout);\n}\n\nfunction ensureListeners(view) {\n view.someProp(\"handleDOMEvents\", function (currentHandlers) {\n for (var type in currentHandlers) { if (!view.eventHandlers[type])\n { view.dom.addEventListener(type, view.eventHandlers[type] = function (event) { return runCustomHandler(view, event); }); } }\n });\n}\n\nfunction runCustomHandler(view, event) {\n return view.someProp(\"handleDOMEvents\", function (handlers) {\n var handler = handlers[event.type];\n return handler ? handler(view, event) || event.defaultPrevented : false\n })\n}\n\nfunction eventBelongsToView(view, event) {\n if (!event.bubbles) { return true }\n if (event.defaultPrevented) { return false }\n for (var node = event.target; node != view.dom; node = node.parentNode)\n { if (!node || node.nodeType == 11 ||\n (node.pmViewDesc && node.pmViewDesc.stopEvent(event)))\n { return false } }\n return true\n}\n\nfunction dispatchEvent(view, event) {\n if (!runCustomHandler(view, event) && handlers[event.type] &&\n (view.editable || !(event.type in editHandlers)))\n { handlers[event.type](view, event); }\n}\n\neditHandlers.keydown = function (view, event) {\n view.shiftKey = event.keyCode == 16 || event.shiftKey;\n if (inOrNearComposition(view, event)) { return }\n view.domObserver.forceFlush();\n view.lastKeyCode = event.keyCode;\n view.lastKeyCodeTime = Date.now();\n // On iOS, if we preventDefault enter key presses, the virtual\n // keyboard gets confused. So the hack here is to set a flag that\n // makes the DOM change code recognize that what just happens should\n // be replaced by whatever the Enter key handlers do.\n if (result.ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {\n var now = Date.now();\n view.lastIOSEnter = now;\n view.lastIOSEnterFallbackTimeout = setTimeout(function () {\n if (view.lastIOSEnter == now) {\n view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(13, \"Enter\")); });\n view.lastIOSEnter = 0;\n }\n }, 200);\n } else if (view.someProp(\"handleKeyDown\", function (f) { return f(view, event); }) || captureKeyDown(view, event)) {\n event.preventDefault();\n } else {\n setSelectionOrigin(view, \"key\");\n }\n};\n\neditHandlers.keyup = function (view, e) {\n if (e.keyCode == 16) { view.shiftKey = false; }\n};\n\neditHandlers.keypress = function (view, event) {\n if (inOrNearComposition(view, event) || !event.charCode ||\n event.ctrlKey && !event.altKey || result.mac && event.metaKey) { return }\n\n if (view.someProp(\"handleKeyPress\", function (f) { return f(view, event); })) {\n event.preventDefault();\n return\n }\n\n var sel = view.state.selection;\n if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {\n var text = String.fromCharCode(event.charCode);\n if (!view.someProp(\"handleTextInput\", function (f) { return f(view, sel.$from.pos, sel.$to.pos, text); }))\n { view.dispatch(view.state.tr.insertText(text).scrollIntoView()); }\n event.preventDefault();\n }\n};\n\nfunction eventCoords(event) { return {left: event.clientX, top: event.clientY} }\n\nfunction isNear(event, click) {\n var dx = click.x - event.clientX, dy = click.y - event.clientY;\n return dx * dx + dy * dy < 100\n}\n\nfunction runHandlerOnContext(view, propName, pos, inside, event) {\n if (inside == -1) { return false }\n var $pos = view.state.doc.resolve(inside);\n var loop = function ( i ) {\n if (view.someProp(propName, function (f) { return i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true)\n : f(view, pos, $pos.node(i), $pos.before(i), event, false); }))\n { return { v: true } }\n };\n\n for (var i = $pos.depth + 1; i > 0; i--) {\n var returned = loop( i );\n\n if ( returned ) return returned.v;\n }\n return false\n}\n\nfunction updateSelection(view, selection, origin) {\n if (!view.focused) { view.focus(); }\n var tr = view.state.tr.setSelection(selection);\n if (origin == \"pointer\") { tr.setMeta(\"pointer\", true); }\n view.dispatch(tr);\n}\n\nfunction selectClickedLeaf(view, inside) {\n if (inside == -1) { return false }\n var $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter;\n if (node && node.isAtom && NodeSelection.isSelectable(node)) {\n updateSelection(view, new NodeSelection($pos), \"pointer\");\n return true\n }\n return false\n}\n\nfunction selectClickedNode(view, inside) {\n if (inside == -1) { return false }\n var sel = view.state.selection, selectedNode, selectAt;\n if (sel instanceof NodeSelection) { selectedNode = sel.node; }\n\n var $pos = view.state.doc.resolve(inside);\n for (var i = $pos.depth + 1; i > 0; i--) {\n var node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n if (NodeSelection.isSelectable(node)) {\n if (selectedNode && sel.$from.depth > 0 &&\n i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos)\n { selectAt = $pos.before(sel.$from.depth); }\n else\n { selectAt = $pos.before(i); }\n break\n }\n }\n\n if (selectAt != null) {\n updateSelection(view, NodeSelection.create(view.state.doc, selectAt), \"pointer\");\n return true\n } else {\n return false\n }\n}\n\nfunction handleSingleClick(view, pos, inside, event, selectNode) {\n return runHandlerOnContext(view, \"handleClickOn\", pos, inside, event) ||\n view.someProp(\"handleClick\", function (f) { return f(view, pos, event); }) ||\n (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside))\n}\n\nfunction handleDoubleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleDoubleClickOn\", pos, inside, event) ||\n view.someProp(\"handleDoubleClick\", function (f) { return f(view, pos, event); })\n}\n\nfunction handleTripleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleTripleClickOn\", pos, inside, event) ||\n view.someProp(\"handleTripleClick\", function (f) { return f(view, pos, event); }) ||\n defaultTripleClick(view, inside)\n}\n\nfunction defaultTripleClick(view, inside) {\n var doc = view.state.doc;\n if (inside == -1) {\n if (doc.inlineContent) {\n updateSelection(view, TextSelection.create(doc, 0, doc.content.size), \"pointer\");\n return true\n }\n return false\n }\n\n var $pos = doc.resolve(inside);\n for (var i = $pos.depth + 1; i > 0; i--) {\n var node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n var nodePos = $pos.before(i);\n if (node.inlineContent)\n { updateSelection(view, TextSelection.create(doc, nodePos + 1, nodePos + 1 + node.content.size), \"pointer\"); }\n else if (NodeSelection.isSelectable(node))\n { updateSelection(view, NodeSelection.create(doc, nodePos), \"pointer\"); }\n else\n { continue }\n return true\n }\n}\n\nfunction forceDOMFlush(view) {\n return endComposition(view)\n}\n\nvar selectNodeModifier = result.mac ? \"metaKey\" : \"ctrlKey\";\n\nhandlers.mousedown = function (view, event) {\n view.shiftKey = event.shiftKey;\n var flushed = forceDOMFlush(view);\n var now = Date.now(), type = \"singleClick\";\n if (now - view.lastClick.time < 500 && isNear(event, view.lastClick) && !event[selectNodeModifier]) {\n if (view.lastClick.type == \"singleClick\") { type = \"doubleClick\"; }\n else if (view.lastClick.type == \"doubleClick\") { type = \"tripleClick\"; }\n }\n view.lastClick = {time: now, x: event.clientX, y: event.clientY, type: type};\n\n var pos = view.posAtCoords(eventCoords(event));\n if (!pos) { return }\n\n if (type == \"singleClick\")\n { view.mouseDown = new MouseDown(view, pos, event, flushed); }\n else if ((type == \"doubleClick\" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event))\n { event.preventDefault(); }\n else\n { setSelectionOrigin(view, \"pointer\"); }\n};\n\nvar MouseDown = function MouseDown(view, pos, event, flushed) {\n var this$1 = this;\n\n this.view = view;\n this.startDoc = view.state.doc;\n this.pos = pos;\n this.event = event;\n this.flushed = flushed;\n this.selectNode = event[selectNodeModifier];\n this.allowDefault = event.shiftKey;\n\n var targetNode, targetPos;\n if (pos.inside > -1) {\n targetNode = view.state.doc.nodeAt(pos.inside);\n targetPos = pos.inside;\n } else {\n var $pos = view.state.doc.resolve(pos.pos);\n targetNode = $pos.parent;\n targetPos = $pos.depth ? $pos.before() : 0;\n }\n\n this.mightDrag = null;\n\n var target = flushed ? null : event.target;\n var targetDesc = target ? view.docView.nearestDesc(target, true) : null;\n this.target = targetDesc ? targetDesc.dom : null;\n\n if (targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false ||\n view.state.selection instanceof NodeSelection && targetPos == view.state.selection.from)\n { this.mightDrag = {node: targetNode,\n pos: targetPos,\n addAttr: this.target && !this.target.draggable,\n setUneditable: this.target && result.gecko && !this.target.hasAttribute(\"contentEditable\")}; }\n\n if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) {\n this.view.domObserver.stop();\n if (this.mightDrag.addAttr) { this.target.draggable = true; }\n if (this.mightDrag.setUneditable)\n { setTimeout(function () { return this$1.target.setAttribute(\"contentEditable\", \"false\"); }, 20); }\n this.view.domObserver.start();\n }\n\n view.root.addEventListener(\"mouseup\", this.up = this.up.bind(this));\n view.root.addEventListener(\"mousemove\", this.move = this.move.bind(this));\n setSelectionOrigin(view, \"pointer\");\n};\n\nMouseDown.prototype.done = function done () {\n this.view.root.removeEventListener(\"mouseup\", this.up);\n this.view.root.removeEventListener(\"mousemove\", this.move);\n if (this.mightDrag && this.target) {\n this.view.domObserver.stop();\n if (this.mightDrag.addAttr) { this.target.removeAttribute(\"draggable\"); }\n if (this.mightDrag.setUneditable) { this.target.removeAttribute(\"contentEditable\"); }\n this.view.domObserver.start();\n }\n this.view.mouseDown = null;\n};\n\nMouseDown.prototype.up = function up (event) {\n this.done();\n\n if (!this.view.dom.contains(event.target.nodeType == 3 ? event.target.parentNode : event.target))\n { return }\n\n var pos = this.pos;\n if (this.view.state.doc != this.startDoc) { pos = this.view.posAtCoords(eventCoords(event)); }\n\n if (this.allowDefault || !pos) {\n setSelectionOrigin(this.view, \"pointer\");\n } else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {\n event.preventDefault();\n } else if (this.flushed ||\n // Safari ignores clicks on draggable elements\n (result.safari && this.mightDrag && !this.mightDrag.node.isAtom) ||\n // Chrome will sometimes treat a node selection as a\n // cursor, but still report that the node is selected\n // when asked through getSelection. You'll then get a\n // situation where clicking at the point where that\n // (hidden) cursor is doesn't change the selection, and\n // thus doesn't get a reaction from ProseMirror. This\n // works around that.\n (result.chrome && !(this.view.state.selection instanceof TextSelection) &&\n (pos.pos == this.view.state.selection.from || pos.pos == this.view.state.selection.to))) {\n updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)), \"pointer\");\n event.preventDefault();\n } else {\n setSelectionOrigin(this.view, \"pointer\");\n }\n};\n\nMouseDown.prototype.move = function move (event) {\n if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 ||\n Math.abs(this.event.y - event.clientY) > 4))\n { this.allowDefault = true; }\n setSelectionOrigin(this.view, \"pointer\");\n};\n\nhandlers.touchdown = function (view) {\n forceDOMFlush(view);\n setSelectionOrigin(view, \"pointer\");\n};\n\nhandlers.contextmenu = function (view) { return forceDOMFlush(view); };\n\nfunction inOrNearComposition(view, event) {\n if (view.composing) { return true }\n // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.\n // On Japanese input method editors (IMEs), the Enter key is used to confirm character\n // selection. On Safari, when Enter is pressed, compositionend and keydown events are\n // emitted. The keydown event triggers newline insertion, which we don't want.\n // This method returns true if the keydown event should be ignored.\n // We only ignore it once, as pressing Enter a second time *should* insert a newline.\n // Furthermore, the keydown event timestamp must be close to the compositionEndedAt timestamp.\n // This guards against the case where compositionend is triggered without the keyboard\n // (e.g. character confirmation may be done with the mouse), and keydown is triggered\n // afterwards- we wouldn't want to ignore the keydown event in this case.\n if (result.safari && Math.abs(event.timeStamp - view.compositionEndedAt) < 500) {\n view.compositionEndedAt = -2e8;\n return true\n }\n return false\n}\n\n// Drop active composition after 5 seconds of inactivity on Android\nvar timeoutComposition = result.android ? 5000 : -1;\n\neditHandlers.compositionstart = editHandlers.compositionupdate = function (view) {\n if (!view.composing) {\n view.domObserver.flush();\n var state = view.state;\n var $pos = state.selection.$from;\n if (state.selection.empty &&\n (state.storedMarks || (!$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some(function (m) { return m.type.spec.inclusive === false; })))) {\n // Need to wrap the cursor in mark nodes different from the ones in the DOM context\n view.markCursor = view.state.storedMarks || $pos.marks();\n endComposition(view, true);\n view.markCursor = null;\n } else {\n endComposition(view);\n // In firefox, if the cursor is after but outside a marked node,\n // the inserted text won't inherit the marks. So this moves it\n // inside if necessary.\n if (result.gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {\n var sel = view.root.getSelection();\n for (var node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0;) {\n var before = offset < 0 ? node.lastChild : node.childNodes[offset - 1];\n if (!before) { break }\n if (before.nodeType == 3) {\n sel.collapse(before, before.nodeValue.length);\n break\n } else {\n node = before;\n offset = -1;\n }\n }\n }\n }\n view.composing = true;\n }\n scheduleComposeEnd(view, timeoutComposition);\n};\n\neditHandlers.compositionend = function (view, event) {\n if (view.composing) {\n view.composing = false;\n view.compositionEndedAt = event.timeStamp;\n scheduleComposeEnd(view, 20);\n }\n};\n\nfunction scheduleComposeEnd(view, delay) {\n clearTimeout(view.composingTimeout);\n if (delay > -1) { view.composingTimeout = setTimeout(function () { return endComposition(view); }, delay); }\n}\n\nfunction clearComposition(view) {\n view.composing = false;\n while (view.compositionNodes.length > 0) { view.compositionNodes.pop().markParentsDirty(); }\n}\n\nfunction endComposition(view, forceUpdate) {\n view.domObserver.forceFlush();\n clearComposition(view);\n if (forceUpdate || view.docView.dirty) {\n var sel = selectionFromDOM(view);\n if (sel && !sel.eq(view.state.selection)) { view.dispatch(view.state.tr.setSelection(sel)); }\n else { view.updateState(view.state); }\n return true\n }\n return false\n}\n\nfunction captureCopy(view, dom) {\n // The extra wrapper is somehow necessary on IE/Edge to prevent the\n // content from being mangled when it is put onto the clipboard\n if (!view.dom.parentNode) { return }\n var wrap = view.dom.parentNode.appendChild(document.createElement(\"div\"));\n wrap.appendChild(dom);\n wrap.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n var sel = getSelection(), range = document.createRange();\n range.selectNodeContents(dom);\n // Done because IE will fire a selectionchange moving the selection\n // to its start when removeAllRanges is called and the editor still\n // has focus (which will mess up the editor's selection state).\n view.dom.blur();\n sel.removeAllRanges();\n sel.addRange(range);\n setTimeout(function () {\n if (wrap.parentNode) { wrap.parentNode.removeChild(wrap); }\n view.focus();\n }, 50);\n}\n\n// This is very crude, but unfortunately both these browsers _pretend_\n// that they have a clipboard API—all the objects and methods are\n// there, they just don't work, and they are hard to test.\nvar brokenClipboardAPI = (result.ie && result.ie_version < 15) ||\n (result.ios && result.webkit_version < 604);\n\nhandlers.copy = editHandlers.cut = function (view, e) {\n var sel = view.state.selection, cut = e.type == \"cut\";\n if (sel.empty) { return }\n\n // IE and Edge's clipboard interface is completely broken\n var data = brokenClipboardAPI ? null : e.clipboardData;\n var slice = sel.content();\n var ref = serializeForClipboard(view, slice);\n var dom = ref.dom;\n var text = ref.text;\n if (data) {\n e.preventDefault();\n data.clearData();\n data.setData(\"text/html\", dom.innerHTML);\n data.setData(\"text/plain\", text);\n } else {\n captureCopy(view, dom);\n }\n if (cut) { view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta(\"uiEvent\", \"cut\")); }\n};\n\nfunction sliceSingleNode(slice) {\n return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null\n}\n\nfunction capturePaste(view, e) {\n if (!view.dom.parentNode) { return }\n var plainText = view.shiftKey || view.state.selection.$from.parent.type.spec.code;\n var target = view.dom.parentNode.appendChild(document.createElement(plainText ? \"textarea\" : \"div\"));\n if (!plainText) { target.contentEditable = \"true\"; }\n target.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n target.focus();\n setTimeout(function () {\n view.focus();\n if (target.parentNode) { target.parentNode.removeChild(target); }\n if (plainText) { doPaste(view, target.value, null, e); }\n else { doPaste(view, target.textContent, target.innerHTML, e); }\n }, 50);\n}\n\nfunction doPaste(view, text, html, e) {\n var slice = parseFromClipboard(view, text, html, view.shiftKey, view.state.selection.$from);\n if (view.someProp(\"handlePaste\", function (f) { return f(view, e, slice || Slice.empty); }) || !slice) { return }\n\n var singleNode = sliceSingleNode(slice);\n var tr = singleNode ? view.state.tr.replaceSelectionWith(singleNode, view.shiftKey) : view.state.tr.replaceSelection(slice);\n view.dispatch(tr.scrollIntoView().setMeta(\"paste\", true).setMeta(\"uiEvent\", \"paste\"));\n}\n\neditHandlers.paste = function (view, e) {\n var data = brokenClipboardAPI ? null : e.clipboardData;\n var html = data && data.getData(\"text/html\"), text = data && data.getData(\"text/plain\");\n if (data && (html || text || data.files.length)) {\n doPaste(view, text, html, e);\n e.preventDefault();\n } else {\n capturePaste(view, e);\n }\n};\n\nvar Dragging = function Dragging(slice, move) {\n this.slice = slice;\n this.move = move;\n};\n\nvar dragCopyModifier = result.mac ? \"altKey\" : \"ctrlKey\";\n\nhandlers.dragstart = function (view, e) {\n var mouseDown = view.mouseDown;\n if (mouseDown) { mouseDown.done(); }\n if (!e.dataTransfer) { return }\n\n var sel = view.state.selection;\n var pos = sel.empty ? null : view.posAtCoords(eventCoords(e));\n if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1: sel.to)) ; else if (mouseDown && mouseDown.mightDrag) {\n view.dispatch(view.state.tr.setSelection(NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos)));\n } else if (e.target && e.target.nodeType == 1) {\n var desc = view.docView.nearestDesc(e.target, true);\n if (!desc || !desc.node.type.spec.draggable || desc == view.docView) { return }\n view.dispatch(view.state.tr.setSelection(NodeSelection.create(view.state.doc, desc.posBefore)));\n }\n var slice = view.state.selection.content();\n var ref = serializeForClipboard(view, slice);\n var dom = ref.dom;\n var text = ref.text;\n e.dataTransfer.clearData();\n e.dataTransfer.setData(brokenClipboardAPI ? \"Text\" : \"text/html\", dom.innerHTML);\n if (!brokenClipboardAPI) { e.dataTransfer.setData(\"text/plain\", text); }\n view.dragging = new Dragging(slice, !e[dragCopyModifier]);\n};\n\nhandlers.dragend = function (view) {\n var dragging = view.dragging;\n window.setTimeout(function () {\n if (view.dragging == dragging) { view.dragging = null; }\n }, 50);\n};\n\neditHandlers.dragover = editHandlers.dragenter = function (_, e) { return e.preventDefault(); };\n\neditHandlers.drop = function (view, e) {\n var dragging = view.dragging;\n view.dragging = null;\n\n if (!e.dataTransfer) { return }\n\n var eventPos = view.posAtCoords(eventCoords(e));\n if (!eventPos) { return }\n var $mouse = view.state.doc.resolve(eventPos.pos);\n if (!$mouse) { return }\n var slice = dragging && dragging.slice ||\n parseFromClipboard(view, e.dataTransfer.getData(brokenClipboardAPI ? \"Text\" : \"text/plain\"),\n brokenClipboardAPI ? null : e.dataTransfer.getData(\"text/html\"), false, $mouse);\n var move = dragging && !e[dragCopyModifier];\n if (view.someProp(\"handleDrop\", function (f) { return f(view, e, slice || Slice.empty, move); })) {\n e.preventDefault();\n return\n }\n if (!slice) { return }\n\n e.preventDefault();\n var insertPos = slice ? dropPoint(view.state.doc, $mouse.pos, slice) : $mouse.pos;\n if (insertPos == null) { insertPos = $mouse.pos; }\n\n var tr = view.state.tr;\n if (move) { tr.deleteSelection(); }\n\n var pos = tr.mapping.map(insertPos);\n var isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1;\n var beforeInsert = tr.doc;\n if (isNode)\n { tr.replaceRangeWith(pos, pos, slice.content.firstChild); }\n else\n { tr.replaceRange(pos, pos, slice); }\n if (tr.doc.eq(beforeInsert)) { return }\n\n var $pos = tr.doc.resolve(pos);\n if (isNode && NodeSelection.isSelectable(slice.content.firstChild) &&\n $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice.content.firstChild)) {\n tr.setSelection(new NodeSelection($pos));\n } else {\n var end = tr.mapping.map(insertPos);\n tr.mapping.maps[tr.mapping.maps.length - 1].forEach(function (_from, _to, _newFrom, newTo) { return end = newTo; });\n tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(end)));\n }\n view.focus();\n view.dispatch(tr.setMeta(\"uiEvent\", \"drop\"));\n};\n\nhandlers.focus = function (view) {\n if (!view.focused) {\n view.domObserver.stop();\n view.dom.classList.add(\"ProseMirror-focused\");\n view.domObserver.start();\n view.focused = true;\n setTimeout(function () {\n if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.root.getSelection()))\n { selectionToDOM(view); }\n }, 20);\n }\n};\n\nhandlers.blur = function (view) {\n if (view.focused) {\n view.domObserver.stop();\n view.dom.classList.remove(\"ProseMirror-focused\");\n view.domObserver.start();\n view.domObserver.currentSelection.set({});\n view.focused = false;\n }\n};\n\nhandlers.beforeinput = function (view, event) {\n // We should probably do more with beforeinput events, but support\n // is so spotty that I'm still waiting to see where they are going.\n\n // Very specific hack to deal with backspace sometimes failing on\n // Chrome Android when after an uneditable node.\n if (result.chrome && result.android && event.inputType == \"deleteContentBackward\") {\n var domChangeCount = view.domChangeCount;\n setTimeout(function () {\n if (view.domChangeCount != domChangeCount) { return } // Event already had some effect\n // This bug tends to close the virtual keyboard, so we refocus\n view.dom.blur();\n view.focus();\n if (view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(8, \"Backspace\")); })) { return }\n var ref = view.state.selection;\n var $cursor = ref.$cursor;\n // Crude approximation of backspace behavior when no command handled it\n if ($cursor && $cursor.pos > 0) { view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView()); }\n }, 50);\n }\n};\n\n// Make sure all handlers get registered\nfor (var prop in editHandlers) { handlers[prop] = editHandlers[prop]; }\n\nfunction compareObjs(a, b) {\n if (a == b) { return true }\n for (var p in a) { if (a[p] !== b[p]) { return false } }\n for (var p$1 in b) { if (!(p$1 in a)) { return false } }\n return true\n}\n\nvar WidgetType = function WidgetType(toDOM, spec) {\n this.spec = spec || noSpec;\n this.side = this.spec.side || 0;\n this.toDOM = toDOM;\n};\n\nWidgetType.prototype.map = function map (mapping, span, offset, oldOffset) {\n var ref = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);\n var pos = ref.pos;\n var deleted = ref.deleted;\n return deleted ? null : new Decoration(pos - offset, pos - offset, this)\n};\n\nWidgetType.prototype.valid = function valid () { return true };\n\nWidgetType.prototype.eq = function eq (other) {\n return this == other ||\n (other instanceof WidgetType &&\n (this.spec.key && this.spec.key == other.spec.key ||\n this.toDOM == other.toDOM && compareObjs(this.spec, other.spec)))\n};\n\nvar InlineType = function InlineType(attrs, spec) {\n this.spec = spec || noSpec;\n this.attrs = attrs;\n};\n\nInlineType.prototype.map = function map (mapping, span, offset, oldOffset) {\n var from = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;\n var to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;\n return from >= to ? null : new Decoration(from, to, this)\n};\n\nInlineType.prototype.valid = function valid (_, span) { return span.from < span.to };\n\nInlineType.prototype.eq = function eq (other) {\n return this == other ||\n (other instanceof InlineType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec))\n};\n\nInlineType.is = function is (span) { return span.type instanceof InlineType };\n\nvar NodeType = function NodeType(attrs, spec) {\n this.spec = spec || noSpec;\n this.attrs = attrs;\n};\n\nNodeType.prototype.map = function map (mapping, span, offset, oldOffset) {\n var from = mapping.mapResult(span.from + oldOffset, 1);\n if (from.deleted) { return null }\n var to = mapping.mapResult(span.to + oldOffset, -1);\n if (to.deleted || to.pos <= from.pos) { return null }\n return new Decoration(from.pos - offset, to.pos - offset, this)\n};\n\nNodeType.prototype.valid = function valid (node, span) {\n var ref = node.content.findIndex(span.from);\n var index = ref.index;\n var offset = ref.offset;\n return offset == span.from && offset + node.child(index).nodeSize == span.to\n};\n\nNodeType.prototype.eq = function eq (other) {\n return this == other ||\n (other instanceof NodeType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec))\n};\n\n// ::- Decoration objects can be provided to the view through the\n// [`decorations` prop](#view.EditorProps.decorations). They come in\n// several variants—see the static members of this class for details.\nvar Decoration = function Decoration(from, to, type) {\n // :: number\n // The start position of the decoration.\n this.from = from;\n // :: number\n // The end position. Will be the same as `from` for [widget\n // decorations](#view.Decoration^widget).\n this.to = to;\n this.type = type;\n};\n\nvar prototypeAccessors$1 = { spec: { configurable: true },inline: { configurable: true } };\n\nDecoration.prototype.copy = function copy (from, to) {\n return new Decoration(from, to, this.type)\n};\n\nDecoration.prototype.eq = function eq (other, offset) {\n if ( offset === void 0 ) offset = 0;\n\n return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to\n};\n\nDecoration.prototype.map = function map (mapping, offset, oldOffset) {\n return this.type.map(mapping, this, offset, oldOffset)\n};\n\n// :: (number, union<(view: EditorView, getPos: () → number) → dom.Node, dom.Node>, ?Object) → Decoration\n// Creates a widget decoration, which is a DOM node that's shown in\n// the document at the given position. It is recommended that you\n// delay rendering the widget by passing a function that will be\n// called when the widget is actually drawn in a view, but you can\n// also directly pass a DOM node. `getPos` can be used to find the\n// widget's current document position.\n//\n// spec::- These options are supported:\n//\n// side:: ?number\n// Controls which side of the document position this widget is\n// associated with. When negative, it is drawn before a cursor\n// at its position, and content inserted at that position ends\n// up after the widget. When zero (the default) or positive, the\n// widget is drawn after the cursor and content inserted there\n// ends up before the widget.\n//\n// When there are multiple widgets at a given position, their\n// `side` values determine the order in which they appear. Those\n// with lower values appear first. The ordering of widgets with\n// the same `side` value is unspecified.\n//\n// When `marks` is null, `side` also determines the marks that\n// the widget is wrapped in—those of the node before when\n// negative, those of the node after when positive.\n//\n// marks:: ?[Mark]\n// The precise set of marks to draw around the widget.\n//\n// stopEvent:: ?(event: dom.Event) → bool\n// Can be used to control which DOM events, when they bubble out\n// of this widget, the editor view should ignore.\n//\n// ignoreSelection:: ?bool\n// When set (defaults to false), selection changes inside the\n// widget are ignored, and don't cause ProseMirror to try and\n// re-sync the selection with its selection state.\n//\n// key:: ?string\n// When comparing decorations of this type (in order to decide\n// whether it needs to be redrawn), ProseMirror will by default\n// compare the widget DOM node by identity. If you pass a key,\n// that key will be compared instead, which can be useful when\n// you generate decorations on the fly and don't want to store\n// and reuse DOM nodes. Make sure that any widgets with the same\n// key are interchangeable—if widgets differ in, for example,\n// the behavior of some event handler, they should get\n// different keys.\nDecoration.widget = function widget (pos, toDOM, spec) {\n return new Decoration(pos, pos, new WidgetType(toDOM, spec))\n};\n\n// :: (number, number, DecorationAttrs, ?Object) → Decoration\n// Creates an inline decoration, which adds the given attributes to\n// each inline node between `from` and `to`.\n//\n// spec::- These options are recognized:\n//\n// inclusiveStart:: ?bool\n// Determines how the left side of the decoration is\n// [mapped](#transform.Position_Mapping) when content is\n// inserted directly at that position. By default, the decoration\n// won't include the new content, but you can set this to `true`\n// to make it inclusive.\n//\n// inclusiveEnd:: ?bool\n// Determines how the right side of the decoration is mapped.\n// See\n// [`inclusiveStart`](#view.Decoration^inline^spec.inclusiveStart).\nDecoration.inline = function inline (from, to, attrs, spec) {\n return new Decoration(from, to, new InlineType(attrs, spec))\n};\n\n// :: (number, number, DecorationAttrs, ?Object) → Decoration\n// Creates a node decoration. `from` and `to` should point precisely\n// before and after a node in the document. That node, and only that\n// node, will receive the given attributes.\n//\n// spec::-\n//\n// Optional information to store with the decoration. It\n// is also used when comparing decorators for equality.\nDecoration.node = function node (from, to, attrs, spec) {\n return new Decoration(from, to, new NodeType(attrs, spec))\n};\n\n// :: Object\n// The spec provided when creating this decoration. Can be useful\n// if you've stored extra information in that object.\nprototypeAccessors$1.spec.get = function () { return this.type.spec };\n\nprototypeAccessors$1.inline.get = function () { return this.type instanceof InlineType };\n\nObject.defineProperties( Decoration.prototype, prototypeAccessors$1 );\n\n// DecorationAttrs:: interface\n// A set of attributes to add to a decorated node. Most properties\n// simply directly correspond to DOM attributes of the same name,\n// which will be set to the property's value. These are exceptions:\n//\n// class:: ?string\n// A CSS class name or a space-separated set of class names to be\n// _added_ to the classes that the node already had.\n//\n// style:: ?string\n// A string of CSS to be _added_ to the node's existing `style` property.\n//\n// nodeName:: ?string\n// When non-null, the target node is wrapped in a DOM element of\n// this type (and the other attributes are applied to this element).\n\nvar none = [], noSpec = {};\n\n// ::- A collection of [decorations](#view.Decoration), organized in\n// such a way that the drawing algorithm can efficiently use and\n// compare them. This is a persistent data structure—it is not\n// modified, updates create a new value.\nvar DecorationSet = function DecorationSet(local, children) {\n this.local = local && local.length ? local : none;\n this.children = children && children.length ? children : none;\n};\n\n// :: (Node, [Decoration]) → DecorationSet\n// Create a set of decorations, using the structure of the given\n// document.\nDecorationSet.create = function create (doc, decorations) {\n return decorations.length ? buildTree(decorations, doc, 0, noSpec) : empty\n};\n\n// :: (?number, ?number, ?(spec: Object) → bool) → [Decoration]\n// Find all decorations in this set which touch the given range\n// (including decorations that start or end directly at the\n// boundaries) and match the given predicate on their spec. When\n// `start` and `end` are omitted, all decorations in the set are\n// considered. When `predicate` isn't given, all decorations are\n// assumed to match.\nDecorationSet.prototype.find = function find (start, end, predicate) {\n var result = [];\n this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate);\n return result\n};\n\nDecorationSet.prototype.findInner = function findInner (start, end, result, offset, predicate) {\n for (var i = 0; i < this.local.length; i++) {\n var span = this.local[i];\n if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec)))\n { result.push(span.copy(span.from + offset, span.to + offset)); }\n }\n for (var i$1 = 0; i$1 < this.children.length; i$1 += 3) {\n if (this.children[i$1] < end && this.children[i$1 + 1] > start) {\n var childOff = this.children[i$1] + 1;\n this.children[i$1 + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate);\n }\n }\n};\n\n// :: (Mapping, Node, ?Object) → DecorationSet\n// Map the set of decorations in response to a change in the\n// document.\n//\n// options::- An optional set of options.\n//\n// onRemove:: ?(decorationSpec: Object)\n// When given, this function will be called for each decoration\n// that gets dropped as a result of the mapping, passing the\n// spec of that decoration.\nDecorationSet.prototype.map = function map (mapping, doc, options) {\n if (this == empty || mapping.maps.length == 0) { return this }\n return this.mapInner(mapping, doc, 0, 0, options || noSpec)\n};\n\nDecorationSet.prototype.mapInner = function mapInner (mapping, node, offset, oldOffset, options) {\n var newLocal;\n for (var i = 0; i < this.local.length; i++) {\n var mapped = this.local[i].map(mapping, offset, oldOffset);\n if (mapped && mapped.type.valid(node, mapped)) { (newLocal || (newLocal = [])).push(mapped); }\n else if (options.onRemove) { options.onRemove(this.local[i].spec); }\n }\n\n if (this.children.length)\n { return mapChildren(this.children, newLocal, mapping, node, offset, oldOffset, options) }\n else\n { return newLocal ? new DecorationSet(newLocal.sort(byPos)) : empty }\n};\n\n// :: (Node, [Decoration]) → DecorationSet\n// Add the given array of decorations to the ones in the set,\n// producing a new set. Needs access to the current document to\n// create the appropriate tree structure.\nDecorationSet.prototype.add = function add (doc, decorations) {\n if (!decorations.length) { return this }\n if (this == empty) { return DecorationSet.create(doc, decorations) }\n return this.addInner(doc, decorations, 0)\n};\n\nDecorationSet.prototype.addInner = function addInner (doc, decorations, offset) {\n var this$1 = this;\n\n var children, childIndex = 0;\n doc.forEach(function (childNode, childOffset) {\n var baseOffset = childOffset + offset, found;\n if (!(found = takeSpansForNode(decorations, childNode, baseOffset))) { return }\n\n if (!children) { children = this$1.children.slice(); }\n while (childIndex < children.length && children[childIndex] < childOffset) { childIndex += 3; }\n if (children[childIndex] == childOffset)\n { children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found, baseOffset + 1); }\n else\n { children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found, childNode, baseOffset + 1, noSpec)); }\n childIndex += 3;\n });\n\n var local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset);\n return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local,\n children || this.children)\n};\n\n// :: ([Decoration]) → DecorationSet\n// Create a new set that contains the decorations in this set, minus\n// the ones in the given array.\nDecorationSet.prototype.remove = function remove (decorations) {\n if (decorations.length == 0 || this == empty) { return this }\n return this.removeInner(decorations, 0)\n};\n\nDecorationSet.prototype.removeInner = function removeInner (decorations, offset) {\n var children = this.children, local = this.local;\n for (var i = 0; i < children.length; i += 3) {\n var found = (void 0), from = children[i] + offset, to = children[i + 1] + offset;\n for (var j = 0, span = (void 0); j < decorations.length; j++) { if (span = decorations[j]) {\n if (span.from > from && span.to < to) {\n decorations[j] = null\n ;(found || (found = [])).push(span);\n }\n } }\n if (!found) { continue }\n if (children == this.children) { children = this.children.slice(); }\n var removed = children[i + 2].removeInner(found, from + 1);\n if (removed != empty) {\n children[i + 2] = removed;\n } else {\n children.splice(i, 3);\n i -= 3;\n }\n }\n if (local.length) { for (var i$1 = 0, span$1 = (void 0); i$1 < decorations.length; i$1++) { if (span$1 = decorations[i$1]) {\n for (var j$1 = 0; j$1 < local.length; j$1++) { if (local[j$1].eq(span$1, offset)) {\n if (local == this.local) { local = this.local.slice(); }\n local.splice(j$1--, 1);\n } }\n } } }\n if (children == this.children && local == this.local) { return this }\n return local.length || children.length ? new DecorationSet(local, children) : empty\n};\n\nDecorationSet.prototype.forChild = function forChild (offset, node) {\n if (this == empty) { return this }\n if (node.isLeaf) { return DecorationSet.empty }\n\n var child, local;\n for (var i = 0; i < this.children.length; i += 3) { if (this.children[i] >= offset) {\n if (this.children[i] == offset) { child = this.children[i + 2]; }\n break\n } }\n var start = offset + 1, end = start + node.content.size;\n for (var i$1 = 0; i$1 < this.local.length; i$1++) {\n var dec = this.local[i$1];\n if (dec.from < end && dec.to > start && (dec.type instanceof InlineType)) {\n var from = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start;\n if (from < to) { (local || (local = [])).push(dec.copy(from, to)); }\n }\n }\n if (local) {\n var localSet = new DecorationSet(local.sort(byPos));\n return child ? new DecorationGroup([localSet, child]) : localSet\n }\n return child || empty\n};\n\nDecorationSet.prototype.eq = function eq (other) {\n if (this == other) { return true }\n if (!(other instanceof DecorationSet) ||\n this.local.length != other.local.length ||\n this.children.length != other.children.length) { return false }\n for (var i = 0; i < this.local.length; i++)\n { if (!this.local[i].eq(other.local[i])) { return false } }\n for (var i$1 = 0; i$1 < this.children.length; i$1 += 3)\n { if (this.children[i$1] != other.children[i$1] ||\n this.children[i$1 + 1] != other.children[i$1 + 1] ||\n !this.children[i$1 + 2].eq(other.children[i$1 + 2])) { return false } }\n return true\n};\n\nDecorationSet.prototype.locals = function locals (node) {\n return removeOverlap(this.localsInner(node))\n};\n\nDecorationSet.prototype.localsInner = function localsInner (node) {\n if (this == empty) { return none }\n if (node.inlineContent || !this.local.some(InlineType.is)) { return this.local }\n var result = [];\n for (var i = 0; i < this.local.length; i++) {\n if (!(this.local[i].type instanceof InlineType))\n { result.push(this.local[i]); }\n }\n return result\n};\n\nvar empty = new DecorationSet();\n\n// :: DecorationSet\n// The empty set of decorations.\nDecorationSet.empty = empty;\n\nDecorationSet.removeOverlap = removeOverlap;\n\n// :- An abstraction that allows the code dealing with decorations to\n// treat multiple DecorationSet objects as if it were a single object\n// with (a subset of) the same interface.\nvar DecorationGroup = function DecorationGroup(members) {\n this.members = members;\n};\n\nDecorationGroup.prototype.forChild = function forChild (offset, child) {\n if (child.isLeaf) { return DecorationSet.empty }\n var found = [];\n for (var i = 0; i < this.members.length; i++) {\n var result = this.members[i].forChild(offset, child);\n if (result == empty) { continue }\n if (result instanceof DecorationGroup) { found = found.concat(result.members); }\n else { found.push(result); }\n }\n return DecorationGroup.from(found)\n};\n\nDecorationGroup.prototype.eq = function eq (other) {\n if (!(other instanceof DecorationGroup) ||\n other.members.length != this.members.length) { return false }\n for (var i = 0; i < this.members.length; i++)\n { if (!this.members[i].eq(other.members[i])) { return false } }\n return true\n};\n\nDecorationGroup.prototype.locals = function locals (node) {\n var result, sorted = true;\n for (var i = 0; i < this.members.length; i++) {\n var locals = this.members[i].localsInner(node);\n if (!locals.length) { continue }\n if (!result) {\n result = locals;\n } else {\n if (sorted) {\n result = result.slice();\n sorted = false;\n }\n for (var j = 0; j < locals.length; j++) { result.push(locals[j]); }\n }\n }\n return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none\n};\n\n// : ([DecorationSet]) → union\n// Create a group for the given array of decoration sets, or return\n// a single set when possible.\nDecorationGroup.from = function from (members) {\n switch (members.length) {\n case 0: return empty\n case 1: return members[0]\n default: return new DecorationGroup(members)\n }\n};\n\nfunction mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) {\n var children = oldChildren.slice();\n\n // Mark the children that are directly touched by changes, and\n // move those that are after the changes.\n var shift = function (oldStart, oldEnd, newStart, newEnd) {\n for (var i = 0; i < children.length; i += 3) {\n var end = children[i + 1], dSize = (void 0);\n if (end == -1 || oldStart > end + oldOffset) { continue }\n if (oldEnd >= children[i] + oldOffset) {\n children[i + 1] = -1;\n } else if (newStart >= offset && (dSize = (newEnd - newStart) - (oldEnd - oldStart))) {\n children[i] += dSize;\n children[i + 1] += dSize;\n }\n }\n };\n for (var i = 0; i < mapping.maps.length; i++) { mapping.maps[i].forEach(shift); }\n\n // Find the child nodes that still correspond to a single node,\n // recursively call mapInner on them and update their positions.\n var mustRebuild = false;\n for (var i$1 = 0; i$1 < children.length; i$1 += 3) { if (children[i$1 + 1] == -1) { // Touched nodes\n var from = mapping.map(oldChildren[i$1] + oldOffset), fromLocal = from - offset;\n if (fromLocal < 0 || fromLocal >= node.content.size) {\n mustRebuild = true;\n continue\n }\n // Must read oldChildren because children was tagged with -1\n var to = mapping.map(oldChildren[i$1 + 1] + oldOffset, -1), toLocal = to - offset;\n var ref = node.content.findIndex(fromLocal);\n var index = ref.index;\n var childOffset = ref.offset;\n var childNode = node.maybeChild(index);\n if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {\n var mapped = children[i$1 + 2].mapInner(mapping, childNode, from + 1, oldChildren[i$1] + oldOffset + 1, options);\n if (mapped != empty) {\n children[i$1] = fromLocal;\n children[i$1 + 1] = toLocal;\n children[i$1 + 2] = mapped;\n } else {\n children[i$1 + 1] = -2;\n mustRebuild = true;\n }\n } else {\n mustRebuild = true;\n }\n } }\n\n // Remaining children must be collected and rebuilt into the appropriate structure\n if (mustRebuild) {\n var decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal || [], mapping,\n offset, oldOffset, options);\n var built = buildTree(decorations, node, 0, options);\n newLocal = built.local;\n for (var i$2 = 0; i$2 < children.length; i$2 += 3) { if (children[i$2 + 1] < 0) {\n children.splice(i$2, 3);\n i$2 -= 3;\n } }\n for (var i$3 = 0, j = 0; i$3 < built.children.length; i$3 += 3) {\n var from$1 = built.children[i$3];\n while (j < children.length && children[j] < from$1) { j += 3; }\n children.splice(j, 0, built.children[i$3], built.children[i$3 + 1], built.children[i$3 + 2]);\n }\n }\n\n return new DecorationSet(newLocal && newLocal.sort(byPos), children)\n}\n\nfunction moveSpans(spans, offset) {\n if (!offset || !spans.length) { return spans }\n var result = [];\n for (var i = 0; i < spans.length; i++) {\n var span = spans[i];\n result.push(new Decoration(span.from + offset, span.to + offset, span.type));\n }\n return result\n}\n\nfunction mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) {\n // Gather all decorations from the remaining marked children\n function gather(set, oldOffset) {\n for (var i = 0; i < set.local.length; i++) {\n var mapped = set.local[i].map(mapping, offset, oldOffset);\n if (mapped) { decorations.push(mapped); }\n else if (options.onRemove) { options.onRemove(set.local[i].spec); }\n }\n for (var i$1 = 0; i$1 < set.children.length; i$1 += 3)\n { gather(set.children[i$1 + 2], set.children[i$1] + oldOffset + 1); }\n }\n for (var i = 0; i < children.length; i += 3) { if (children[i + 1] == -1)\n { gather(children[i + 2], oldChildren[i] + oldOffset + 1); } }\n\n return decorations\n}\n\nfunction takeSpansForNode(spans, node, offset) {\n if (node.isLeaf) { return null }\n var end = offset + node.nodeSize, found = null;\n for (var i = 0, span = (void 0); i < spans.length; i++) {\n if ((span = spans[i]) && span.from > offset && span.to < end) {\n(found || (found = [])).push(span);\n spans[i] = null;\n }\n }\n return found\n}\n\nfunction withoutNulls(array) {\n var result = [];\n for (var i = 0; i < array.length; i++)\n { if (array[i] != null) { result.push(array[i]); } }\n return result\n}\n\n// : ([Decoration], Node, number) → DecorationSet\n// Build up a tree that corresponds to a set of decorations. `offset`\n// is a base offset that should be subtractet from the `from` and `to`\n// positions in the spans (so that we don't have to allocate new spans\n// for recursive calls).\nfunction buildTree(spans, node, offset, options) {\n var children = [], hasNulls = false;\n node.forEach(function (childNode, localStart) {\n var found = takeSpansForNode(spans, childNode, localStart + offset);\n if (found) {\n hasNulls = true;\n var subtree = buildTree(found, childNode, offset + localStart + 1, options);\n if (subtree != empty)\n { children.push(localStart, localStart + childNode.nodeSize, subtree); }\n }\n });\n var locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);\n for (var i = 0; i < locals.length; i++) { if (!locals[i].type.valid(node, locals[i])) {\n if (options.onRemove) { options.onRemove(locals[i].spec); }\n locals.splice(i--, 1);\n } }\n return locals.length || children.length ? new DecorationSet(locals, children) : empty\n}\n\n// : (Decoration, Decoration) → number\n// Used to sort decorations so that ones with a low start position\n// come first, and within a set with the same start position, those\n// with an smaller end position come first.\nfunction byPos(a, b) {\n return a.from - b.from || a.to - b.to\n}\n\n// : ([Decoration]) → [Decoration]\n// Scan a sorted array of decorations for partially overlapping spans,\n// and split those so that only fully overlapping spans are left (to\n// make subsequent rendering easier). Will return the input array if\n// no partially overlapping spans are found (the common case).\nfunction removeOverlap(spans) {\n var working = spans;\n for (var i = 0; i < working.length - 1; i++) {\n var span = working[i];\n if (span.from != span.to) { for (var j = i + 1; j < working.length; j++) {\n var next = working[j];\n if (next.from == span.from) {\n if (next.to != span.to) {\n if (working == spans) { working = spans.slice(); }\n // Followed by a partially overlapping larger span. Split that\n // span.\n working[j] = next.copy(next.from, span.to);\n insertAhead(working, j + 1, next.copy(span.to, next.to));\n }\n continue\n } else {\n if (next.from < span.to) {\n if (working == spans) { working = spans.slice(); }\n // The end of this one overlaps with a subsequent span. Split\n // this one.\n working[i] = span.copy(span.from, next.from);\n insertAhead(working, j, span.copy(next.from, span.to));\n }\n break\n }\n } }\n }\n return working\n}\n\nfunction insertAhead(array, i, deco) {\n while (i < array.length && byPos(deco, array[i]) > 0) { i++; }\n array.splice(i, 0, deco);\n}\n\n// : (EditorView) → union\n// Get the decorations associated with the current props of a view.\nfunction viewDecorations(view) {\n var found = [];\n view.someProp(\"decorations\", function (f) {\n var result = f(view.state);\n if (result && result != empty) { found.push(result); }\n });\n if (view.cursorWrapper)\n { found.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco])); }\n return DecorationGroup.from(found)\n}\n\n// ::- An editor view manages the DOM structure that represents an\n// editable document. Its state and behavior are determined by its\n// [props](#view.DirectEditorProps).\nvar EditorView = function EditorView(place, props) {\n this._props = props;\n // :: EditorState\n // The view's current [state](#state.EditorState).\n this.state = props.state;\n\n this.dispatch = this.dispatch.bind(this);\n\n this._root = null;\n this.focused = false;\n // Kludge used to work around a Chrome bug\n this.trackWrites = null;\n\n // :: dom.Element\n // An editable DOM node containing the document. (You probably\n // should not directly interfere with its content.)\n this.dom = (place && place.mount) || document.createElement(\"div\");\n if (place) {\n if (place.appendChild) { place.appendChild(this.dom); }\n else if (place.apply) { place(this.dom); }\n else if (place.mount) { this.mounted = true; }\n }\n\n // :: bool\n // Indicates whether the editor is currently [editable](#view.EditorProps.editable).\n this.editable = getEditable(this);\n this.markCursor = null;\n this.cursorWrapper = null;\n updateCursorWrapper(this);\n this.nodeViews = buildNodeViews(this);\n this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);\n\n this.lastSelectedViewDesc = null;\n // :: ?{slice: Slice, move: bool}\n // When editor content is being dragged, this object contains\n // information about the dragged slice and whether it is being\n // copied or moved. At any other time, it is null.\n this.dragging = null;\n\n initInput(this);\n\n this.pluginViews = [];\n this.updatePluginViews();\n};\n\nvar prototypeAccessors$2 = { props: { configurable: true },root: { configurable: true } };\n\n// composing:: boolean\n// Holds `true` when a\n// [composition](https://developer.mozilla.org/en-US/docs/Mozilla/IME_handling_guide)\n// is active.\n\n// :: DirectEditorProps\n// The view's current [props](#view.EditorProps).\nprototypeAccessors$2.props.get = function () {\n if (this._props.state != this.state) {\n var prev = this._props;\n this._props = {};\n for (var name in prev) { this._props[name] = prev[name]; }\n this._props.state = this.state;\n }\n return this._props\n};\n\n// :: (DirectEditorProps)\n// Update the view's props. Will immediately cause an update to\n// the DOM.\nEditorView.prototype.update = function update (props) {\n if (props.handleDOMEvents != this._props.handleDOMEvents) { ensureListeners(this); }\n this._props = props;\n this.updateStateInner(props.state, true);\n};\n\n// :: (DirectEditorProps)\n// Update the view by updating existing props object with the object\n// given as argument. Equivalent to `view.update(Object.assign({},\n// view.props, props))`.\nEditorView.prototype.setProps = function setProps (props) {\n var updated = {};\n for (var name in this._props) { updated[name] = this._props[name]; }\n updated.state = this.state;\n for (var name$1 in props) { updated[name$1] = props[name$1]; }\n this.update(updated);\n};\n\n// :: (EditorState)\n// Update the editor's `state` prop, without touching any of the\n// other props.\nEditorView.prototype.updateState = function updateState (state) {\n this.updateStateInner(state, this.state.plugins != state.plugins);\n};\n\nEditorView.prototype.updateStateInner = function updateStateInner (state, reconfigured) {\n var this$1 = this;\n\n var prev = this.state, redraw = false, updateSel = false;\n // When stored marks are added, stop composition, so that they can\n // be displayed.\n if (state.storedMarks && this.composing) {\n clearComposition(this);\n updateSel = true;\n }\n this.state = state;\n if (reconfigured) {\n var nodeViews = buildNodeViews(this);\n if (changedNodeViews(nodeViews, this.nodeViews)) {\n this.nodeViews = nodeViews;\n redraw = true;\n }\n ensureListeners(this);\n }\n\n this.editable = getEditable(this);\n updateCursorWrapper(this);\n var innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);\n\n var scroll = reconfigured ? \"reset\"\n : state.scrollToSelection > prev.scrollToSelection ? \"to selection\" : \"preserve\";\n var updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);\n if (updateDoc || !state.selection.eq(prev.selection)) { updateSel = true; }\n var oldScrollPos = scroll == \"preserve\" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);\n\n if (updateSel) {\n this.domObserver.stop();\n // Work around an issue in Chrome, IE, and Edge where changing\n // the DOM around an active selection puts it into a broken\n // state where the thing the user sees differs from the\n // selection reported by the Selection object (#710, #973,\n // #1011, #1013, #1035).\n var forceSelUpdate = updateDoc && (result.ie || result.chrome) && !this.composing &&\n !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);\n if (updateDoc) {\n // If the node that the selection points into is written to,\n // Chrome sometimes starts misreporting the selection, so this\n // tracks that and forces a selection reset when our update\n // did write to the node.\n var chromeKludge = result.chrome ? (this.trackWrites = this.root.getSelection().focusNode) : null;\n if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {\n this.docView.updateOuterDeco([]);\n this.docView.destroy();\n this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);\n }\n if (chromeKludge && !this.trackWrites) { forceSelUpdate = true; }\n }\n // Work around for an issue where an update arriving right between\n // a DOM selection change and the \"selectionchange\" event for it\n // can cause a spurious DOM selection update, disrupting mouse\n // drag selection.\n if (forceSelUpdate ||\n !(this.mouseDown && this.domObserver.currentSelection.eq(this.root.getSelection()) && anchorInRightPlace(this))) {\n selectionToDOM(this, forceSelUpdate);\n } else {\n syncNodeSelection(this, state.selection);\n this.domObserver.setCurSelection();\n }\n this.domObserver.start();\n }\n\n this.updatePluginViews(prev);\n\n if (scroll == \"reset\") {\n this.dom.scrollTop = 0;\n } else if (scroll == \"to selection\") {\n var startDOM = this.root.getSelection().focusNode;\n if (this.someProp(\"handleScrollToSelection\", function (f) { return f(this$1); }))\n ; // Handled\n else if (state.selection instanceof NodeSelection)\n { scrollRectIntoView(this, this.docView.domAfterPos(state.selection.from).getBoundingClientRect(), startDOM); }\n else\n { scrollRectIntoView(this, this.coordsAtPos(state.selection.head, 1), startDOM); }\n } else if (oldScrollPos) {\n resetScrollPos(oldScrollPos);\n }\n};\n\nEditorView.prototype.destroyPluginViews = function destroyPluginViews () {\n var view;\n while (view = this.pluginViews.pop()) { if (view.destroy) { view.destroy(); } }\n};\n\nEditorView.prototype.updatePluginViews = function updatePluginViews (prevState) {\n if (!prevState || prevState.plugins != this.state.plugins) {\n this.destroyPluginViews();\n for (var i = 0; i < this.state.plugins.length; i++) {\n var plugin = this.state.plugins[i];\n if (plugin.spec.view) { this.pluginViews.push(plugin.spec.view(this)); }\n }\n } else {\n for (var i$1 = 0; i$1 < this.pluginViews.length; i$1++) {\n var pluginView = this.pluginViews[i$1];\n if (pluginView.update) { pluginView.update(this, prevState); }\n }\n }\n};\n\n// :: (string, ?(prop: *) → *) → *\n// Goes over the values of a prop, first those provided directly,\n// then those from plugins (in order), and calls `f` every time a\n// non-undefined value is found. When `f` returns a truthy value,\n// that is immediately returned. When `f` isn't provided, it is\n// treated as the identity function (the prop value is returned\n// directly).\nEditorView.prototype.someProp = function someProp (propName, f) {\n var prop = this._props && this._props[propName], value;\n if (prop != null && (value = f ? f(prop) : prop)) { return value }\n var plugins = this.state.plugins;\n if (plugins) { for (var i = 0; i < plugins.length; i++) {\n var prop$1 = plugins[i].props[propName];\n if (prop$1 != null && (value = f ? f(prop$1) : prop$1)) { return value }\n } }\n};\n\n// :: () → bool\n// Query whether the view has focus.\nEditorView.prototype.hasFocus = function hasFocus () {\n return this.root.activeElement == this.dom\n};\n\n// :: ()\n// Focus the editor.\nEditorView.prototype.focus = function focus () {\n this.domObserver.stop();\n if (this.editable) { focusPreventScroll(this.dom); }\n selectionToDOM(this);\n this.domObserver.start();\n};\n\n// :: union\n// Get the document root in which the editor exists. This will\n// usually be the top-level `document`, but might be a [shadow\n// DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)\n// root if the editor is inside one.\nprototypeAccessors$2.root.get = function () {\n var cached = this._root;\n if (cached == null) { for (var search = this.dom.parentNode; search; search = search.parentNode) {\n if (search.nodeType == 9 || (search.nodeType == 11 && search.host)) {\n if (!search.getSelection) { Object.getPrototypeOf(search).getSelection = function () { return document.getSelection(); }; }\n return this._root = search\n }\n } }\n return cached || document\n};\n\n// :: ({left: number, top: number}) → ?{pos: number, inside: number}\n// Given a pair of viewport coordinates, return the document\n// position that corresponds to them. May return null if the given\n// coordinates aren't inside of the editor. When an object is\n// returned, its `pos` property is the position nearest to the\n// coordinates, and its `inside` property holds the position of the\n// inner node that the position falls inside of, or -1 if it is at\n// the top level, not in any node.\nEditorView.prototype.posAtCoords = function posAtCoords$1 (coords) {\n return posAtCoords(this, coords)\n};\n\n// :: (number, number) → {left: number, right: number, top: number, bottom: number}\n// Returns the viewport rectangle at a given document position.\n// `left` and `right` will be the same number, as this returns a\n// flat cursor-ish rectangle. If the position is between two things\n// that aren't directly adjacent, `side` determines which element is\n// used. When < 0, the element before the position is used,\n// otherwise the element after.\nEditorView.prototype.coordsAtPos = function coordsAtPos$1 (pos, side) {\n if ( side === void 0 ) side = 1;\n\n return coordsAtPos(this, pos, side)\n};\n\n// :: (number) → {node: dom.Node, offset: number}\n// Find the DOM position that corresponds to the given document\n// position. Note that you should **not** mutate the editor's\n// internal DOM, only inspect it (and even that is usually not\n// necessary).\nEditorView.prototype.domAtPos = function domAtPos (pos) {\n return this.docView.domFromPos(pos)\n};\n\n// :: (number) → ?dom.Node\n// Find the DOM node that represents the document node after the\n// given position. May return `null` when the position doesn't point\n// in front of a node or if the node is inside an opaque node view.\n//\n// This is intended to be able to call things like\n// `getBoundingClientRect` on that DOM node. Do **not** mutate the\n// editor DOM directly, or add styling this way, since that will be\n// immediately overriden by the editor as it redraws the node.\nEditorView.prototype.nodeDOM = function nodeDOM (pos) {\n var desc = this.docView.descAt(pos);\n return desc ? desc.nodeDOM : null\n};\n\n// :: (dom.Node, number, ?number) → number\n// Find the document position that corresponds to a given DOM\n// position. (Whenever possible, it is preferable to inspect the\n// document structure directly, rather than poking around in the\n// DOM, but sometimes—for example when interpreting an event\n// target—you don't have a choice.)\n//\n// The `bias` parameter can be used to influence which side of a DOM\n// node to use when the position is inside a leaf node.\nEditorView.prototype.posAtDOM = function posAtDOM (node, offset, bias) {\n if ( bias === void 0 ) bias = -1;\n\n var pos = this.docView.posFromDOM(node, offset, bias);\n if (pos == null) { throw new RangeError(\"DOM position not inside the editor\") }\n return pos\n};\n\n// :: (union<\"up\", \"down\", \"left\", \"right\", \"forward\", \"backward\">, ?EditorState) → bool\n// Find out whether the selection is at the end of a textblock when\n// moving in a given direction. When, for example, given `\"left\"`,\n// it will return true if moving left from the current cursor\n// position would leave that position's parent textblock. Will apply\n// to the view's current state by default, but it is possible to\n// pass a different state.\nEditorView.prototype.endOfTextblock = function endOfTextblock$1 (dir, state) {\n return endOfTextblock(this, state || this.state, dir)\n};\n\n// :: ()\n// Removes the editor from the DOM and destroys all [node\n// views](#view.NodeView).\nEditorView.prototype.destroy = function destroy () {\n if (!this.docView) { return }\n destroyInput(this);\n this.destroyPluginViews();\n if (this.mounted) {\n this.docView.update(this.state.doc, [], viewDecorations(this), this);\n this.dom.textContent = \"\";\n } else if (this.dom.parentNode) {\n this.dom.parentNode.removeChild(this.dom);\n }\n this.docView.destroy();\n this.docView = null;\n};\n\n// Used for testing.\nEditorView.prototype.dispatchEvent = function dispatchEvent$1 (event) {\n return dispatchEvent(this, event)\n};\n\n// :: (Transaction)\n// Dispatch a transaction. Will call\n// [`dispatchTransaction`](#view.DirectEditorProps.dispatchTransaction)\n// when given, and otherwise defaults to applying the transaction to\n// the current state and calling\n// [`updateState`](#view.EditorView.updateState) with the result.\n// This method is bound to the view instance, so that it can be\n// easily passed around.\nEditorView.prototype.dispatch = function dispatch (tr) {\n var dispatchTransaction = this._props.dispatchTransaction;\n if (dispatchTransaction) { dispatchTransaction.call(this, tr); }\n else { this.updateState(this.state.apply(tr)); }\n};\n\nObject.defineProperties( EditorView.prototype, prototypeAccessors$2 );\n\nfunction computeDocDeco(view) {\n var attrs = Object.create(null);\n attrs.class = \"ProseMirror\";\n attrs.contenteditable = String(view.editable);\n\n view.someProp(\"attributes\", function (value) {\n if (typeof value == \"function\") { value = value(view.state); }\n if (value) { for (var attr in value) {\n if (attr == \"class\")\n { attrs.class += \" \" + value[attr]; }\n else if (!attrs[attr] && attr != \"contenteditable\" && attr != \"nodeName\")\n { attrs[attr] = String(value[attr]); }\n } }\n });\n\n return [Decoration.node(0, view.state.doc.content.size, attrs)]\n}\n\nfunction updateCursorWrapper(view) {\n if (view.markCursor) {\n var dom = document.createElement(\"img\");\n dom.setAttribute(\"mark-placeholder\", \"true\");\n view.cursorWrapper = {dom: dom, deco: Decoration.widget(view.state.selection.head, dom, {raw: true, marks: view.markCursor})};\n } else {\n view.cursorWrapper = null;\n }\n}\n\nfunction getEditable(view) {\n return !view.someProp(\"editable\", function (value) { return value(view.state) === false; })\n}\n\nfunction selectionContextChanged(sel1, sel2) {\n var depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));\n return sel1.$anchor.start(depth) != sel2.$anchor.start(depth)\n}\n\nfunction buildNodeViews(view) {\n var result = {};\n view.someProp(\"nodeViews\", function (obj) {\n for (var prop in obj) { if (!Object.prototype.hasOwnProperty.call(result, prop))\n { result[prop] = obj[prop]; } }\n });\n return result\n}\n\nfunction changedNodeViews(a, b) {\n var nA = 0, nB = 0;\n for (var prop in a) {\n if (a[prop] != b[prop]) { return true }\n nA++;\n }\n for (var _ in b) { nB++; }\n return nA != nB\n}\n\n// EditorProps:: interface\n//\n// Props are configuration values that can be passed to an editor view\n// or included in a plugin. This interface lists the supported props.\n//\n// The various event-handling functions may all return `true` to\n// indicate that they handled the given event. The view will then take\n// care to call `preventDefault` on the event, except with\n// `handleDOMEvents`, where the handler itself is responsible for that.\n//\n// How a prop is resolved depends on the prop. Handler functions are\n// called one at a time, starting with the base props and then\n// searching through the plugins (in order of appearance) until one of\n// them returns true. For some props, the first plugin that yields a\n// value gets precedence.\n//\n// handleDOMEvents:: ?Object<(view: EditorView, event: dom.Event) → bool>\n// Can be an object mapping DOM event type names to functions that\n// handle them. Such functions will be called before any handling\n// ProseMirror does of events fired on the editable DOM element.\n// Contrary to the other event handling props, when returning true\n// from such a function, you are responsible for calling\n// `preventDefault` yourself (or not, if you want to allow the\n// default behavior).\n//\n// handleKeyDown:: ?(view: EditorView, event: dom.KeyboardEvent) → bool\n// Called when the editor receives a `keydown` event.\n//\n// handleKeyPress:: ?(view: EditorView, event: dom.KeyboardEvent) → bool\n// Handler for `keypress` events.\n//\n// handleTextInput:: ?(view: EditorView, from: number, to: number, text: string) → bool\n// Whenever the user directly input text, this handler is called\n// before the input is applied. If it returns `true`, the default\n// behavior of actually inserting the text is suppressed.\n//\n// handleClickOn:: ?(view: EditorView, pos: number, node: Node, nodePos: number, event: dom.MouseEvent, direct: bool) → bool\n// Called for each node around a click, from the inside out. The\n// `direct` flag will be true for the inner node.\n//\n// handleClick:: ?(view: EditorView, pos: number, event: dom.MouseEvent) → bool\n// Called when the editor is clicked, after `handleClickOn` handlers\n// have been called.\n//\n// handleDoubleClickOn:: ?(view: EditorView, pos: number, node: Node, nodePos: number, event: dom.MouseEvent, direct: bool) → bool\n// Called for each node around a double click.\n//\n// handleDoubleClick:: ?(view: EditorView, pos: number, event: dom.MouseEvent) → bool\n// Called when the editor is double-clicked, after `handleDoubleClickOn`.\n//\n// handleTripleClickOn:: ?(view: EditorView, pos: number, node: Node, nodePos: number, event: dom.MouseEvent, direct: bool) → bool\n// Called for each node around a triple click.\n//\n// handleTripleClick:: ?(view: EditorView, pos: number, event: dom.MouseEvent) → bool\n// Called when the editor is triple-clicked, after `handleTripleClickOn`.\n//\n// handlePaste:: ?(view: EditorView, event: dom.ClipboardEvent, slice: Slice) → bool\n// Can be used to override the behavior of pasting. `slice` is the\n// pasted content parsed by the editor, but you can directly access\n// the event to get at the raw content.\n//\n// handleDrop:: ?(view: EditorView, event: dom.Event, slice: Slice, moved: bool) → bool\n// Called when something is dropped on the editor. `moved` will be\n// true if this drop moves from the current selection (which should\n// thus be deleted).\n//\n// handleScrollToSelection:: ?(view: EditorView) → bool\n// Called when the view, after updating its state, tries to scroll\n// the selection into view. A handler function may return false to\n// indicate that it did not handle the scrolling and further\n// handlers or the default behavior should be tried.\n//\n// createSelectionBetween:: ?(view: EditorView, anchor: ResolvedPos, head: ResolvedPos) → ?Selection\n// Can be used to override the way a selection is created when\n// reading a DOM selection between the given anchor and head.\n//\n// domParser:: ?DOMParser\n// The [parser](#model.DOMParser) to use when reading editor changes\n// from the DOM. Defaults to calling\n// [`DOMParser.fromSchema`](#model.DOMParser^fromSchema) on the\n// editor's schema.\n//\n// transformPastedHTML:: ?(html: string) → string\n// Can be used to transform pasted HTML text, _before_ it is parsed,\n// for example to clean it up.\n//\n// clipboardParser:: ?DOMParser\n// The [parser](#model.DOMParser) to use when reading content from\n// the clipboard. When not given, the value of the\n// [`domParser`](#view.EditorProps.domParser) prop is used.\n//\n// transformPastedText:: ?(text: string, plain: bool) → string\n// Transform pasted plain text. The `plain` flag will be true when\n// the text is pasted as plain text.\n//\n// clipboardTextParser:: ?(text: string, $context: ResolvedPos, plain: bool) → Slice\n// A function to parse text from the clipboard into a document\n// slice. Called after\n// [`transformPastedText`](#view.EditorProps.transformPastedText).\n// The default behavior is to split the text into lines, wrap them\n// in `

` tags, and call\n// [`clipboardParser`](#view.EditorProps.clipboardParser) on it.\n// The `plain` flag will be true when the text is pasted as plain text.\n//\n// transformPasted:: ?(Slice) → Slice\n// Can be used to transform pasted content before it is applied to\n// the document.\n//\n// nodeViews:: ?Object<(node: Node, view: EditorView, getPos: () → number, decorations: [Decoration]) → NodeView>\n// Allows you to pass custom rendering and behavior logic for nodes\n// and marks. Should map node and mark names to constructor\n// functions that produce a [`NodeView`](#view.NodeView) object\n// implementing the node's display behavior. For nodes, the third\n// argument `getPos` is a function that can be called to get the\n// node's current position, which can be useful when creating\n// transactions to update it. For marks, the third argument is a\n// boolean that indicates whether the mark's content is inline.\n//\n// `decorations` is an array of node or inline decorations that are\n// active around the node. They are automatically drawn in the\n// normal way, and you will usually just want to ignore this, but\n// they can also be used as a way to provide context information to\n// the node view without adding it to the document itself.\n//\n// clipboardSerializer:: ?DOMSerializer\n// The DOM serializer to use when putting content onto the\n// clipboard. If not given, the result of\n// [`DOMSerializer.fromSchema`](#model.DOMSerializer^fromSchema)\n// will be used.\n//\n// clipboardTextSerializer:: ?(Slice) → string\n// A function that will be called to get the text for the current\n// selection when copying text to the clipboard. By default, the\n// editor will use [`textBetween`](#model.Node.textBetween) on the\n// selected range.\n//\n// decorations:: ?(state: EditorState) → ?DecorationSet\n// A set of [document decorations](#view.Decoration) to show in the\n// view.\n//\n// editable:: ?(state: EditorState) → bool\n// When this returns false, the content of the view is not directly\n// editable.\n//\n// attributes:: ?union, (EditorState) → ?Object>\n// Control the DOM attributes of the editable element. May be either\n// an object or a function going from an editor state to an object.\n// By default, the element will get a class `\"ProseMirror\"`, and\n// will have its `contentEditable` attribute determined by the\n// [`editable` prop](#view.EditorProps.editable). Additional classes\n// provided here will be added to the class. For other attributes,\n// the value provided first (as in\n// [`someProp`](#view.EditorView.someProp)) will be used.\n//\n// scrollThreshold:: ?union\n// Determines the distance (in pixels) between the cursor and the\n// end of the visible viewport at which point, when scrolling the\n// cursor into view, scrolling takes place. Defaults to 0.\n//\n// scrollMargin:: ?union\n// Determines the extra space (in pixels) that is left above or\n// below the cursor when it is scrolled into view. Defaults to 5.\n\n// DirectEditorProps:: interface extends EditorProps\n//\n// The props object given directly to the editor view supports two\n// fields that can't be used in plugins:\n//\n// state:: EditorState\n// The current state of the editor.\n//\n// dispatchTransaction:: ?(tr: Transaction)\n// The callback over which to send transactions (state updates)\n// produced by the view. If you specify this, you probably want to\n// make sure this ends up calling the view's\n// [`updateState`](#view.EditorView.updateState) method with a new\n// state that has the transaction\n// [applied](#state.EditorState.apply). The callback will be bound to have\n// the view instance as its `this` binding.\n\nexport { Decoration, DecorationSet, EditorView, endComposition as __endComposition, parseFromClipboard as __parseFromClipboard, serializeForClipboard as __serializeForClipboard };\n//# sourceMappingURL=index.es.js.map\n","/**\n * Efficient diffs.\n *\n * @module diff\n */\n\nimport { equalityStrict } from './function.js'\n\n/**\n * A SimpleDiff describes a change on a String.\n *\n * ```js\n * console.log(a) // the old value\n * console.log(b) // the updated value\n * // Apply changes of diff (pseudocode)\n * a.remove(diff.index, diff.remove) // Remove `diff.remove` characters\n * a.insert(diff.index, diff.insert) // Insert `diff.insert`\n * a === b // values match\n * ```\n *\n * @typedef {Object} SimpleDiff\n * @property {Number} index The index where changes were applied\n * @property {Number} remove The number of characters to delete starting\n * at `index`.\n * @property {T} insert The new text to insert at `index` after applying\n * `delete`\n *\n * @template T\n */\n\n/**\n * Create a diff between two strings. This diff implementation is highly\n * efficient, but not very sophisticated.\n *\n * @function\n *\n * @param {string} a The old version of the string\n * @param {string} b The updated version of the string\n * @return {SimpleDiff} The diff description.\n */\nexport const simpleDiffString = (a, b) => {\n let left = 0 // number of same characters counting from left\n let right = 0 // number of same characters counting from right\n while (left < a.length && left < b.length && a[left] === b[left]) {\n left++\n }\n if (left !== a.length || left !== b.length) {\n // Only check right if a !== b\n while (right + left < a.length && right + left < b.length && a[a.length - right - 1] === b[b.length - right - 1]) {\n right++\n }\n }\n return {\n index: left,\n remove: a.length - left - right,\n insert: b.slice(left, b.length - right)\n }\n}\n\n/**\n * @todo Remove in favor of simpleDiffString\n * @deprecated\n */\nexport const simpleDiff = simpleDiffString\n\n/**\n * Create a diff between two arrays. This diff implementation is highly\n * efficient, but not very sophisticated.\n *\n * Note: This is basically the same function as above. Another function was created so that the runtime\n * can better optimize these function calls.\n *\n * @function\n * @template T\n *\n * @param {Array} a The old version of the array\n * @param {Array} b The updated version of the array\n * @param {function(T, T):boolean} [compare]\n * @return {SimpleDiff>} The diff description.\n */\nexport const simpleDiffArray = (a, b, compare = equalityStrict) => {\n let left = 0 // number of same characters counting from left\n let right = 0 // number of same characters counting from right\n while (left < a.length && left < b.length && compare(a[left], b[left])) {\n left++\n }\n if (left !== a.length || left !== b.length) {\n // Only check right if a !== b\n while (right + left < a.length && right + left < b.length && compare(a[a.length - right - 1], b[b.length - right - 1])) {\n right++\n }\n }\n return {\n index: left,\n remove: a.length - left - right,\n insert: b.slice(left, b.length - right)\n }\n}\n","\nimport { PluginKey } from 'prosemirror-state' // eslint-disable-line\n\n/**\n * The unique prosemirror plugin key for syncPlugin\n *\n * @public\n */\nexport const ySyncPluginKey = new PluginKey('y-sync')\n\n/**\n * The unique prosemirror plugin key for undoPlugin\n *\n * @public\n */\nexport const yUndoPluginKey = new PluginKey('y-undo')\n\n/**\n * The unique prosemirror plugin key for cursorPlugin\n *\n * @public\n */\nexport const yCursorPluginKey = new PluginKey('yjs-cursor')\n","/**\n * @module bindings/prosemirror\n */\n\nimport { createMutex } from 'lib0/mutex.js'\nimport { Node as PMNode, Slice as PMSlice, Fragment as PMFragment, Schema as PMSchema } from 'prosemirror-model'\nimport { Plugin, TextSelection } from 'prosemirror-state' // eslint-disable-line\nimport { min } from 'lib0/math.js'\nimport { keys } from 'lib0/object.js'\nimport { simpleDiff } from 'lib0/diff.js'\nimport { methodUnimplemented } from 'lib0/error.js'\nimport { ySyncPluginKey } from './keys.js'\nimport * as Y from 'yjs'\nimport { absolutePositionToRelativePosition, relativePositionToAbsolutePosition } from '../lib.js'\nimport { isBrowser } from 'lib0/environment.js'\nimport { doc } from 'lib0/dom.js'\n\n/**\n * @param {Y.Item} item\n * @param {Y.Snapshot} [snapshot]\n */\nexport const isVisible = (item, snapshot) => snapshot === undefined ? !item.deleted : (snapshot.sv.has(item.id.client) && /** @type {number} */ (snapshot.sv.get(item.id.client)) > item.id.clock && !Y.isDeleted(snapshot.ds, item.id))\n\n/**\n * Either a node if type is YXmlElement or an Array of text nodes if YXmlText\n * @typedef {Map>} ProsemirrorMapping\n */\n\n/**\n * @typedef {Object} ColorDef\n * @property {string} ColorDef.light\n * @property {string} ColorDef.dark\n */\n\n/**\n * @typedef {Object} YSyncOpts\n * @property {Array} [YSyncOpts.colors]\n * @property {Map} [YSyncOpts.colorMapping]\n * @property {Y.PermanentUserData|null} [YSyncOpts.permanentUserData]\n * @property {JSON|null} [YSyncOpts.initialContent]\n */\n\n/**\n * @type {Array}\n */\nconst defaultColors = [{ light: '#ecd44433', dark: '#ecd444' }]\n\n/**\n * @param {Map} colorMapping\n * @param {Array} colors\n * @param {string} user\n * @return {ColorDef}\n */\nconst getUserColor = (colorMapping, colors, user) => {\n if (!colorMapping.has(user)) {\n colorMapping.set(user, colors[colorMapping.size % colors.length]);\n }\n return /** @type {ColorDef} */ (colorMapping.get(user));\n}\n\n/**\n * This plugin listens to changes in prosemirror view and keeps yXmlState and view in sync.\n *\n * This plugin also keeps references to the type and the shared document so other plugins can access it.\n * @param {Y.XmlFragment} yXmlFragment\n * @param {YSyncOpts} opts\n * @return {any} Returns a prosemirror plugin that binds to this type\n */\nexport const ySyncPlugin = (yXmlFragment, { colors = defaultColors, colorMapping = new Map(), permanentUserData = null, initialContent = null } = {}) => {\n let changedInitialContent = false\n const plugin = new Plugin({\n props: {\n editable: (state) => {\n const syncState = ySyncPluginKey.getState(state)\n return syncState.snapshot == null && syncState.prevSnapshot == null\n }\n },\n key: ySyncPluginKey,\n state: {\n init: (initargs, state) => {\n return {\n type: yXmlFragment,\n doc: yXmlFragment.doc,\n binding: null,\n snapshot: null,\n prevSnapshot: null,\n isChangeOrigin: false,\n colors,\n colorMapping,\n permanentUserData\n }\n },\n apply: (tr, pluginState) => {\n const change = tr.getMeta(ySyncPluginKey)\n if (change !== undefined) {\n pluginState = Object.assign({}, pluginState)\n for (const key in change) {\n pluginState[key] = change[key]\n }\n }\n // always set isChangeOrigin. If undefined, this is not change origin.\n pluginState.isChangeOrigin = change !== undefined && !!change.isChangeOrigin\n if (pluginState.binding !== null) {\n if (change !== undefined && (change.snapshot != null || change.prevSnapshot != null)) {\n // snapshot changed, rerender next\n setTimeout(() => {\n if (change.restore == null) {\n pluginState.binding._renderSnapshot(change.snapshot, change.prevSnapshot, pluginState)\n } else {\n pluginState.binding._renderSnapshot(change.snapshot, change.snapshot, pluginState)\n // reset to current prosemirror state\n delete pluginState.restore\n delete pluginState.snapshot\n delete pluginState.prevSnapshot\n pluginState.binding._prosemirrorChanged(pluginState.binding.prosemirrorView.state.doc)\n }\n }, 0)\n }\n }\n return pluginState\n }\n },\n view: view => {\n const binding = new ProsemirrorBinding(yXmlFragment, view);\n binding._forceRerender();\n return {\n update: () => {\n const pluginState = plugin.getState(view.state)\n if (pluginState.snapshot == null && pluginState.prevSnapshot == null) {\n changedInitialContent = changedInitialContent || initialContent \n ? view.state.doc.content.findDiffStart(view.state.schema.nodeFromJSON(initialContent)) !== null \n : view.state.doc.content.findDiffStart(view.state.doc.type.createAndFill().content) !== null\n if (changedInitialContent) {\n changedInitialContent = true\n binding._prosemirrorChanged(view.state.doc)\n }\n }\n },\n destroy: () => {\n binding.destroy()\n }\n }\n }\n })\n return plugin\n}\n\n/**\n * @param {any} tr\n * @param {any} relSel\n * @param {ProsemirrorBinding} binding\n */\nconst restoreRelativeSelection = (tr, relSel, binding) => {\n if (relSel !== null && relSel.anchor !== null && relSel.head !== null) {\n const anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping)\n const head = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.head, binding.mapping)\n if (anchor !== null && head !== null) {\n tr = tr.setSelection(TextSelection.create(tr.doc, anchor, head))\n }\n }\n}\n\nexport const getRelativeSelection = (pmbinding, state) => ({\n anchor: absolutePositionToRelativePosition(state.selection.anchor, pmbinding.type, pmbinding.mapping),\n head: absolutePositionToRelativePosition(state.selection.head, pmbinding.type, pmbinding.mapping)\n})\n\n/**\n * Binding for prosemirror.\n *\n * @protected\n */\nexport class ProsemirrorBinding {\n /**\n * @param {Y.XmlFragment} yXmlFragment The bind source\n * @param {any} prosemirrorView The target binding\n */\n constructor (yXmlFragment, prosemirrorView) {\n this.type = yXmlFragment\n this.prosemirrorView = prosemirrorView\n this.mux = createMutex()\n /**\n * @type {ProsemirrorMapping}\n */\n this.mapping = new Map()\n this._observeFunction = this._typeChanged.bind(this)\n /**\n * @type {Y.Doc}\n */\n // @ts-ignore\n this.doc = yXmlFragment.doc\n /**\n * current selection as relative positions in the Yjs model\n */\n this.beforeTransactionSelection = null\n this.beforeAllTransactions = () => {\n if (this.beforeTransactionSelection === null) {\n this.beforeTransactionSelection = getRelativeSelection(this, prosemirrorView.state)\n }\n }\n this.afterAllTransactions = () => {\n this.beforeTransactionSelection = null\n }\n\n this.doc.on('beforeAllTransactions', this.beforeAllTransactions)\n this.doc.on('afterAllTransactions', this.afterAllTransactions)\n yXmlFragment.observeDeep(this._observeFunction)\n\n this._domSelectionInView = null\n }\n\n _isLocalCursorInView () {\n if (!this.prosemirrorView.hasFocus()) return false\n if (isBrowser && this._domSelectionInView === null) {\n // Calculate the domSelectionInView and clear by next tick after all events are finished\n setTimeout(() => {\n this._domSelectionInView = null\n }, 0)\n this._domSelectionInView = this._isDomSelectionInView()\n }\n return this._domSelectionInView\n }\n\n _isDomSelectionInView () {\n const selection = this.prosemirrorView._root.getSelection()\n\n const range = this.prosemirrorView._root.createRange()\n range.setStart(selection.anchorNode, selection.anchorOffset)\n range.setEnd(selection.focusNode, selection.focusOffset)\n\n // This is a workaround for an edgecase where getBoundingClientRect will\n // return zero values if the selection is collapsed at the start of a newline\n // see reference here: https://stackoverflow.com/a/59780954\n const rects = range.getClientRects()\n if (rects.length === 0) {\n // probably buggy newline behavior, explicitly select the node contents\n if (range.startContainer && range.collapsed) {\n range.selectNodeContents(range.startContainer)\n }\n }\n\n const bounding = range.getBoundingClientRect()\n const documentElement = doc.documentElement\n\n return bounding.bottom >= 0 && bounding.right >= 0 &&\n bounding.left <= (window.innerWidth || documentElement.clientWidth || 0) &&\n bounding.top <= (window.innerHeight || documentElement.clientHeight || 0)\n }\n\n renderSnapshot (snapshot, prevSnapshot) {\n if (!prevSnapshot) {\n prevSnapshot = Y.createSnapshot(Y.createDeleteSet(), new Map())\n }\n this.prosemirrorView.dispatch(this.prosemirrorView.state.tr.setMeta(ySyncPluginKey, { snapshot, prevSnapshot }))\n }\n\n unrenderSnapshot () {\n this.mapping = new Map()\n this.mux(() => {\n const fragmentContent = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null)\n // @ts-ignore\n const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new PMSlice(new PMFragment(fragmentContent), 0, 0))\n tr.setMeta(ySyncPluginKey, { snapshot: null, prevSnapshot: null })\n this.prosemirrorView.dispatch(tr)\n })\n }\n\n _forceRerender () {\n this.mapping = new Map()\n this.mux(() => {\n // const fragmentContent = this.type.toArray().map(t => createNodeFromYElement(/** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null)\n // @ts-ignore\n // const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new PModel.Slice(new PModel.Fragment(fragmentContent), 0, 0)) const tr = this.prosemirrorView.state.tr\n const tr = this.prosemirrorView.state.tr\n tr.setMeta(ySyncPluginKey, { binding: this })\n this.prosemirrorView.dispatch(tr)\n })\n }\n\n /**\n * @param {Y.Snapshot} snapshot\n * @param {Y.Snapshot} prevSnapshot\n * @param {Object} pluginState\n */\n _renderSnapshot (snapshot, prevSnapshot, pluginState) {\n if (!snapshot) {\n snapshot = Y.snapshot(this.doc)\n }\n // clear mapping because we are going to rerender\n this.mapping = new Map()\n this.mux(() => {\n this.doc.transact(transaction => {\n // before rendering, we are going to sanitize ops and split deleted ops\n // if they were deleted by seperate users.\n const pud = pluginState.permanentUserData\n if (pud) {\n pud.dss.forEach(ds => {\n Y.iterateDeletedStructs(transaction, ds, item => {})\n })\n }\n const computeYChange = (type, id) => {\n const user = type === 'added' ? pud.getUserByClientId(id.client) : pud.getUserByDeletedId(id)\n return {\n user,\n type,\n color: getUserColor(pluginState.colorMapping, pluginState.colors, user)\n }\n }\n // Create document fragment and render\n const fragmentContent = Y.typeListToArraySnapshot(this.type, new Y.Snapshot(prevSnapshot.ds, snapshot.sv)).map(t => {\n if (!t._item.deleted || isVisible(t._item, snapshot) || isVisible(t._item, prevSnapshot)) {\n return createNodeFromYElement(t, this.prosemirrorView.state.schema, new Map(), snapshot, prevSnapshot, computeYChange)\n } else {\n // No need to render elements that are not visible by either snapshot.\n // If a client adds and deletes content in the same snapshot the element is not visible by either snapshot.\n return null\n }\n }).filter(n => n !== null)\n // @ts-ignore\n const tr = this.prosemirrorView.state.tr.replace(0, this.prosemirrorView.state.doc.content.size, new PMSlice(new PMFragment(fragmentContent), 0, 0))\n this.prosemirrorView.dispatch(tr)\n }, ySyncPluginKey)\n })\n }\n\n /**\n * @param {Array} events\n * @param {Y.Transaction} transaction\n */\n _typeChanged (events, transaction) {\n const syncState = ySyncPluginKey.getState(this.prosemirrorView.state)\n if (events.length === 0 || syncState.snapshot != null || syncState.prevSnapshot != null) {\n // drop out if snapshot is active\n this.renderSnapshot(syncState.snapshot, syncState.prevSnapshot)\n return\n }\n this.mux(() => {\n /**\n * @param {any} _\n * @param {Y.AbstractType} type\n */\n const delType = (_, type) => this.mapping.delete(type)\n Y.iterateDeletedStructs(transaction, transaction.deleteSet, struct => struct.constructor === Y.Item && this.mapping.delete(/** @type {Y.ContentType} */ (/** @type {Y.Item} */ (struct).content).type))\n transaction.changed.forEach(delType)\n transaction.changedParentTypes.forEach(delType)\n const fragmentContent = this.type.toArray().map(t => createNodeIfNotExists(/** @type {Y.XmlElement | Y.XmlHook} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter(n => n !== null)\n // @ts-ignore\n let tr = this.prosemirrorView.state.tr.replaceWith(0, this.prosemirrorView.state.doc.content.size, new PMFragment(fragmentContent));\n restoreRelativeSelection(tr, this.beforeTransactionSelection, this)\n tr = tr.setMeta(ySyncPluginKey, { isChangeOrigin: true })\n if (this.beforeTransactionSelection !== null && this._isLocalCursorInView()) {\n tr.scrollIntoView()\n }\n this.prosemirrorView.dispatch(tr)\n })\n }\n\n _prosemirrorChanged (doc) {\n this.mux(() => {\n this.doc.transact(() => {\n updateYFragment(this.doc, this.type, doc, this.mapping)\n this.beforeTransactionSelection = getRelativeSelection(this, this.prosemirrorView.state)\n }, ySyncPluginKey)\n })\n }\n\n destroy () {\n this.type.unobserveDeep(this._observeFunction)\n this.doc.off('beforeAllTransactions', this.beforeAllTransactions)\n this.doc.off('afterAllTransactions', this.afterAllTransactions)\n }\n}\n\n/**\n * @private\n * @param {Y.XmlElement | Y.XmlHook} el\n * @param {PMSchema} schema\n * @param {ProsemirrorMapping} mapping\n * @param {Y.Snapshot} [snapshot]\n * @param {Y.Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', Y.ID):any} [computeYChange]\n * @return {PMNode | null}\n */\nconst createNodeIfNotExists = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => {\n const node = /** @type {PMNode} */ (mapping.get(el))\n if (node === undefined) {\n if (el instanceof Y.XmlElement) {\n return createNodeFromYElement(el, schema, mapping, snapshot, prevSnapshot, computeYChange)\n } else {\n throw methodUnimplemented() // we are currently not handling hooks\n }\n }\n return node\n}\n\n/**\n * @private\n * @param {Y.XmlElement} el\n * @param {any} schema\n * @param {ProsemirrorMapping} mapping\n * @param {Y.Snapshot} [snapshot]\n * @param {Y.Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', Y.ID):any} [computeYChange]\n * @return {PMNode | null} Returns node if node could be created. Otherwise it deletes the yjs type and returns null\n */\nconst createNodeFromYElement = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => {\n const children = []\n const createChildren = type => {\n if (type.constructor === Y.XmlElement) {\n const n = createNodeIfNotExists(type, schema, mapping, snapshot, prevSnapshot, computeYChange)\n if (n !== null) {\n children.push(n)\n }\n } else {\n const ns = createTextNodesFromYText(type, schema, mapping, snapshot, prevSnapshot, computeYChange)\n if (ns !== null) {\n ns.forEach(textchild => {\n if (textchild !== null) {\n children.push(textchild)\n }\n })\n }\n }\n }\n if (snapshot === undefined || prevSnapshot === undefined) {\n el.toArray().forEach(createChildren)\n } else {\n Y.typeListToArraySnapshot(el, new Y.Snapshot(prevSnapshot.ds, snapshot.sv)).forEach(createChildren)\n }\n try {\n const attrs = el.getAttributes(snapshot)\n if (snapshot !== undefined) {\n if (!isVisible(/** @type {Y.Item} */ (el._item), snapshot)) {\n attrs.ychange = computeYChange ? computeYChange('removed', /** @type {Y.Item} */ (el._item).id) : { type: 'removed' }\n } else if (!isVisible(/** @type {Y.Item} */ (el._item), prevSnapshot)) {\n attrs.ychange = computeYChange ? computeYChange('added', /** @type {Y.Item} */ (el._item).id) : { type: 'added' }\n }\n }\n const node = schema.node(el.nodeName, attrs, children)\n mapping.set(el, node)\n return node\n } catch (e) {\n // an error occured while creating the node. This is probably a result of a concurrent action.\n /** @type {Y.Doc} */ (el.doc).transact(transaction => {\n /** @type {Y.Item} */ (el._item).delete(transaction)\n }, ySyncPluginKey)\n mapping.delete(el)\n return null\n }\n}\n\n/**\n * @private\n * @param {Y.XmlText} text\n * @param {any} schema\n * @param {ProsemirrorMapping} mapping\n * @param {Y.Snapshot} [snapshot]\n * @param {Y.Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', Y.ID):any} [computeYChange]\n * @return {Array|null}\n */\nconst createTextNodesFromYText = (text, schema, mapping, snapshot, prevSnapshot, computeYChange) => {\n const nodes = []\n const deltas = text.toDelta(snapshot, prevSnapshot, computeYChange)\n try {\n for (let i = 0; i < deltas.length; i++) {\n const delta = deltas[i]\n const marks = []\n for (const markName in delta.attributes) {\n marks.push(schema.mark(markName, delta.attributes[markName]))\n }\n nodes.push(schema.text(delta.insert, marks))\n }\n } catch (e) {\n // an error occured while creating the node. This is probably a result of a concurrent action.\n /** @type {Y.Doc} */ (text.doc).transact(transaction => {\n /** @type {Y.Item} */ (text._item).delete(transaction)\n }, ySyncPluginKey)\n return null\n }\n // @ts-ignore\n return nodes\n}\n\n/**\n * @private\n * @param {Array} nodes prosemirror node\n * @param {ProsemirrorMapping} mapping\n * @return {Y.XmlText}\n */\nconst createTypeFromTextNodes = (nodes, mapping) => {\n const type = new Y.XmlText()\n const delta = nodes.map(node => ({\n // @ts-ignore\n insert: node.text,\n attributes: marksToAttributes(node.marks)\n }))\n type.applyDelta(delta)\n mapping.set(type, nodes)\n return type\n}\n\n/**\n * @private\n * @param {any} node prosemirror node\n * @param {ProsemirrorMapping} mapping\n * @return {Y.XmlElement}\n */\nconst createTypeFromElementNode = (node, mapping) => {\n const type = new Y.XmlElement(node.type.name)\n for (const key in node.attrs) {\n const val = node.attrs[key]\n if (val !== null && key !== 'ychange') {\n type.setAttribute(key, val)\n }\n }\n type.insert(0, normalizePNodeContent(node).map(n => createTypeFromTextOrElementNode(n, mapping)))\n mapping.set(type, node)\n return type\n}\n\n/**\n * @private\n * @param {PMNode|Array} node prosemirror text node\n * @param {ProsemirrorMapping} mapping\n * @return {Y.XmlElement|Y.XmlText}\n */\nconst createTypeFromTextOrElementNode = (node, mapping) => node instanceof Array ? createTypeFromTextNodes(node, mapping) : createTypeFromElementNode(node, mapping)\n\nconst equalAttrs = (pattrs, yattrs) => {\n const keys = Object.keys(pattrs).filter(key => pattrs[key] !== null)\n let eq = keys.length === Object.keys(yattrs).filter(key => yattrs[key] !== null).length\n for (let i = 0; i < keys.length && eq; i++) {\n const key = keys[i]\n const l = pattrs[key]\n const r = yattrs[key]\n eq = key === 'ychange' || l === r || (typeof l === 'object' && typeof r === 'object' && equalAttrs(l, r))\n }\n return eq\n}\n\n/**\n * @typedef {Array|PMNode>} NormalizedPNodeContent\n */\n\n/**\n * @param {any} pnode\n * @return {NormalizedPNodeContent}\n */\nconst normalizePNodeContent = pnode => {\n const c = pnode.content.content\n const res = []\n for (let i = 0; i < c.length; i++) {\n const n = c[i]\n if (n.isText) {\n const textNodes = []\n for (let tnode = c[i]; i < c.length && tnode.isText; tnode = c[++i]) {\n textNodes.push(tnode)\n }\n i--\n res.push(textNodes)\n } else {\n res.push(n)\n }\n }\n return res\n}\n\n/**\n * @param {Y.XmlText} ytext\n * @param {Array} ptexts\n */\nconst equalYTextPText = (ytext, ptexts) => {\n const delta = ytext.toDelta()\n return delta.length === ptexts.length && delta.every((d, i) => d.insert === /** @type {any} */ (ptexts[i]).text && keys(d.attributes || {}).length === ptexts[i].marks.length && ptexts[i].marks.every(mark => equalAttrs(d.attributes[mark.type.name] || {}, mark.attrs)))\n}\n\n/**\n * @param {Y.XmlElement|Y.XmlText|Y.XmlHook} ytype\n * @param {any|Array} pnode\n */\nconst equalYTypePNode = (ytype, pnode) => {\n if (ytype instanceof Y.XmlElement && !(pnode instanceof Array) && matchNodeName(ytype, pnode)) {\n const normalizedContent = normalizePNodeContent(pnode)\n return ytype._length === normalizedContent.length && equalAttrs(ytype.getAttributes(), pnode.attrs) && ytype.toArray().every((ychild, i) => equalYTypePNode(ychild, normalizedContent[i]))\n }\n return ytype instanceof Y.XmlText && pnode instanceof Array && equalYTextPText(ytype, pnode)\n}\n\n/**\n * @param {PMNode | Array | undefined} mapped\n * @param {PMNode | Array} pcontent\n */\nconst mappedIdentity = (mapped, pcontent) => mapped === pcontent || (mapped instanceof Array && pcontent instanceof Array && mapped.length === pcontent.length && mapped.every((a, i) => pcontent[i] === a))\n\n/**\n * @param {Y.XmlElement} ytype\n * @param {PMNode} pnode\n * @param {ProsemirrorMapping} mapping\n * @return {{ foundMappedChild: boolean, equalityFactor: number }}\n */\nconst computeChildEqualityFactor = (ytype, pnode, mapping) => {\n const yChildren = ytype.toArray()\n const pChildren = normalizePNodeContent(pnode)\n const pChildCnt = pChildren.length\n const yChildCnt = yChildren.length\n const minCnt = min(yChildCnt, pChildCnt)\n let left = 0\n let right = 0\n let foundMappedChild = false\n for (; left < minCnt; left++) {\n const leftY = yChildren[left]\n const leftP = pChildren[left]\n if (mappedIdentity(mapping.get(leftY), leftP)) {\n foundMappedChild = true// definite (good) match!\n } else if (!equalYTypePNode(leftY, leftP)) {\n break\n }\n }\n for (; left + right < minCnt; right++) {\n const rightY = yChildren[yChildCnt - right - 1]\n const rightP = pChildren[pChildCnt - right - 1]\n if (mappedIdentity(mapping.get(rightY), rightP)) {\n foundMappedChild = true\n } else if (!equalYTypePNode(rightY, rightP)) {\n break\n }\n }\n return {\n equalityFactor: left + right,\n foundMappedChild\n }\n}\n\nconst ytextTrans = ytext => {\n let str = ''\n /**\n * @type {Y.Item|null}\n */\n let n = ytext._start\n const nAttrs = {}\n while (n !== null) {\n if (!n.deleted) {\n if (n.countable && n.content instanceof Y.ContentString) {\n str += n.content.str\n } else if (n.content instanceof Y.ContentFormat) {\n nAttrs[n.content.key] = null\n }\n }\n n = n.right\n }\n return {\n str,\n nAttrs\n }\n}\n\n/**\n * @todo test this more\n *\n * @param {Y.Text} ytext\n * @param {Array} ptexts\n * @param {ProsemirrorMapping} mapping\n */\nconst updateYText = (ytext, ptexts, mapping) => {\n mapping.set(ytext, ptexts)\n const { nAttrs, str } = ytextTrans(ytext)\n const content = ptexts.map(p => ({ insert: /** @type {any} */ (p).text, attributes: Object.assign({}, nAttrs, marksToAttributes(p.marks)) }))\n const { insert, remove, index } = simpleDiff(str, content.map(c => c.insert).join(''))\n ytext.delete(index, remove)\n ytext.insert(index, insert)\n ytext.applyDelta(content.map(c => ({ retain: c.insert.length, attributes: c.attributes })))\n}\n\nconst marksToAttributes = marks => {\n const pattrs = {}\n marks.forEach(mark => {\n if (mark.type.name !== 'ychange') {\n pattrs[mark.type.name] = mark.attrs\n }\n })\n return pattrs\n}\n\n/**\n * @private\n * @param {Y.Doc} y\n * @param {Y.XmlFragment} yDomFragment\n * @param {any} pNode\n * @param {ProsemirrorMapping} mapping\n */\nexport const updateYFragment = (y, yDomFragment, pNode, mapping) => {\n if (yDomFragment instanceof Y.XmlElement && yDomFragment.nodeName !== pNode.type.name) {\n throw new Error('node name mismatch!')\n }\n mapping.set(yDomFragment, pNode)\n // update attributes\n if (yDomFragment instanceof Y.XmlElement) {\n const yDomAttrs = yDomFragment.getAttributes()\n const pAttrs = pNode.attrs\n for (const key in pAttrs) {\n if (pAttrs[key] !== null) {\n if (yDomAttrs[key] !== pAttrs[key] && key !== 'ychange') {\n yDomFragment.setAttribute(key, pAttrs[key])\n }\n } else {\n yDomFragment.removeAttribute(key)\n }\n }\n // remove all keys that are no longer in pAttrs\n for (const key in yDomAttrs) {\n if (pAttrs[key] === undefined) {\n yDomFragment.removeAttribute(key)\n }\n }\n }\n // update children\n const pChildren = normalizePNodeContent(pNode)\n const pChildCnt = pChildren.length\n const yChildren = yDomFragment.toArray()\n const yChildCnt = yChildren.length\n const minCnt = min(pChildCnt, yChildCnt)\n let left = 0\n let right = 0\n // find number of matching elements from left\n for (;left < minCnt; left++) {\n const leftY = yChildren[left]\n const leftP = pChildren[left]\n if (!mappedIdentity(mapping.get(leftY), leftP)) {\n if (equalYTypePNode(leftY, leftP)) {\n // update mapping\n mapping.set(leftY, leftP)\n } else {\n break\n }\n }\n }\n // find number of matching elements from right\n for (;right + left + 1 < minCnt; right++) {\n const rightY = yChildren[yChildCnt - right - 1]\n const rightP = pChildren[pChildCnt - right - 1]\n if (!mappedIdentity(mapping.get(rightY), rightP)) {\n if (equalYTypePNode(rightY, rightP)) {\n // update mapping\n mapping.set(rightY, rightP)\n } else {\n break\n }\n }\n }\n y.transact(() => {\n // try to compare and update\n while (yChildCnt - left - right > 0 && pChildCnt - left - right > 0) {\n const leftY = yChildren[left]\n const leftP = pChildren[left]\n const rightY = yChildren[yChildCnt - right - 1]\n const rightP = pChildren[pChildCnt - right - 1]\n if (leftY instanceof Y.XmlText && leftP instanceof Array) {\n if (!equalYTextPText(leftY, leftP)) {\n updateYText(leftY, leftP, mapping)\n }\n left += 1\n } else {\n let updateLeft = leftY instanceof Y.XmlElement && matchNodeName(leftY, leftP)\n let updateRight = rightY instanceof Y.XmlElement && matchNodeName(rightY, rightP)\n if (updateLeft && updateRight) {\n // decide which which element to update\n const equalityLeft = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (leftY), /** @type {PMNode} */ (leftP), mapping)\n const equalityRight = computeChildEqualityFactor(/** @type {Y.XmlElement} */ (rightY), /** @type {PMNode} */ (rightP), mapping)\n if (equalityLeft.foundMappedChild && !equalityRight.foundMappedChild) {\n updateRight = false\n } else if (!equalityLeft.foundMappedChild && equalityRight.foundMappedChild) {\n updateLeft = false\n } else if (equalityLeft.equalityFactor < equalityRight.equalityFactor) {\n updateLeft = false\n } else {\n updateRight = false\n }\n }\n if (updateLeft) {\n updateYFragment(y, /** @type {Y.XmlFragment} */ (leftY), /** @type {PMNode} */ (leftP), mapping)\n left += 1\n } else if (updateRight) {\n updateYFragment(y, /** @type {Y.XmlFragment} */ (rightY), /** @type {PMNode} */ (rightP), mapping)\n right += 1\n } else {\n yDomFragment.delete(left, 1)\n yDomFragment.insert(left, [createTypeFromTextOrElementNode(leftP, mapping)])\n left += 1\n }\n }\n }\n const yDelLen = yChildCnt - left - right\n if (yDelLen > 0) {\n yDomFragment.delete(left, yDelLen)\n }\n if (left + right < pChildCnt) {\n const ins = []\n for (let i = left; i < pChildCnt - right; i++) {\n ins.push(createTypeFromTextOrElementNode(pChildren[i], mapping))\n }\n yDomFragment.insert(left, ins)\n }\n }, ySyncPluginKey)\n}\n\n/**\n * @function\n * @param {Y.XmlElement} yElement\n * @param {any} pNode Prosemirror Node\n */\nconst matchNodeName = (yElement, pNode) => !(pNode instanceof Array) && yElement.nodeName === pNode.type.name\n","import { updateYFragment } from './plugins/sync-plugin.js' // eslint-disable-line\nimport * as Y from 'yjs'\nimport { EditorView } from 'prosemirror-view' // eslint-disable-line\nimport { Node, Schema } from 'prosemirror-model' // eslint-disable-line\nimport * as error from 'lib0/error.js'\nimport * as map from 'lib0/map.js'\nimport * as eventloop from 'lib0/eventloop.js'\n\n/**\n * Either a node if type is YXmlElement or an Array of text nodes if YXmlText\n * @typedef {Map>} ProsemirrorMapping\n */\n\n/**\n * Is null if no timeout is in progress.\n * Is defined if a timeout is in progress.\n * Maps from view\n * @type {Map>|null}\n */\nlet viewsToUpdate = null\n\nconst updateMetas = () => {\n const ups = /** @type {Map>} */ (viewsToUpdate)\n viewsToUpdate = null\n ups.forEach((metas, view) => {\n const tr = view.state.tr\n metas.forEach((val, key) => {\n tr.setMeta(key, val)\n })\n view.dispatch(tr)\n })\n}\n\nexport const setMeta = (view, key, value) => {\n if (!viewsToUpdate) {\n viewsToUpdate = new Map()\n eventloop.timeout(0, updateMetas)\n }\n map.setIfUndefined(viewsToUpdate, view, map.create).set(key, value)\n}\n\n/**\n * Transforms a Prosemirror based absolute position to a Yjs Cursor (relative position in the Yjs model).\n *\n * @param {number} pos\n * @param {Y.XmlFragment} type\n * @param {ProsemirrorMapping} mapping\n * @return {any} relative position\n */\nexport const absolutePositionToRelativePosition = (pos, type, mapping) => {\n if (pos === 0) {\n return Y.createRelativePositionFromTypeIndex(type, 0)\n }\n let n = type._first === null ? null : /** @type {Y.ContentType} */ (type._first.content).type\n while (n !== null && type !== n) {\n if (n.constructor === Y.XmlText) {\n if (n._length >= pos) {\n return Y.createRelativePositionFromTypeIndex(n, pos)\n } else {\n pos -= n._length\n }\n if (n._item !== null && n._item.next !== null) {\n n = /** @type {Y.ContentType} */ (n._item.next.content).type\n } else {\n do {\n n = n._item === null ? null : n._item.parent\n pos--\n } while (n !== type && n !== null && n._item !== null && n._item.next === null)\n if (n !== null && n !== type) {\n // @ts-gnore we know that n.next !== null because of above loop conditition\n n = n._item === null ? null : /** @type {Y.ContentType} */ (/** @type Y.Item */ (n._item.next).content).type\n }\n }\n } else {\n const pNodeSize = /** @type {any} */ (mapping.get(n) || { nodeSize: 0 }).nodeSize\n if (n._first !== null && pos < pNodeSize) {\n n = /** @type {Y.ContentType} */ (n._first.content).type\n pos--\n } else {\n if (pos === 1 && n._length === 0 && pNodeSize > 1) {\n // edge case, should end in this paragraph\n return new Y.RelativePosition(n._item === null ? null : n._item.id, n._item === null ? Y.findRootTypeKey(n) : null, null)\n }\n pos -= pNodeSize\n if (n._item !== null && n._item.next !== null) {\n n = /** @type {Y.ContentType} */ (n._item.next.content).type\n } else {\n if (pos === 0) {\n // set to end of n.parent\n n = n._item === null ? n : n._item.parent\n return new Y.RelativePosition(n._item === null ? null : n._item.id, n._item === null ? Y.findRootTypeKey(n) : null, null)\n }\n do {\n n = /** @type {Y.Item} */ (n._item).parent\n pos--\n } while (n !== type && /** @type {Y.Item} */ (n._item).next === null)\n // if n is null at this point, we have an unexpected case\n if (n !== type) {\n // We know that n._item.next is defined because of above loop condition\n n = /** @type {Y.ContentType} */ (/** @type {Y.Item} */ (/** @type {Y.Item} */ (n._item).next).content).type\n }\n }\n }\n }\n if (n === null) {\n throw error.unexpectedCase()\n }\n if (pos === 0 && n.constructor !== Y.XmlText && n !== type) { // TODO: set to <= 0\n return createRelativePosition(n._item.parent, n._item)\n }\n }\n return Y.createRelativePositionFromTypeIndex(type, type._length)\n}\n\nconst createRelativePosition = (type, item) => {\n let typeid = null\n let tname = null\n if (type._item === null) {\n tname = Y.findRootTypeKey(type)\n } else {\n typeid = Y.createID(type._item.id.client, type._item.id.clock)\n }\n return new Y.RelativePosition(typeid, tname, item.id)\n}\n\n/**\n * @param {Y.Doc} y\n * @param {Y.XmlFragment} documentType Top level type that is bound to pView\n * @param {any} relPos Encoded Yjs based relative position\n * @param {ProsemirrorMapping} mapping\n * @return {null|number}\n */\nexport const relativePositionToAbsolutePosition = (y, documentType, relPos, mapping) => {\n const decodedPos = Y.createAbsolutePositionFromRelativePosition(relPos, y)\n if (decodedPos === null || (decodedPos.type !== documentType && !Y.isParentOf(documentType, decodedPos.type._item))) {\n return null\n }\n let type = decodedPos.type\n let pos = 0\n if (type.constructor === Y.XmlText) {\n pos = decodedPos.index\n } else if (type._item === null || !type._item.deleted) {\n let n = type._first\n let i = 0\n while (i < type._length && i < decodedPos.index && n !== null) {\n if (!n.deleted) {\n const t = /** @type {Y.ContentType} */ (n.content).type\n i++\n if (t.constructor === Y.XmlText) {\n pos += t._length\n } else {\n pos += /** @type {any} */ (mapping.get(t)).nodeSize\n }\n }\n n = /** @type {Y.Item} */ (n.right)\n }\n pos += 1 // increase because we go out of n\n }\n while (type !== documentType && type._item !== null) {\n // @ts-ignore\n const parent = type._item.parent\n // @ts-ignore\n if (parent._item === null || !parent._item.deleted) {\n pos += 1 // the start tag\n let n = parent._first\n // now iterate until we found type\n while (n !== null) {\n const contentType = /** @type {Y.ContentType} */ (n.content).type\n if (contentType === type) {\n break\n }\n if (!n.deleted) {\n if (contentType.constructor === Y.XmlText) {\n pos += contentType._length\n } else {\n pos += /** @type {any} */ (mapping.get(contentType)).nodeSize\n }\n }\n n = n.right\n }\n }\n type = parent\n }\n return pos - 1 // we don't count the most outer tag, because it is a fragment\n}\n\n/**\n * Utility method to convert a Prosemirror Doc Node into a Y.Doc.\n *\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param {Node} doc\n * @param {string} xmlFragment\n * @return {Y.Doc}\n */\nexport function prosemirrorToYDoc (doc, xmlFragment = 'prosemirror') {\n const ydoc = new Y.Doc()\n const type = ydoc.get(xmlFragment, Y.XmlFragment)\n if (!type.doc) {\n return ydoc\n }\n\n updateYFragment(type.doc, type, doc, new Map())\n return type.doc\n}\n\n/**\n * Utility method to convert Prosemirror compatible JSON into a Y.Doc.\n *\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param {Schema} schema\n * @param {any} state\n * @param {string} xmlFragment\n * @return {Y.Doc}\n */\nexport function prosemirrorJSONToYDoc (schema, state, xmlFragment = 'prosemirror') {\n const doc = Node.fromJSON(schema, state)\n return prosemirrorToYDoc(doc, xmlFragment)\n}\n\n/**\n * Utility method to convert a Y.Doc to a Prosemirror Doc node.\n *\n * @param {Schema} schema\n * @param {Y.Doc} ydoc\n * @return {Node}\n */\nexport function yDocToProsemirror (schema, ydoc) {\n const state = yDocToProsemirrorJSON(ydoc)\n return Node.fromJSON(schema, state)\n}\n\n/**\n * Utility method to convert a Y.Doc to Prosemirror compatible JSON.\n *\n * @param {Y.Doc} ydoc\n * @param {string} xmlFragment\n * @return {Record}\n */\nexport function yDocToProsemirrorJSON (\n ydoc,\n xmlFragment = 'prosemirror'\n) {\n const items = ydoc.getXmlFragment(xmlFragment).toArray()\n\n function serialize (item) {\n /**\n * @type {Object} NodeObject\n * @property {string} NodeObject.type\n * @property {Record=} NodeObject.attrs\n * @property {Array=} NodeObject.content\n */\n let response\n\n // TODO: Must be a better way to detect text nodes than this\n if (!item.nodeName) {\n const delta = item.toDelta()\n response = delta.map((d) => {\n const text = {\n type: 'text',\n text: d.insert\n }\n\n if (d.attributes) {\n text.marks = Object.keys(d.attributes).map((type) => {\n const attrs = d.attributes[type]\n const mark = {\n type\n }\n\n if (Object.keys(attrs)) {\n mark.attrs = attrs\n }\n\n return mark\n })\n }\n return text\n })\n } else {\n response = {\n type: item.nodeName\n }\n\n const attrs = item.getAttributes()\n if (Object.keys(attrs).length) {\n response.attrs = attrs\n }\n\n const children = item.toArray()\n if (children.length) {\n response.content = children.map(serialize).flat()\n }\n }\n\n return response\n }\n\n return {\n type: 'doc',\n content: items.map(serialize)\n }\n}\n","\nimport * as Y from 'yjs'\nimport { Decoration, DecorationSet } from 'prosemirror-view' // eslint-disable-line\nimport { Plugin } from 'prosemirror-state' // eslint-disable-line\nimport { Awareness } from 'y-protocols/awareness.js' // eslint-disable-line\nimport { absolutePositionToRelativePosition, relativePositionToAbsolutePosition, setMeta } from '../lib.js'\nimport { yCursorPluginKey, ySyncPluginKey } from './keys.js'\n\nimport * as math from 'lib0/math.js'\n\n/**\n * Default generator for a cursor element\n *\n * @param {any} user user data\n * @return HTMLElement\n */\nexport const defaultCursorBuilder = user => {\n const cursor = document.createElement('span')\n cursor.classList.add('ProseMirror-yjs-cursor')\n cursor.setAttribute('style', `border-color: ${user.color}`)\n const userDiv = document.createElement('div')\n userDiv.setAttribute('style', `background-color: ${user.color}`)\n userDiv.insertBefore(document.createTextNode(user.name), null)\n cursor.insertBefore(userDiv, null)\n return cursor\n}\n\n/**\n * @param {any} state\n * @param {Awareness} awareness\n * @return {any} DecorationSet\n */\nexport const createDecorations = (state, awareness, createCursor) => {\n const ystate = ySyncPluginKey.getState(state)\n const y = ystate.doc\n const decorations = []\n if (ystate.snapshot != null || ystate.prevSnapshot != null || ystate.binding === null) {\n // do not render cursors while snapshot is active\n return DecorationSet.create(state.doc, [])\n }\n awareness.getStates().forEach((aw, clientId) => {\n if (clientId === y.clientID) {\n return\n }\n if (aw.cursor != null) {\n const user = aw.user || {}\n if (user.color == null) {\n user.color = '#ffa500'\n }\n if (user.name == null) {\n user.name = `User: ${clientId}`\n }\n let anchor = relativePositionToAbsolutePosition(y, ystate.type, Y.createRelativePositionFromJSON(aw.cursor.anchor), ystate.binding.mapping)\n let head = relativePositionToAbsolutePosition(y, ystate.type, Y.createRelativePositionFromJSON(aw.cursor.head), ystate.binding.mapping)\n if (anchor !== null && head !== null) {\n const maxsize = math.max(state.doc.content.size - 1, 0)\n anchor = math.min(anchor, maxsize)\n head = math.min(head, maxsize)\n decorations.push(Decoration.widget(head, () => createCursor(user), { key: clientId + '', side: 10 }))\n const from = math.min(anchor, head)\n const to = math.max(anchor, head)\n decorations.push(Decoration.inline(from, to, { style: `background-color: ${user.color}70` }, { inclusiveEnd: true, inclusiveStart: false }))\n }\n }\n })\n return DecorationSet.create(state.doc, decorations)\n}\n\n/**\n * A prosemirror plugin that listens to awareness information on Yjs.\n * This requires that a `prosemirrorPlugin` is also bound to the prosemirror.\n *\n * @public\n * @param {Awareness} awareness\n * @param {object} [opts]\n * @param {function(any):HTMLElement} [opts.cursorBuilder]\n * @param {function(any):any} [opts.getSelection]\n * @param {string} [opts.cursorStateField] By default all editor bindings use the awareness 'cursor' field to propagate cursor information.\n * @return {any}\n */\nexport const yCursorPlugin = (awareness, { cursorBuilder = defaultCursorBuilder, getSelection = state => state.selection } = {}, cursorStateField = 'cursor') => new Plugin({\n key: yCursorPluginKey,\n state: {\n init (_, state) {\n return createDecorations(state, awareness, cursorBuilder)\n },\n apply (tr, prevState, oldState, newState) {\n const ystate = ySyncPluginKey.getState(newState)\n const yCursorState = tr.getMeta(yCursorPluginKey)\n if ((ystate && ystate.isChangeOrigin) || (yCursorState && yCursorState.awarenessUpdated)) {\n return createDecorations(newState, awareness, cursorBuilder)\n }\n return prevState.map(tr.mapping, tr.doc)\n }\n },\n props: {\n decorations: state => {\n return yCursorPluginKey.getState(state)\n }\n },\n view: view => {\n const awarenessListener = () => {\n // @ts-ignore\n if (view.docView) {\n setMeta(view, yCursorPluginKey, { awarenessUpdated: true })\n }\n }\n const updateCursorInfo = () => {\n const ystate = ySyncPluginKey.getState(view.state)\n // @note We make implicit checks when checking for the cursor property\n const current = awareness.getLocalState() || {}\n if (view.hasFocus() && ystate.binding !== null) {\n const selection = getSelection(view.state)\n /**\n * @type {Y.RelativePosition}\n */\n const anchor = absolutePositionToRelativePosition(selection.anchor, ystate.type, ystate.binding.mapping)\n /**\n * @type {Y.RelativePosition}\n */\n const head = absolutePositionToRelativePosition(selection.head, ystate.type, ystate.binding.mapping)\n if (current.cursor == null || !Y.compareRelativePositions(Y.createRelativePositionFromJSON(current.cursor.anchor), anchor) || !Y.compareRelativePositions(Y.createRelativePositionFromJSON(current.cursor.head), head)) {\n awareness.setLocalStateField(cursorStateField, {\n anchor, head\n })\n }\n } else if (current.cursor != null && relativePositionToAbsolutePosition(ystate.doc, ystate.type, Y.createRelativePositionFromJSON(current.cursor.anchor), ystate.binding.mapping) !== null) {\n // delete cursor information if current cursor information is owned by this editor binding\n awareness.setLocalStateField(cursorStateField, null)\n }\n }\n awareness.on('change', awarenessListener)\n view.dom.addEventListener('focusin', updateCursorInfo)\n view.dom.addEventListener('focusout', updateCursorInfo)\n return {\n update: updateCursorInfo,\n destroy: () => {\n view.dom.removeEventListener('focusin', updateCursorInfo)\n view.dom.removeEventListener('focusout', updateCursorInfo)\n awareness.off('change', awarenessListener)\n awareness.setLocalStateField(cursorStateField, null)\n }\n }\n }\n})\n","\nimport { Plugin, PluginKey } from 'prosemirror-state' // eslint-disable-line\n\nimport { getRelativeSelection } from './sync-plugin.js'\nimport { UndoManager, Item, ContentType, XmlElement, Text } from 'yjs'\nimport { yUndoPluginKey, ySyncPluginKey } from './keys.js'\n\nexport const undo = state => {\n const undoManager = yUndoPluginKey.getState(state).undoManager\n if (undoManager != null) {\n undoManager.undo()\n return true\n }\n}\n\nexport const redo = state => {\n const undoManager = yUndoPluginKey.getState(state).undoManager\n if (undoManager != null) {\n undoManager.redo()\n return true\n }\n}\n\nexport const yUndoPlugin = ({ protectedNodes = new Set(['paragraph']), trackedOrigins = [] } = {}) => new Plugin({\n key: yUndoPluginKey,\n state: {\n init: (initargs, state) => {\n // TODO: check if plugin order matches and fix\n const ystate = ySyncPluginKey.getState(state)\n const undoManager = new UndoManager(ystate.type, {\n trackedOrigins: new Set([ySyncPluginKey].concat(trackedOrigins)),\n deleteFilter: item => !(item instanceof Item) ||\n !(item.content instanceof ContentType) ||\n !(item.content.type instanceof Text ||\n (item.content.type instanceof XmlElement && protectedNodes.has(item.content.type.nodeName))) ||\n item.content.type._length === 0\n })\n return {\n undoManager,\n prevSel: null,\n hasUndoOps: undoManager.undoStack.length > 0,\n hasRedoOps: undoManager.redoStack.length > 0\n }\n },\n apply: (tr, val, oldState, state) => {\n const binding = ySyncPluginKey.getState(state).binding\n const undoManager = val.undoManager\n const hasUndoOps = undoManager.undoStack.length > 0\n const hasRedoOps = undoManager.redoStack.length > 0\n if (binding) {\n return {\n undoManager,\n prevSel: getRelativeSelection(binding, oldState),\n hasUndoOps,\n hasRedoOps\n }\n } else {\n if (hasUndoOps !== val.hasUndoOps || hasRedoOps !== val.hasRedoOps) {\n return Object.assign({}, val, {\n hasUndoOps: undoManager.undoStack.length > 0,\n hasRedoOps: undoManager.redoStack.length > 0\n })\n } else { // nothing changed\n return val\n }\n }\n }\n },\n view: view => {\n const ystate = ySyncPluginKey.getState(view.state)\n const undoManager = yUndoPluginKey.getState(view.state).undoManager\n undoManager.on('stack-item-added', ({ stackItem }) => {\n const binding = ystate.binding\n if (binding) {\n stackItem.meta.set(binding, yUndoPluginKey.getState(view.state).prevSel)\n }\n })\n undoManager.on('stack-item-popped', ({ stackItem }) => {\n const binding = ystate.binding\n if (binding) {\n binding.beforeTransactionSelection = stackItem.meta.get(binding) || binding.beforeTransactionSelection\n }\n })\n return {\n destroy: () => {\n undoManager.destroy()\n }\n }\n }\n})\n","import { Schema } from 'prosemirror-model'\n\nconst brDOM = ['br']\n\nconst calcYchangeDomAttrs = (attrs, domAttrs = {}) => {\n domAttrs = Object.assign({}, domAttrs)\n if (attrs.ychange !== null) {\n domAttrs.ychange_user = attrs.ychange.user\n domAttrs.ychange_state = attrs.ychange.state\n }\n return domAttrs\n}\n\n// :: Object\n// [Specs](#model.NodeSpec) for the nodes defined in this schema.\nexport const nodes = {\n // :: NodeSpec The top level document node.\n doc: {\n content: 'block+'\n },\n\n // :: NodeSpec A plain paragraph textblock. Represented in the DOM\n // as a `

` element.\n paragraph: {\n attrs: { ychange: { default: null } },\n content: 'inline*',\n group: 'block',\n parseDOM: [{ tag: 'p' }],\n toDOM (node) { return ['p', calcYchangeDomAttrs(node.attrs), 0] }\n },\n\n // :: NodeSpec A blockquote (`

`) wrapping one or more blocks.\n blockquote: {\n attrs: { ychange: { default: null } },\n content: 'block+',\n group: 'block',\n defining: true,\n parseDOM: [{ tag: 'blockquote' }],\n toDOM (node) { return ['blockquote', calcYchangeDomAttrs(node.attrs), 0] }\n },\n\n // :: NodeSpec A horizontal rule (`
`).\n horizontal_rule: {\n attrs: { ychange: { default: null } },\n group: 'block',\n parseDOM: [{ tag: 'hr' }],\n toDOM (node) {\n return ['hr', calcYchangeDomAttrs(node.attrs)]\n }\n },\n\n // :: NodeSpec A heading textblock, with a `level` attribute that\n // should hold the number 1 to 6. Parsed and serialized as `

` to\n // `

` elements.\n heading: {\n attrs: {\n level: { default: 1 },\n ychange: { default: null }\n },\n content: 'inline*',\n group: 'block',\n defining: true,\n parseDOM: [{ tag: 'h1', attrs: { level: 1 } },\n { tag: 'h2', attrs: { level: 2 } },\n { tag: 'h3', attrs: { level: 3 } },\n { tag: 'h4', attrs: { level: 4 } },\n { tag: 'h5', attrs: { level: 5 } },\n { tag: 'h6', attrs: { level: 6 } }],\n toDOM (node) { return ['h' + node.attrs.level, calcYchangeDomAttrs(node.attrs), 0] }\n },\n\n // :: NodeSpec A code listing. Disallows marks or non-text inline\n // nodes by default. Represented as a `
` element with a\n  // `` element inside of it.\n  code_block: {\n    attrs: { ychange: { default: null } },\n    content: 'text*',\n    marks: '',\n    group: 'block',\n    code: true,\n    defining: true,\n    parseDOM: [{ tag: 'pre', preserveWhitespace: 'full' }],\n    toDOM (node) { return ['pre', calcYchangeDomAttrs(node.attrs), ['code', 0]] }\n  },\n\n  // :: NodeSpec The text node.\n  text: {\n    group: 'inline'\n  },\n\n  // :: NodeSpec An inline image (``) node. Supports `src`,\n  // `alt`, and `href` attributes. The latter two default to the empty\n  // string.\n  image: {\n    inline: true,\n    attrs: {\n      ychange: { default: null },\n      src: {},\n      alt: { default: null },\n      title: { default: null }\n    },\n    group: 'inline',\n    draggable: true,\n    parseDOM: [{\n      tag: 'img[src]',\n      getAttrs (dom) {\n        return {\n          src: dom.getAttribute('src'),\n          title: dom.getAttribute('title'),\n          alt: dom.getAttribute('alt')\n        }\n      }\n    }],\n    toDOM (node) {\n      const domAttrs = {\n        src: node.attrs.src,\n        title: node.attrs.title,\n        alt: node.attrs.alt\n      }\n      return ['img', calcYchangeDomAttrs(node.attrs, domAttrs)]\n    }\n  },\n\n  // :: NodeSpec A hard line break, represented in the DOM as `
`.\n hard_break: {\n inline: true,\n group: 'inline',\n selectable: false,\n parseDOM: [{ tag: 'br' }],\n toDOM () { return brDOM }\n }\n}\n\nconst emDOM = ['em', 0]; const strongDOM = ['strong', 0]; const codeDOM = ['code', 0]\n\n// :: Object [Specs](#model.MarkSpec) for the marks in the schema.\nexport const marks = {\n // :: MarkSpec A link. Has `href` and `title` attributes. `title`\n // defaults to the empty string. Rendered and parsed as an ``\n // element.\n link: {\n attrs: {\n href: {},\n title: { default: null }\n },\n inclusive: false,\n parseDOM: [{\n tag: 'a[href]',\n getAttrs (dom) {\n return { href: dom.getAttribute('href'), title: dom.getAttribute('title') }\n }\n }],\n toDOM (node) { return ['a', node.attrs, 0] }\n },\n\n // :: MarkSpec An emphasis mark. Rendered as an `` element.\n // Has parse rules that also match `` and `font-style: italic`.\n em: {\n parseDOM: [{ tag: 'i' }, { tag: 'em' }, { style: 'font-style=italic' }],\n toDOM () { return emDOM }\n },\n\n // :: MarkSpec A strong mark. Rendered as ``, parse rules\n // also match `` and `font-weight: bold`.\n strong: {\n parseDOM: [{ tag: 'strong' },\n // This works around a Google Docs misbehavior where\n // pasted content will be inexplicably wrapped in ``\n // tags with a font-weight normal.\n { tag: 'b', getAttrs: node => node.style.fontWeight !== 'normal' && null },\n { style: 'font-weight', getAttrs: value => /^(bold(er)?|[5-9]\\d{2,})$/.test(value) && null }],\n toDOM () { return strongDOM }\n },\n\n // :: MarkSpec Code font mark. Represented as a `` element.\n code: {\n parseDOM: [{ tag: 'code' }],\n toDOM () { return codeDOM }\n },\n ychange: {\n attrs: {\n user: { default: null },\n state: { default: null }\n },\n inclusive: false,\n parseDOM: [{ tag: 'ychange' }],\n toDOM (node) {\n return ['ychange', { ychange_user: node.attrs.user, ychange_state: node.attrs.state }, 0]\n }\n }\n}\n\n// :: Schema\n// This schema rougly corresponds to the document schema used by\n// [CommonMark](http://commonmark.org/), minus the list elements,\n// which are defined in the [`prosemirror-schema-list`](#schema-list)\n// module.\n//\n// To reuse elements from this schema, extend or read from its\n// `spec.nodes` and `spec.marks` [properties](#model.Schema.spec).\nexport const schema = new Schema({ nodes, marks })\n","export var base = {\n 8: \"Backspace\",\n 9: \"Tab\",\n 10: \"Enter\",\n 12: \"NumLock\",\n 13: \"Enter\",\n 16: \"Shift\",\n 17: \"Control\",\n 18: \"Alt\",\n 20: \"CapsLock\",\n 27: \"Escape\",\n 32: \" \",\n 33: \"PageUp\",\n 34: \"PageDown\",\n 35: \"End\",\n 36: \"Home\",\n 37: \"ArrowLeft\",\n 38: \"ArrowUp\",\n 39: \"ArrowRight\",\n 40: \"ArrowDown\",\n 44: \"PrintScreen\",\n 45: \"Insert\",\n 46: \"Delete\",\n 59: \";\",\n 61: \"=\",\n 91: \"Meta\",\n 92: \"Meta\",\n 106: \"*\",\n 107: \"+\",\n 108: \",\",\n 109: \"-\",\n 110: \".\",\n 111: \"/\",\n 144: \"NumLock\",\n 145: \"ScrollLock\",\n 160: \"Shift\",\n 161: \"Shift\",\n 162: \"Control\",\n 163: \"Control\",\n 164: \"Alt\",\n 165: \"Alt\",\n 173: \"-\",\n 186: \";\",\n 187: \"=\",\n 188: \",\",\n 189: \"-\",\n 190: \".\",\n 191: \"/\",\n 192: \"`\",\n 219: \"[\",\n 220: \"\\\\\",\n 221: \"]\",\n 222: \"'\",\n 229: \"q\"\n}\n\nexport var shift = {\n 48: \")\",\n 49: \"!\",\n 50: \"@\",\n 51: \"#\",\n 52: \"$\",\n 53: \"%\",\n 54: \"^\",\n 55: \"&\",\n 56: \"*\",\n 57: \"(\",\n 59: \":\",\n 61: \"+\",\n 173: \"_\",\n 186: \":\",\n 187: \"+\",\n 188: \"<\",\n 189: \"_\",\n 190: \">\",\n 191: \"?\",\n 192: \"~\",\n 219: \"{\",\n 220: \"|\",\n 221: \"}\",\n 222: \"\\\"\",\n 229: \"Q\"\n}\n\nvar chrome = typeof navigator != \"undefined\" && /Chrome\\/(\\d+)/.exec(navigator.userAgent)\nvar safari = typeof navigator != \"undefined\" && /Apple Computer/.test(navigator.vendor)\nvar gecko = typeof navigator != \"undefined\" && /Gecko\\/\\d+/.test(navigator.userAgent)\nvar mac = typeof navigator != \"undefined\" && /Mac/.test(navigator.platform)\nvar ie = typeof navigator != \"undefined\" && /MSIE \\d|Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(navigator.userAgent)\nvar brokenModifierNames = chrome && (mac || +chrome[1] < 57) || gecko && mac\n\n// Fill in the digit keys\nfor (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i)\n\n// The function keys\nfor (var i = 1; i <= 24; i++) base[i + 111] = \"F\" + i\n\n// And the alphabetic keys\nfor (var i = 65; i <= 90; i++) {\n base[i] = String.fromCharCode(i + 32)\n shift[i] = String.fromCharCode(i)\n}\n\n// For each code that doesn't have a shift-equivalent, copy the base name\nfor (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]\n\nexport function keyName(event) {\n // Don't trust event.key in Chrome when there are modifiers until\n // they fix https://bugs.chromium.org/p/chromium/issues/detail?id=633838\n var ignoreKey = brokenModifierNames && (event.ctrlKey || event.altKey || event.metaKey) ||\n (safari || ie) && event.shiftKey && event.key && event.key.length == 1\n var name = (!ignoreKey && event.key) ||\n (event.shiftKey ? shift : base)[event.keyCode] ||\n event.key || \"Unidentified\"\n // Edge sometimes produces wrong names (Issue #3)\n if (name == \"Esc\") name = \"Escape\"\n if (name == \"Del\") name = \"Delete\"\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/\n if (name == \"Left\") name = \"ArrowLeft\"\n if (name == \"Up\") name = \"ArrowUp\"\n if (name == \"Right\") name = \"ArrowRight\"\n if (name == \"Down\") name = \"ArrowDown\"\n return name\n}\n","import { keyName, base } from 'w3c-keyname';\nimport { Plugin } from 'prosemirror-state';\n\n// declare global: navigator\n\nvar mac = typeof navigator != \"undefined\" ? /Mac/.test(navigator.platform) : false;\n\nfunction normalizeKeyName(name) {\n var parts = name.split(/-(?!$)/), result = parts[parts.length - 1];\n if (result == \"Space\") { result = \" \"; }\n var alt, ctrl, shift, meta;\n for (var i = 0; i < parts.length - 1; i++) {\n var mod = parts[i];\n if (/^(cmd|meta|m)$/i.test(mod)) { meta = true; }\n else if (/^a(lt)?$/i.test(mod)) { alt = true; }\n else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }\n else if (/^s(hift)?$/i.test(mod)) { shift = true; }\n else if (/^mod$/i.test(mod)) { if (mac) { meta = true; } else { ctrl = true; } }\n else { throw new Error(\"Unrecognized modifier name: \" + mod) }\n }\n if (alt) { result = \"Alt-\" + result; }\n if (ctrl) { result = \"Ctrl-\" + result; }\n if (meta) { result = \"Meta-\" + result; }\n if (shift) { result = \"Shift-\" + result; }\n return result\n}\n\nfunction normalize(map) {\n var copy = Object.create(null);\n for (var prop in map) { copy[normalizeKeyName(prop)] = map[prop]; }\n return copy\n}\n\nfunction modifiers(name, event, shift) {\n if (event.altKey) { name = \"Alt-\" + name; }\n if (event.ctrlKey) { name = \"Ctrl-\" + name; }\n if (event.metaKey) { name = \"Meta-\" + name; }\n if (shift !== false && event.shiftKey) { name = \"Shift-\" + name; }\n return name\n}\n\n// :: (Object) → Plugin\n// Create a keymap plugin for the given set of bindings.\n//\n// Bindings should map key names to [command](#commands)-style\n// functions, which will be called with `(EditorState, dispatch,\n// EditorView)` arguments, and should return true when they've handled\n// the key. Note that the view argument isn't part of the command\n// protocol, but can be used as an escape hatch if a binding needs to\n// directly interact with the UI.\n//\n// Key names may be strings like `\"Shift-Ctrl-Enter\"`—a key\n// identifier prefixed with zero or more modifiers. Key identifiers\n// are based on the strings that can appear in\n// [`KeyEvent.key`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key).\n// Use lowercase letters to refer to letter keys (or uppercase letters\n// if you want shift to be held). You may use `\"Space\"` as an alias\n// for the `\" \"` name.\n//\n// Modifiers can be given in any order. `Shift-` (or `s-`), `Alt-` (or\n// `a-`), `Ctrl-` (or `c-` or `Control-`) and `Cmd-` (or `m-` or\n// `Meta-`) are recognized. For characters that are created by holding\n// shift, the `Shift-` prefix is implied, and should not be added\n// explicitly.\n//\n// You can use `Mod-` as a shorthand for `Cmd-` on Mac and `Ctrl-` on\n// other platforms.\n//\n// You can add multiple keymap plugins to an editor. The order in\n// which they appear determines their precedence (the ones early in\n// the array get to dispatch first).\nfunction keymap(bindings) {\n return new Plugin({props: {handleKeyDown: keydownHandler(bindings)}})\n}\n\n// :: (Object) → (view: EditorView, event: dom.Event) → bool\n// Given a set of bindings (using the same format as\n// [`keymap`](#keymap.keymap), return a [keydown\n// handler](#view.EditorProps.handleKeyDown) that handles them.\nfunction keydownHandler(bindings) {\n var map = normalize(bindings);\n return function(view, event) {\n var name = keyName(event), isChar = name.length == 1 && name != \" \", baseName;\n var direct = map[modifiers(name, event, !isChar)];\n if (direct && direct(view.state, view.dispatch, view)) { return true }\n if (isChar && (event.shiftKey || event.altKey || event.metaKey || name.charCodeAt(0) > 127) &&\n (baseName = base[event.keyCode]) && baseName != name) {\n // Try falling back to the keyCode when there's a modifier\n // active or the character produced isn't ASCII, and our table\n // produces a different name from the the keyCode. See #668,\n // #1060\n var fromCode = map[modifiers(baseName, event, true)];\n if (fromCode && fromCode(view.state, view.dispatch, view)) { return true }\n } else if (isChar && event.shiftKey) {\n // Otherwise, if shift is active, also try the binding with the\n // Shift- prefix enabled. See #997\n var withShift = map[modifiers(name, event, true)];\n if (withShift && withShift(view.state, view.dispatch, view)) { return true }\n }\n return false\n }\n}\n\nexport { keydownHandler, keymap };\n//# sourceMappingURL=index.es.js.map\n","var GOOD_LEAF_SIZE = 200;\n\n// :: class A rope sequence is a persistent sequence data structure\n// that supports appending, prepending, and slicing without doing a\n// full copy. It is represented as a mostly-balanced tree.\nvar RopeSequence = function RopeSequence () {};\n\nRopeSequence.prototype.append = function append (other) {\n if (!other.length) { return this }\n other = RopeSequence.from(other);\n\n return (!this.length && other) ||\n (other.length < GOOD_LEAF_SIZE && this.leafAppend(other)) ||\n (this.length < GOOD_LEAF_SIZE && other.leafPrepend(this)) ||\n this.appendInner(other)\n};\n\n// :: (union<[T], RopeSequence>) → RopeSequence\n// Prepend an array or other rope to this one, returning a new rope.\nRopeSequence.prototype.prepend = function prepend (other) {\n if (!other.length) { return this }\n return RopeSequence.from(other).append(this)\n};\n\nRopeSequence.prototype.appendInner = function appendInner (other) {\n return new Append(this, other)\n};\n\n// :: (?number, ?number) → RopeSequence\n// Create a rope repesenting a sub-sequence of this rope.\nRopeSequence.prototype.slice = function slice (from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.length;\n\n if (from >= to) { return RopeSequence.empty }\n return this.sliceInner(Math.max(0, from), Math.min(this.length, to))\n};\n\n// :: (number) → T\n// Retrieve the element at the given position from this rope.\nRopeSequence.prototype.get = function get (i) {\n if (i < 0 || i >= this.length) { return undefined }\n return this.getInner(i)\n};\n\n// :: ((element: T, index: number) → ?bool, ?number, ?number)\n// Call the given function for each element between the given\n// indices. This tends to be more efficient than looping over the\n// indices and calling `get`, because it doesn't have to descend the\n// tree for every element.\nRopeSequence.prototype.forEach = function forEach (f, from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.length;\n\n if (from <= to)\n { this.forEachInner(f, from, to, 0); }\n else\n { this.forEachInvertedInner(f, from, to, 0); }\n};\n\n// :: ((element: T, index: number) → U, ?number, ?number) → [U]\n// Map the given functions over the elements of the rope, producing\n// a flat array.\nRopeSequence.prototype.map = function map (f, from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.length;\n\n var result = [];\n this.forEach(function (elt, i) { return result.push(f(elt, i)); }, from, to);\n return result\n};\n\n// :: (?union<[T], RopeSequence>) → RopeSequence\n// Create a rope representing the given array, or return the rope\n// itself if a rope was given.\nRopeSequence.from = function from (values) {\n if (values instanceof RopeSequence) { return values }\n return values && values.length ? new Leaf(values) : RopeSequence.empty\n};\n\nvar Leaf = /*@__PURE__*/(function (RopeSequence) {\n function Leaf(values) {\n RopeSequence.call(this);\n this.values = values;\n }\n\n if ( RopeSequence ) Leaf.__proto__ = RopeSequence;\n Leaf.prototype = Object.create( RopeSequence && RopeSequence.prototype );\n Leaf.prototype.constructor = Leaf;\n\n var prototypeAccessors = { length: { configurable: true },depth: { configurable: true } };\n\n Leaf.prototype.flatten = function flatten () {\n return this.values\n };\n\n Leaf.prototype.sliceInner = function sliceInner (from, to) {\n if (from == 0 && to == this.length) { return this }\n return new Leaf(this.values.slice(from, to))\n };\n\n Leaf.prototype.getInner = function getInner (i) {\n return this.values[i]\n };\n\n Leaf.prototype.forEachInner = function forEachInner (f, from, to, start) {\n for (var i = from; i < to; i++)\n { if (f(this.values[i], start + i) === false) { return false } }\n };\n\n Leaf.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {\n for (var i = from - 1; i >= to; i--)\n { if (f(this.values[i], start + i) === false) { return false } }\n };\n\n Leaf.prototype.leafAppend = function leafAppend (other) {\n if (this.length + other.length <= GOOD_LEAF_SIZE)\n { return new Leaf(this.values.concat(other.flatten())) }\n };\n\n Leaf.prototype.leafPrepend = function leafPrepend (other) {\n if (this.length + other.length <= GOOD_LEAF_SIZE)\n { return new Leaf(other.flatten().concat(this.values)) }\n };\n\n prototypeAccessors.length.get = function () { return this.values.length };\n\n prototypeAccessors.depth.get = function () { return 0 };\n\n Object.defineProperties( Leaf.prototype, prototypeAccessors );\n\n return Leaf;\n}(RopeSequence));\n\n// :: RopeSequence\n// The empty rope sequence.\nRopeSequence.empty = new Leaf([]);\n\nvar Append = /*@__PURE__*/(function (RopeSequence) {\n function Append(left, right) {\n RopeSequence.call(this);\n this.left = left;\n this.right = right;\n this.length = left.length + right.length;\n this.depth = Math.max(left.depth, right.depth) + 1;\n }\n\n if ( RopeSequence ) Append.__proto__ = RopeSequence;\n Append.prototype = Object.create( RopeSequence && RopeSequence.prototype );\n Append.prototype.constructor = Append;\n\n Append.prototype.flatten = function flatten () {\n return this.left.flatten().concat(this.right.flatten())\n };\n\n Append.prototype.getInner = function getInner (i) {\n return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length)\n };\n\n Append.prototype.forEachInner = function forEachInner (f, from, to, start) {\n var leftLen = this.left.length;\n if (from < leftLen &&\n this.left.forEachInner(f, from, Math.min(to, leftLen), start) === false)\n { return false }\n if (to > leftLen &&\n this.right.forEachInner(f, Math.max(from - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false)\n { return false }\n };\n\n Append.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {\n var leftLen = this.left.length;\n if (from > leftLen &&\n this.right.forEachInvertedInner(f, from - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false)\n { return false }\n if (to < leftLen &&\n this.left.forEachInvertedInner(f, Math.min(from, leftLen), to, start) === false)\n { return false }\n };\n\n Append.prototype.sliceInner = function sliceInner (from, to) {\n if (from == 0 && to == this.length) { return this }\n var leftLen = this.left.length;\n if (to <= leftLen) { return this.left.slice(from, to) }\n if (from >= leftLen) { return this.right.slice(from - leftLen, to - leftLen) }\n return this.left.slice(from, leftLen).append(this.right.slice(0, to - leftLen))\n };\n\n Append.prototype.leafAppend = function leafAppend (other) {\n var inner = this.right.leafAppend(other);\n if (inner) { return new Append(this.left, inner) }\n };\n\n Append.prototype.leafPrepend = function leafPrepend (other) {\n var inner = this.left.leafPrepend(other);\n if (inner) { return new Append(inner, this.right) }\n };\n\n Append.prototype.appendInner = function appendInner (other) {\n if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1)\n { return new Append(this.left, new Append(this.right, other)) }\n return new Append(this, other)\n };\n\n return Append;\n}(RopeSequence));\n\nvar ropeSequence = RopeSequence;\n\nexport default ropeSequence;\n","import RopeSequence from 'rope-sequence';\nimport { Mapping } from 'prosemirror-transform';\nimport { PluginKey, Plugin } from 'prosemirror-state';\n\n// ProseMirror's history isn't simply a way to roll back to a previous\n// state, because ProseMirror supports applying changes without adding\n// them to the history (for example during collaboration).\n//\n// To this end, each 'Branch' (one for the undo history and one for\n// the redo history) keeps an array of 'Items', which can optionally\n// hold a step (an actual undoable change), and always hold a position\n// map (which is needed to move changes below them to apply to the\n// current document).\n//\n// An item that has both a step and a selection bookmark is the start\n// of an 'event' — a group of changes that will be undone or redone at\n// once. (It stores only the bookmark, since that way we don't have to\n// provide a document until the selection is actually applied, which\n// is useful when compressing.)\n\n// Used to schedule history compression\nvar max_empty_items = 500;\n\nvar Branch = function Branch(items, eventCount) {\n this.items = items;\n this.eventCount = eventCount;\n};\n\n// : (EditorState, bool) → ?{transform: Transform, selection: ?SelectionBookmark, remaining: Branch}\n// Pop the latest event off the branch's history and apply it\n// to a document transform.\nBranch.prototype.popEvent = function popEvent (state, preserveItems) {\n var this$1 = this;\n\n if (this.eventCount == 0) { return null }\n\n var end = this.items.length;\n for (;; end--) {\n var next = this.items.get(end - 1);\n if (next.selection) { --end; break }\n }\n\n var remap, mapFrom;\n if (preserveItems) {\n remap = this.remapping(end, this.items.length);\n mapFrom = remap.maps.length;\n }\n var transform = state.tr;\n var selection, remaining;\n var addAfter = [], addBefore = [];\n\n this.items.forEach(function (item, i) {\n if (!item.step) {\n if (!remap) {\n remap = this$1.remapping(end, i + 1);\n mapFrom = remap.maps.length;\n }\n mapFrom--;\n addBefore.push(item);\n return\n }\n\n if (remap) {\n addBefore.push(new Item(item.map));\n var step = item.step.map(remap.slice(mapFrom)), map;\n\n if (step && transform.maybeStep(step).doc) {\n map = transform.mapping.maps[transform.mapping.maps.length - 1];\n addAfter.push(new Item(map, null, null, addAfter.length + addBefore.length));\n }\n mapFrom--;\n if (map) { remap.appendMap(map, mapFrom); }\n } else {\n transform.maybeStep(item.step);\n }\n\n if (item.selection) {\n selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection;\n remaining = new Branch(this$1.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this$1.eventCount - 1);\n return false\n }\n }, this.items.length, 0);\n\n return {remaining: remaining, transform: transform, selection: selection}\n};\n\n// : (Transform, ?SelectionBookmark, Object) → Branch\n// Create a new branch with the given transform added.\nBranch.prototype.addTransform = function addTransform (transform, selection, histOptions, preserveItems) {\n var newItems = [], eventCount = this.eventCount;\n var oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;\n\n for (var i = 0; i < transform.steps.length; i++) {\n var step = transform.steps[i].invert(transform.docs[i]);\n var item = new Item(transform.mapping.maps[i], step, selection), merged = (void 0);\n if (merged = lastItem && lastItem.merge(item)) {\n item = merged;\n if (i) { newItems.pop(); }\n else { oldItems = oldItems.slice(0, oldItems.length - 1); }\n }\n newItems.push(item);\n if (selection) {\n eventCount++;\n selection = null;\n }\n if (!preserveItems) { lastItem = item; }\n }\n var overflow = eventCount - histOptions.depth;\n if (overflow > DEPTH_OVERFLOW) {\n oldItems = cutOffEvents(oldItems, overflow);\n eventCount -= overflow;\n }\n return new Branch(oldItems.append(newItems), eventCount)\n};\n\nBranch.prototype.remapping = function remapping (from, to) {\n var maps = new Mapping;\n this.items.forEach(function (item, i) {\n var mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from\n ? maps.maps.length - item.mirrorOffset : null;\n maps.appendMap(item.map, mirrorPos);\n }, from, to);\n return maps\n};\n\nBranch.prototype.addMaps = function addMaps (array) {\n if (this.eventCount == 0) { return this }\n return new Branch(this.items.append(array.map(function (map) { return new Item(map); })), this.eventCount)\n};\n\n// : (Transform, number)\n// When the collab module receives remote changes, the history has\n// to know about those, so that it can adjust the steps that were\n// rebased on top of the remote changes, and include the position\n// maps for the remote changes in its array of items.\nBranch.prototype.rebased = function rebased (rebasedTransform, rebasedCount) {\n if (!this.eventCount) { return this }\n\n var rebasedItems = [], start = Math.max(0, this.items.length - rebasedCount);\n\n var mapping = rebasedTransform.mapping;\n var newUntil = rebasedTransform.steps.length;\n var eventCount = this.eventCount;\n this.items.forEach(function (item) { if (item.selection) { eventCount--; } }, start);\n\n var iRebased = rebasedCount;\n this.items.forEach(function (item) {\n var pos = mapping.getMirror(--iRebased);\n if (pos == null) { return }\n newUntil = Math.min(newUntil, pos);\n var map = mapping.maps[pos];\n if (item.step) {\n var step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);\n var selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos));\n if (selection) { eventCount++; }\n rebasedItems.push(new Item(map, step, selection));\n } else {\n rebasedItems.push(new Item(map));\n }\n }, start);\n\n var newMaps = [];\n for (var i = rebasedCount; i < newUntil; i++)\n { newMaps.push(new Item(mapping.maps[i])); }\n var items = this.items.slice(0, start).append(newMaps).append(rebasedItems);\n var branch = new Branch(items, eventCount);\n\n if (branch.emptyItemCount() > max_empty_items)\n { branch = branch.compress(this.items.length - rebasedItems.length); }\n return branch\n};\n\nBranch.prototype.emptyItemCount = function emptyItemCount () {\n var count = 0;\n this.items.forEach(function (item) { if (!item.step) { count++; } });\n return count\n};\n\n// Compressing a branch means rewriting it to push the air (map-only\n// items) out. During collaboration, these naturally accumulate\n// because each remote change adds one. The `upto` argument is used\n// to ensure that only the items below a given level are compressed,\n// because `rebased` relies on a clean, untouched set of items in\n// order to associate old items with rebased steps.\nBranch.prototype.compress = function compress (upto) {\n if ( upto === void 0 ) upto = this.items.length;\n\n var remap = this.remapping(0, upto), mapFrom = remap.maps.length;\n var items = [], events = 0;\n this.items.forEach(function (item, i) {\n if (i >= upto) {\n items.push(item);\n if (item.selection) { events++; }\n } else if (item.step) {\n var step = item.step.map(remap.slice(mapFrom)), map = step && step.getMap();\n mapFrom--;\n if (map) { remap.appendMap(map, mapFrom); }\n if (step) {\n var selection = item.selection && item.selection.map(remap.slice(mapFrom));\n if (selection) { events++; }\n var newItem = new Item(map.invert(), step, selection), merged, last = items.length - 1;\n if (merged = items.length && items[last].merge(newItem))\n { items[last] = merged; }\n else\n { items.push(newItem); }\n }\n } else if (item.map) {\n mapFrom--;\n }\n }, this.items.length, 0);\n return new Branch(RopeSequence.from(items.reverse()), events)\n};\n\nBranch.empty = new Branch(RopeSequence.empty, 0);\n\nfunction cutOffEvents(items, n) {\n var cutPoint;\n items.forEach(function (item, i) {\n if (item.selection && (n-- == 0)) {\n cutPoint = i;\n return false\n }\n });\n return items.slice(cutPoint)\n}\n\nvar Item = function Item(map, step, selection, mirrorOffset) {\n // The (forward) step map for this item.\n this.map = map;\n // The inverted step\n this.step = step;\n // If this is non-null, this item is the start of a group, and\n // this selection is the starting selection for the group (the one\n // that was active before the first step was applied)\n this.selection = selection;\n // If this item is the inverse of a previous mapping on the stack,\n // this points at the inverse's offset\n this.mirrorOffset = mirrorOffset;\n};\n\nItem.prototype.merge = function merge (other) {\n if (this.step && other.step && !other.selection) {\n var step = other.step.merge(this.step);\n if (step) { return new Item(step.getMap().invert(), step, this.selection) }\n }\n};\n\n// The value of the state field that tracks undo/redo history for that\n// state. Will be stored in the plugin state when the history plugin\n// is active.\nvar HistoryState = function HistoryState(done, undone, prevRanges, prevTime) {\n this.done = done;\n this.undone = undone;\n this.prevRanges = prevRanges;\n this.prevTime = prevTime;\n};\n\nvar DEPTH_OVERFLOW = 20;\n\n// : (HistoryState, EditorState, Transaction, Object)\n// Record a transformation in undo history.\nfunction applyTransaction(history, state, tr, options) {\n var historyTr = tr.getMeta(historyKey), rebased;\n if (historyTr) { return historyTr.historyState }\n\n if (tr.getMeta(closeHistoryKey)) { history = new HistoryState(history.done, history.undone, null, 0); }\n\n var appended = tr.getMeta(\"appendedTransaction\");\n\n if (tr.steps.length == 0) {\n return history\n } else if (appended && appended.getMeta(historyKey)) {\n if (appended.getMeta(historyKey).redo)\n { return new HistoryState(history.done.addTransform(tr, null, options, mustPreserveItems(state)),\n history.undone, rangesFor(tr.mapping.maps[tr.steps.length - 1]), history.prevTime) }\n else\n { return new HistoryState(history.done, history.undone.addTransform(tr, null, options, mustPreserveItems(state)),\n null, history.prevTime) }\n } else if (tr.getMeta(\"addToHistory\") !== false && !(appended && appended.getMeta(\"addToHistory\") === false)) {\n // Group transforms that occur in quick succession into one event.\n var newGroup = history.prevTime == 0 || !appended && (history.prevTime < (tr.time || 0) - options.newGroupDelay ||\n !isAdjacentTo(tr, history.prevRanges));\n var prevRanges = appended ? mapRanges(history.prevRanges, tr.mapping) : rangesFor(tr.mapping.maps[tr.steps.length - 1]);\n return new HistoryState(history.done.addTransform(tr, newGroup ? state.selection.getBookmark() : null,\n options, mustPreserveItems(state)),\n Branch.empty, prevRanges, tr.time)\n } else if (rebased = tr.getMeta(\"rebased\")) {\n // Used by the collab module to tell the history that some of its\n // content has been rebased.\n return new HistoryState(history.done.rebased(tr, rebased),\n history.undone.rebased(tr, rebased),\n mapRanges(history.prevRanges, tr.mapping), history.prevTime)\n } else {\n return new HistoryState(history.done.addMaps(tr.mapping.maps),\n history.undone.addMaps(tr.mapping.maps),\n mapRanges(history.prevRanges, tr.mapping), history.prevTime)\n }\n}\n\nfunction isAdjacentTo(transform, prevRanges) {\n if (!prevRanges) { return false }\n if (!transform.docChanged) { return true }\n var adjacent = false;\n transform.mapping.maps[0].forEach(function (start, end) {\n for (var i = 0; i < prevRanges.length; i += 2)\n { if (start <= prevRanges[i + 1] && end >= prevRanges[i])\n { adjacent = true; } }\n });\n return adjacent\n}\n\nfunction rangesFor(map) {\n var result = [];\n map.forEach(function (_from, _to, from, to) { return result.push(from, to); });\n return result\n}\n\nfunction mapRanges(ranges, mapping) {\n if (!ranges) { return null }\n var result = [];\n for (var i = 0; i < ranges.length; i += 2) {\n var from = mapping.map(ranges[i], 1), to = mapping.map(ranges[i + 1], -1);\n if (from <= to) { result.push(from, to); }\n }\n return result\n}\n\n// : (HistoryState, EditorState, (tr: Transaction), bool)\n// Apply the latest event from one branch to the document and shift the event\n// onto the other branch.\nfunction histTransaction(history, state, dispatch, redo) {\n var preserveItems = mustPreserveItems(state), histOptions = historyKey.get(state).spec.config;\n var pop = (redo ? history.undone : history.done).popEvent(state, preserveItems);\n if (!pop) { return }\n\n var selection = pop.selection.resolve(pop.transform.doc);\n var added = (redo ? history.done : history.undone).addTransform(pop.transform, state.selection.getBookmark(),\n histOptions, preserveItems);\n\n var newHist = new HistoryState(redo ? added : pop.remaining, redo ? pop.remaining : added, null, 0);\n dispatch(pop.transform.setSelection(selection).setMeta(historyKey, {redo: redo, historyState: newHist}).scrollIntoView());\n}\n\nvar cachedPreserveItems = false, cachedPreserveItemsPlugins = null;\n// Check whether any plugin in the given state has a\n// `historyPreserveItems` property in its spec, in which case we must\n// preserve steps exactly as they came in, so that they can be\n// rebased.\nfunction mustPreserveItems(state) {\n var plugins = state.plugins;\n if (cachedPreserveItemsPlugins != plugins) {\n cachedPreserveItems = false;\n cachedPreserveItemsPlugins = plugins;\n for (var i = 0; i < plugins.length; i++) { if (plugins[i].spec.historyPreserveItems) {\n cachedPreserveItems = true;\n break\n } }\n }\n return cachedPreserveItems\n}\n\n// :: (Transaction) → Transaction\n// Set a flag on the given transaction that will prevent further steps\n// from being appended to an existing history event (so that they\n// require a separate undo command to undo).\nfunction closeHistory(tr) {\n return tr.setMeta(closeHistoryKey, true)\n}\n\nvar historyKey = new PluginKey(\"history\");\nvar closeHistoryKey = new PluginKey(\"closeHistory\");\n\n// :: (?Object) → Plugin\n// Returns a plugin that enables the undo history for an editor. The\n// plugin will track undo and redo stacks, which can be used with the\n// [`undo`](#history.undo) and [`redo`](#history.redo) commands.\n//\n// You can set an `\"addToHistory\"` [metadata\n// property](#state.Transaction.setMeta) of `false` on a transaction\n// to prevent it from being rolled back by undo.\n//\n// config::-\n// Supports the following configuration options:\n//\n// depth:: ?number\n// The amount of history events that are collected before the\n// oldest events are discarded. Defaults to 100.\n//\n// newGroupDelay:: ?number\n// The delay between changes after which a new group should be\n// started. Defaults to 500 (milliseconds). Note that when changes\n// aren't adjacent, a new group is always started.\nfunction history(config) {\n config = {depth: config && config.depth || 100,\n newGroupDelay: config && config.newGroupDelay || 500};\n return new Plugin({\n key: historyKey,\n\n state: {\n init: function init() {\n return new HistoryState(Branch.empty, Branch.empty, null, 0)\n },\n apply: function apply(tr, hist, state) {\n return applyTransaction(hist, state, tr, config)\n }\n },\n\n config: config\n })\n}\n\n// :: (EditorState, ?(tr: Transaction)) → bool\n// A command function that undoes the last change, if any.\nfunction undo(state, dispatch) {\n var hist = historyKey.getState(state);\n if (!hist || hist.done.eventCount == 0) { return false }\n if (dispatch) { histTransaction(hist, state, dispatch, false); }\n return true\n}\n\n// :: (EditorState, ?(tr: Transaction)) → bool\n// A command function that redoes the last undone change, if any.\nfunction redo(state, dispatch) {\n var hist = historyKey.getState(state);\n if (!hist || hist.undone.eventCount == 0) { return false }\n if (dispatch) { histTransaction(hist, state, dispatch, true); }\n return true\n}\n\n// :: (EditorState) → number\n// The amount of undoable events available in a given state.\nfunction undoDepth(state) {\n var hist = historyKey.getState(state);\n return hist ? hist.done.eventCount : 0\n}\n\n// :: (EditorState) → number\n// The amount of redoable events available in a given editor state.\nfunction redoDepth(state) {\n var hist = historyKey.getState(state);\n return hist ? hist.undone.eventCount : 0\n}\n\nexport { HistoryState, closeHistory, history, redo, redoDepth, undo, undoDepth };\n//# sourceMappingURL=index.es.js.map\n","import { liftTarget, canJoin, joinPoint, canSplit, ReplaceAroundStep, findWrapping } from 'prosemirror-transform';\nimport { Fragment, Slice } from 'prosemirror-model';\nimport { NodeSelection, Selection, TextSelection, AllSelection } from 'prosemirror-state';\n\n// :: (EditorState, ?(tr: Transaction)) → bool\n// Delete the selection, if there is one.\nfunction deleteSelection(state, dispatch) {\n if (state.selection.empty) { return false }\n if (dispatch) { dispatch(state.tr.deleteSelection().scrollIntoView()); }\n return true\n}\n\n// :: (EditorState, ?(tr: Transaction), ?EditorView) → bool\n// If the selection is empty and at the start of a textblock, try to\n// reduce the distance between that block and the one before it—if\n// there's a block directly before it that can be joined, join them.\n// If not, try to move the selected block closer to the next one in\n// the document structure by lifting it out of its parent or moving it\n// into a parent of the previous block. Will use the view for accurate\n// (bidi-aware) start-of-textblock detection if given.\nfunction joinBackward(state, dispatch, view) {\n var ref = state.selection;\n var $cursor = ref.$cursor;\n if (!$cursor || (view ? !view.endOfTextblock(\"backward\", state)\n : $cursor.parentOffset > 0))\n { return false }\n\n var $cut = findCutBefore($cursor);\n\n // If there is no node before this, try to lift\n if (!$cut) {\n var range = $cursor.blockRange(), target = range && liftTarget(range);\n if (target == null) { return false }\n if (dispatch) { dispatch(state.tr.lift(range, target).scrollIntoView()); }\n return true\n }\n\n var before = $cut.nodeBefore;\n // Apply the joining algorithm\n if (!before.type.spec.isolating && deleteBarrier(state, $cut, dispatch))\n { return true }\n\n // If the node below has no content and the node above is\n // selectable, delete the node below and select the one above.\n if ($cursor.parent.content.size == 0 &&\n (textblockAt(before, \"end\") || NodeSelection.isSelectable(before))) {\n if (dispatch) {\n var tr = state.tr.deleteRange($cursor.before(), $cursor.after());\n tr.setSelection(textblockAt(before, \"end\") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1)\n : NodeSelection.create(tr.doc, $cut.pos - before.nodeSize));\n dispatch(tr.scrollIntoView());\n }\n return true\n }\n\n // If the node before is an atom, delete it\n if (before.isAtom && $cut.depth == $cursor.depth - 1) {\n if (dispatch) { dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView()); }\n return true\n }\n\n return false\n}\n\nfunction textblockAt(node, side) {\n for (; node; node = (side == \"start\" ? node.firstChild : node.lastChild))\n { if (node.isTextblock) { return true } }\n return false\n}\n\n// :: (EditorState, ?(tr: Transaction), ?EditorView) → bool\n// When the selection is empty and at the start of a textblock, select\n// the node before that textblock, if possible. This is intended to be\n// bound to keys like backspace, after\n// [`joinBackward`](#commands.joinBackward) or other deleting\n// commands, as a fall-back behavior when the schema doesn't allow\n// deletion at the selected point.\nfunction selectNodeBackward(state, dispatch, view) {\n var ref = state.selection;\n var $head = ref.$head;\n var empty = ref.empty;\n var $cut = $head;\n if (!empty) { return false }\n\n if ($head.parent.isTextblock) {\n if (view ? !view.endOfTextblock(\"backward\", state) : $head.parentOffset > 0) { return false }\n $cut = findCutBefore($head);\n }\n var node = $cut && $cut.nodeBefore;\n if (!node || !NodeSelection.isSelectable(node)) { return false }\n if (dispatch)\n { dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView()); }\n return true\n}\n\nfunction findCutBefore($pos) {\n if (!$pos.parent.type.spec.isolating) { for (var i = $pos.depth - 1; i >= 0; i--) {\n if ($pos.index(i) > 0) { return $pos.doc.resolve($pos.before(i + 1)) }\n if ($pos.node(i).type.spec.isolating) { break }\n } }\n return null\n}\n\n// :: (EditorState, ?(tr: Transaction), ?EditorView) → bool\n// If the selection is empty and the cursor is at the end of a\n// textblock, try to reduce or remove the boundary between that block\n// and the one after it, either by joining them or by moving the other\n// block closer to this one in the tree structure. Will use the view\n// for accurate start-of-textblock detection if given.\nfunction joinForward(state, dispatch, view) {\n var ref = state.selection;\n var $cursor = ref.$cursor;\n if (!$cursor || (view ? !view.endOfTextblock(\"forward\", state)\n : $cursor.parentOffset < $cursor.parent.content.size))\n { return false }\n\n var $cut = findCutAfter($cursor);\n\n // If there is no node after this, there's nothing to do\n if (!$cut) { return false }\n\n var after = $cut.nodeAfter;\n // Try the joining algorithm\n if (deleteBarrier(state, $cut, dispatch)) { return true }\n\n // If the node above has no content and the node below is\n // selectable, delete the node above and select the one below.\n if ($cursor.parent.content.size == 0 &&\n (textblockAt(after, \"start\") || NodeSelection.isSelectable(after))) {\n if (dispatch) {\n var tr = state.tr.deleteRange($cursor.before(), $cursor.after());\n tr.setSelection(textblockAt(after, \"start\") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1)\n : NodeSelection.create(tr.doc, tr.mapping.map($cut.pos)));\n dispatch(tr.scrollIntoView());\n }\n return true\n }\n\n // If the next node is an atom, delete it\n if (after.isAtom && $cut.depth == $cursor.depth - 1) {\n if (dispatch) { dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView()); }\n return true\n }\n\n return false\n}\n\n// :: (EditorState, ?(tr: Transaction), ?EditorView) → bool\n// When the selection is empty and at the end of a textblock, select\n// the node coming after that textblock, if possible. This is intended\n// to be bound to keys like delete, after\n// [`joinForward`](#commands.joinForward) and similar deleting\n// commands, to provide a fall-back behavior when the schema doesn't\n// allow deletion at the selected point.\nfunction selectNodeForward(state, dispatch, view) {\n var ref = state.selection;\n var $head = ref.$head;\n var empty = ref.empty;\n var $cut = $head;\n if (!empty) { return false }\n if ($head.parent.isTextblock) {\n if (view ? !view.endOfTextblock(\"forward\", state) : $head.parentOffset < $head.parent.content.size)\n { return false }\n $cut = findCutAfter($head);\n }\n var node = $cut && $cut.nodeAfter;\n if (!node || !NodeSelection.isSelectable(node)) { return false }\n if (dispatch)\n { dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView()); }\n return true\n}\n\nfunction findCutAfter($pos) {\n if (!$pos.parent.type.spec.isolating) { for (var i = $pos.depth - 1; i >= 0; i--) {\n var parent = $pos.node(i);\n if ($pos.index(i) + 1 < parent.childCount) { return $pos.doc.resolve($pos.after(i + 1)) }\n if (parent.type.spec.isolating) { break }\n } }\n return null\n}\n\n// :: (EditorState, ?(tr: Transaction)) → bool\n// Join the selected block or, if there is a text selection, the\n// closest ancestor block of the selection that can be joined, with\n// the sibling above it.\nfunction joinUp(state, dispatch) {\n var sel = state.selection, nodeSel = sel instanceof NodeSelection, point;\n if (nodeSel) {\n if (sel.node.isTextblock || !canJoin(state.doc, sel.from)) { return false }\n point = sel.from;\n } else {\n point = joinPoint(state.doc, sel.from, -1);\n if (point == null) { return false }\n }\n if (dispatch) {\n var tr = state.tr.join(point);\n if (nodeSel) { tr.setSelection(NodeSelection.create(tr.doc, point - state.doc.resolve(point).nodeBefore.nodeSize)); }\n dispatch(tr.scrollIntoView());\n }\n return true\n}\n\n// :: (EditorState, ?(tr: Transaction)) → bool\n// Join the selected block, or the closest ancestor of the selection\n// that can be joined, with the sibling after it.\nfunction joinDown(state, dispatch) {\n var sel = state.selection, point;\n if (sel instanceof NodeSelection) {\n if (sel.node.isTextblock || !canJoin(state.doc, sel.to)) { return false }\n point = sel.to;\n } else {\n point = joinPoint(state.doc, sel.to, 1);\n if (point == null) { return false }\n }\n if (dispatch)\n { dispatch(state.tr.join(point).scrollIntoView()); }\n return true\n}\n\n// :: (EditorState, ?(tr: Transaction)) → bool\n// Lift the selected block, or the closest ancestor block of the\n// selection that can be lifted, out of its parent node.\nfunction lift(state, dispatch) {\n var ref = state.selection;\n var $from = ref.$from;\n var $to = ref.$to;\n var range = $from.blockRange($to), target = range && liftTarget(range);\n if (target == null) { return false }\n if (dispatch) { dispatch(state.tr.lift(range, target).scrollIntoView()); }\n return true\n}\n\n// :: (EditorState, ?(tr: Transaction)) → bool\n// If the selection is in a node whose type has a truthy\n// [`code`](#model.NodeSpec.code) property in its spec, replace the\n// selection with a newline character.\nfunction newlineInCode(state, dispatch) {\n var ref = state.selection;\n var $head = ref.$head;\n var $anchor = ref.$anchor;\n if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) { return false }\n if (dispatch) { dispatch(state.tr.insertText(\"\\n\").scrollIntoView()); }\n return true\n}\n\nfunction defaultBlockAt(match) {\n for (var i = 0; i < match.edgeCount; i++) {\n var ref = match.edge(i);\n var type = ref.type;\n if (type.isTextblock && !type.hasRequiredAttrs()) { return type }\n }\n return null\n}\n\n// :: (EditorState, ?(tr: Transaction)) → bool\n// When the selection is in a node with a truthy\n// [`code`](#model.NodeSpec.code) property in its spec, create a\n// default block after the code block, and move the cursor there.\nfunction exitCode(state, dispatch) {\n var ref = state.selection;\n var $head = ref.$head;\n var $anchor = ref.$anchor;\n if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) { return false }\n var above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after));\n if (!above.canReplaceWith(after, after, type)) { return false }\n if (dispatch) {\n var pos = $head.after(), tr = state.tr.replaceWith(pos, pos, type.createAndFill());\n tr.setSelection(Selection.near(tr.doc.resolve(pos), 1));\n dispatch(tr.scrollIntoView());\n }\n return true\n}\n\n// :: (EditorState, ?(tr: Transaction)) → bool\n// If a block node is selected, create an empty paragraph before (if\n// it is its parent's first child) or after it.\nfunction createParagraphNear(state, dispatch) {\n var ref = state.selection;\n var $from = ref.$from;\n var $to = ref.$to;\n if ($from.parent.inlineContent || $to.parent.inlineContent) { return false }\n var type = defaultBlockAt($from.parent.contentMatchAt($to.indexAfter()));\n if (!type || !type.isTextblock) { return false }\n if (dispatch) {\n var side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;\n var tr = state.tr.insert(side, type.createAndFill());\n tr.setSelection(TextSelection.create(tr.doc, side + 1));\n dispatch(tr.scrollIntoView());\n }\n return true\n}\n\n// :: (EditorState, ?(tr: Transaction)) → bool\n// If the cursor is in an empty textblock that can be lifted, lift the\n// block.\nfunction liftEmptyBlock(state, dispatch) {\n var ref = state.selection;\n var $cursor = ref.$cursor;\n if (!$cursor || $cursor.parent.content.size) { return false }\n if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {\n var before = $cursor.before();\n if (canSplit(state.doc, before)) {\n if (dispatch) { dispatch(state.tr.split(before).scrollIntoView()); }\n return true\n }\n }\n var range = $cursor.blockRange(), target = range && liftTarget(range);\n if (target == null) { return false }\n if (dispatch) { dispatch(state.tr.lift(range, target).scrollIntoView()); }\n return true\n}\n\n// :: (EditorState, ?(tr: Transaction)) → bool\n// Split the parent block of the selection. If the selection is a text\n// selection, also delete its content.\nfunction splitBlock(state, dispatch) {\n var ref = state.selection;\n var $from = ref.$from;\n var $to = ref.$to;\n if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {\n if (!$from.parentOffset || !canSplit(state.doc, $from.pos)) { return false }\n if (dispatch) { dispatch(state.tr.split($from.pos).scrollIntoView()); }\n return true\n }\n\n if (!$from.parent.isBlock) { return false }\n\n if (dispatch) {\n var atEnd = $to.parentOffset == $to.parent.content.size;\n var tr = state.tr;\n if (state.selection instanceof TextSelection) { tr.deleteSelection(); }\n var deflt = $from.depth == 0 ? null : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)));\n var types = atEnd && deflt ? [{type: deflt}] : null;\n var can = canSplit(tr.doc, tr.mapping.map($from.pos), 1, types);\n if (!types && !can && canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt && [{type: deflt}])) {\n types = [{type: deflt}];\n can = true;\n }\n if (can) {\n tr.split(tr.mapping.map($from.pos), 1, types);\n if (!atEnd && !$from.parentOffset && $from.parent.type != deflt &&\n $from.node(-1).canReplace($from.index(-1), $from.indexAfter(-1), Fragment.from(deflt.create(), $from.parent)))\n { tr.setNodeMarkup(tr.mapping.map($from.before()), deflt); }\n }\n dispatch(tr.scrollIntoView());\n }\n return true\n}\n\n// :: (EditorState, ?(tr: Transaction)) → bool\n// Acts like [`splitBlock`](#commands.splitBlock), but without\n// resetting the set of active marks at the cursor.\nfunction splitBlockKeepMarks(state, dispatch) {\n return splitBlock(state, dispatch && (function (tr) {\n var marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());\n if (marks) { tr.ensureMarks(marks); }\n dispatch(tr);\n }))\n}\n\n// :: (EditorState, ?(tr: Transaction)) → bool\n// Move the selection to the node wrapping the current selection, if\n// any. (Will not select the document node.)\nfunction selectParentNode(state, dispatch) {\n var ref = state.selection;\n var $from = ref.$from;\n var to = ref.to;\n var pos;\n var same = $from.sharedDepth(to);\n if (same == 0) { return false }\n pos = $from.before(same);\n if (dispatch) { dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos))); }\n return true\n}\n\n// :: (EditorState, ?(tr: Transaction)) → bool\n// Select the whole document.\nfunction selectAll(state, dispatch) {\n if (dispatch) { dispatch(state.tr.setSelection(new AllSelection(state.doc))); }\n return true\n}\n\nfunction joinMaybeClear(state, $pos, dispatch) {\n var before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index();\n if (!before || !after || !before.type.compatibleContent(after.type)) { return false }\n if (!before.content.size && $pos.parent.canReplace(index - 1, index)) {\n if (dispatch) { dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView()); }\n return true\n }\n if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos)))\n { return false }\n if (dispatch)\n { dispatch(state.tr\n .clearIncompatible($pos.pos, before.type, before.contentMatchAt(before.childCount))\n .join($pos.pos)\n .scrollIntoView()); }\n return true\n}\n\nfunction deleteBarrier(state, $cut, dispatch) {\n var before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match;\n if (before.type.spec.isolating || after.type.spec.isolating) { return false }\n if (joinMaybeClear(state, $cut, dispatch)) { return true }\n\n if ($cut.parent.canReplace($cut.index(), $cut.index() + 1) &&\n (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) &&\n match.matchType(conn[0] || after.type).validEnd) {\n if (dispatch) {\n var end = $cut.pos + after.nodeSize, wrap = Fragment.empty;\n for (var i = conn.length - 1; i >= 0; i--)\n { wrap = Fragment.from(conn[i].create(null, wrap)); }\n wrap = Fragment.from(before.copy(wrap));\n var tr = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap, 1, 0), conn.length, true));\n var joinAt = end + 2 * conn.length;\n if (canJoin(tr.doc, joinAt)) { tr.join(joinAt); }\n dispatch(tr.scrollIntoView());\n }\n return true\n }\n\n var selAfter = Selection.findFrom($cut, 1);\n var range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range);\n if (target != null && target >= $cut.depth) {\n if (dispatch) { dispatch(state.tr.lift(range, target).scrollIntoView()); }\n return true\n }\n\n return false\n}\n\n// Parameterized commands\n\n// :: (NodeType, ?Object) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool\n// Wrap the selection in a node of the given type with the given\n// attributes.\nfunction wrapIn(nodeType, attrs) {\n return function(state, dispatch) {\n var ref = state.selection;\n var $from = ref.$from;\n var $to = ref.$to;\n var range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs);\n if (!wrapping) { return false }\n if (dispatch) { dispatch(state.tr.wrap(range, wrapping).scrollIntoView()); }\n return true\n }\n}\n\n// :: (NodeType, ?Object) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool\n// Returns a command that tries to set the selected textblocks to the\n// given node type with the given attributes.\nfunction setBlockType(nodeType, attrs) {\n return function(state, dispatch) {\n var ref = state.selection;\n var from = ref.from;\n var to = ref.to;\n var applicable = false;\n state.doc.nodesBetween(from, to, function (node, pos) {\n if (applicable) { return false }\n if (!node.isTextblock || node.hasMarkup(nodeType, attrs)) { return }\n if (node.type == nodeType) {\n applicable = true;\n } else {\n var $pos = state.doc.resolve(pos), index = $pos.index();\n applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);\n }\n });\n if (!applicable) { return false }\n if (dispatch) { dispatch(state.tr.setBlockType(from, to, nodeType, attrs).scrollIntoView()); }\n return true\n }\n}\n\nfunction markApplies(doc, ranges, type) {\n var loop = function ( i ) {\n var ref = ranges[i];\n var $from = ref.$from;\n var $to = ref.$to;\n var can = $from.depth == 0 ? doc.type.allowsMarkType(type) : false;\n doc.nodesBetween($from.pos, $to.pos, function (node) {\n if (can) { return false }\n can = node.inlineContent && node.type.allowsMarkType(type);\n });\n if (can) { return { v: true } }\n };\n\n for (var i = 0; i < ranges.length; i++) {\n var returned = loop( i );\n\n if ( returned ) return returned.v;\n }\n return false\n}\n\n// :: (MarkType, ?Object) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool\n// Create a command function that toggles the given mark with the\n// given attributes. Will return `false` when the current selection\n// doesn't support that mark. This will remove the mark if any marks\n// of that type exist in the selection, or add it otherwise. If the\n// selection is empty, this applies to the [stored\n// marks](#state.EditorState.storedMarks) instead of a range of the\n// document.\nfunction toggleMark(markType, attrs) {\n return function(state, dispatch) {\n var ref = state.selection;\n var empty = ref.empty;\n var $cursor = ref.$cursor;\n var ranges = ref.ranges;\n if ((empty && !$cursor) || !markApplies(state.doc, ranges, markType)) { return false }\n if (dispatch) {\n if ($cursor) {\n if (markType.isInSet(state.storedMarks || $cursor.marks()))\n { dispatch(state.tr.removeStoredMark(markType)); }\n else\n { dispatch(state.tr.addStoredMark(markType.create(attrs))); }\n } else {\n var has = false, tr = state.tr;\n for (var i = 0; !has && i < ranges.length; i++) {\n var ref$1 = ranges[i];\n var $from = ref$1.$from;\n var $to = ref$1.$to;\n has = state.doc.rangeHasMark($from.pos, $to.pos, markType);\n }\n for (var i$1 = 0; i$1 < ranges.length; i$1++) {\n var ref$2 = ranges[i$1];\n var $from$1 = ref$2.$from;\n var $to$1 = ref$2.$to;\n if (has) { tr.removeMark($from$1.pos, $to$1.pos, markType); }\n else { tr.addMark($from$1.pos, $to$1.pos, markType.create(attrs)); }\n }\n dispatch(tr.scrollIntoView());\n }\n }\n return true\n }\n}\n\nfunction wrapDispatchForJoin(dispatch, isJoinable) {\n return function (tr) {\n if (!tr.isGeneric) { return dispatch(tr) }\n\n var ranges = [];\n for (var i = 0; i < tr.mapping.maps.length; i++) {\n var map = tr.mapping.maps[i];\n for (var j = 0; j < ranges.length; j++)\n { ranges[j] = map.map(ranges[j]); }\n map.forEach(function (_s, _e, from, to) { return ranges.push(from, to); });\n }\n\n // Figure out which joinable points exist inside those ranges,\n // by checking all node boundaries in their parent nodes.\n var joinable = [];\n for (var i$1 = 0; i$1 < ranges.length; i$1 += 2) {\n var from = ranges[i$1], to = ranges[i$1 + 1];\n var $from = tr.doc.resolve(from), depth = $from.sharedDepth(to), parent = $from.node(depth);\n for (var index = $from.indexAfter(depth), pos = $from.after(depth + 1); pos <= to; ++index) {\n var after = parent.maybeChild(index);\n if (!after) { break }\n if (index && joinable.indexOf(pos) == -1) {\n var before = parent.child(index - 1);\n if (before.type == after.type && isJoinable(before, after))\n { joinable.push(pos); }\n }\n pos += after.nodeSize;\n }\n }\n // Join the joinable points\n joinable.sort(function (a, b) { return a - b; });\n for (var i$2 = joinable.length - 1; i$2 >= 0; i$2--) {\n if (canJoin(tr.doc, joinable[i$2])) { tr.join(joinable[i$2]); }\n }\n dispatch(tr);\n }\n}\n\n// :: ((state: EditorState, ?(tr: Transaction)) → bool, union<(before: Node, after: Node) → bool, [string]>) → (state: EditorState, ?(tr: Transaction)) → bool\n// Wrap a command so that, when it produces a transform that causes\n// two joinable nodes to end up next to each other, those are joined.\n// Nodes are considered joinable when they are of the same type and\n// when the `isJoinable` predicate returns true for them or, if an\n// array of strings was passed, if their node type name is in that\n// array.\nfunction autoJoin(command, isJoinable) {\n if (Array.isArray(isJoinable)) {\n var types = isJoinable;\n isJoinable = function (node) { return types.indexOf(node.type.name) > -1; };\n }\n return function (state, dispatch) { return command(state, dispatch && wrapDispatchForJoin(dispatch, isJoinable)); }\n}\n\n// :: (...[(EditorState, ?(tr: Transaction), ?EditorView) → bool]) → (EditorState, ?(tr: Transaction), ?EditorView) → bool\n// Combine a number of command functions into a single function (which\n// calls them one by one until one returns true).\nfunction chainCommands() {\n var commands = [], len = arguments.length;\n while ( len-- ) commands[ len ] = arguments[ len ];\n\n return function(state, dispatch, view) {\n for (var i = 0; i < commands.length; i++)\n { if (commands[i](state, dispatch, view)) { return true } }\n return false\n }\n}\n\nvar backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);\nvar del = chainCommands(deleteSelection, joinForward, selectNodeForward);\n\n// :: Object\n// A basic keymap containing bindings not specific to any schema.\n// Binds the following keys (when multiple commands are listed, they\n// are chained with [`chainCommands`](#commands.chainCommands)):\n//\n// * **Enter** to `newlineInCode`, `createParagraphNear`, `liftEmptyBlock`, `splitBlock`\n// * **Mod-Enter** to `exitCode`\n// * **Backspace** and **Mod-Backspace** to `deleteSelection`, `joinBackward`, `selectNodeBackward`\n// * **Delete** and **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n// * **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n// * **Mod-a** to `selectAll`\nvar pcBaseKeymap = {\n \"Enter\": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),\n \"Mod-Enter\": exitCode,\n \"Backspace\": backspace,\n \"Mod-Backspace\": backspace,\n \"Delete\": del,\n \"Mod-Delete\": del,\n \"Mod-a\": selectAll\n};\n\n// :: Object\n// A copy of `pcBaseKeymap` that also binds **Ctrl-h** like Backspace,\n// **Ctrl-d** like Delete, **Alt-Backspace** like Ctrl-Backspace, and\n// **Ctrl-Alt-Backspace**, **Alt-Delete**, and **Alt-d** like\n// Ctrl-Delete.\nvar macBaseKeymap = {\n \"Ctrl-h\": pcBaseKeymap[\"Backspace\"],\n \"Alt-Backspace\": pcBaseKeymap[\"Mod-Backspace\"],\n \"Ctrl-d\": pcBaseKeymap[\"Delete\"],\n \"Ctrl-Alt-Backspace\": pcBaseKeymap[\"Mod-Delete\"],\n \"Alt-Delete\": pcBaseKeymap[\"Mod-Delete\"],\n \"Alt-d\": pcBaseKeymap[\"Mod-Delete\"]\n};\nfor (var key in pcBaseKeymap) { macBaseKeymap[key] = pcBaseKeymap[key]; }\n\n// declare global: os, navigator\nvar mac = typeof navigator != \"undefined\" ? /Mac/.test(navigator.platform)\n : typeof os != \"undefined\" ? os.platform() == \"darwin\" : false;\n\n// :: Object\n// Depending on the detected platform, this will hold\n// [`pcBasekeymap`](#commands.pcBaseKeymap) or\n// [`macBaseKeymap`](#commands.macBaseKeymap).\nvar baseKeymap = mac ? macBaseKeymap : pcBaseKeymap;\n\nexport { autoJoin, baseKeymap, chainCommands, createParagraphNear, deleteSelection, exitCode, joinBackward, joinDown, joinForward, joinUp, lift, liftEmptyBlock, macBaseKeymap, newlineInCode, pcBaseKeymap, selectAll, selectNodeBackward, selectNodeForward, selectParentNode, setBlockType, splitBlock, splitBlockKeepMarks, toggleMark, wrapIn };\n//# sourceMappingURL=index.es.js.map\n","import { Plugin } from 'prosemirror-state';\nimport { dropPoint } from 'prosemirror-transform';\n\n// :: (options: ?Object) → Plugin\n// Create a plugin that, when added to a ProseMirror instance,\n// causes a decoration to show up at the drop position when something\n// is dragged over the editor.\n//\n// options::- These options are supported:\n//\n// color:: ?string\n// The color of the cursor. Defaults to `black`.\n//\n// width:: ?number\n// The precise width of the cursor in pixels. Defaults to 1.\n//\n// class:: ?string\n// A CSS class name to add to the cursor element.\nfunction dropCursor(options) {\n if ( options === void 0 ) options = {};\n\n return new Plugin({\n view: function view(editorView) { return new DropCursorView(editorView, options) }\n })\n}\n\nvar DropCursorView = function DropCursorView(editorView, options) {\n var this$1 = this;\n\n this.editorView = editorView;\n this.width = options.width || 1;\n this.color = options.color || \"black\";\n this.class = options.class;\n this.cursorPos = null;\n this.element = null;\n this.timeout = null;\n\n this.handlers = [\"dragover\", \"dragend\", \"drop\", \"dragleave\"].map(function (name) {\n var handler = function (e) { return this$1[name](e); };\n editorView.dom.addEventListener(name, handler);\n return {name: name, handler: handler}\n });\n};\n\nDropCursorView.prototype.destroy = function destroy () {\n var this$1 = this;\n\n this.handlers.forEach(function (ref) {\n var name = ref.name;\n var handler = ref.handler;\n\n return this$1.editorView.dom.removeEventListener(name, handler);\n });\n};\n\nDropCursorView.prototype.update = function update (editorView, prevState) {\n if (this.cursorPos != null && prevState.doc != editorView.state.doc) { this.updateOverlay(); }\n};\n\nDropCursorView.prototype.setCursor = function setCursor (pos) {\n if (pos == this.cursorPos) { return }\n this.cursorPos = pos;\n if (pos == null) {\n this.element.parentNode.removeChild(this.element);\n this.element = null;\n } else {\n this.updateOverlay();\n }\n};\n\nDropCursorView.prototype.updateOverlay = function updateOverlay () {\n var $pos = this.editorView.state.doc.resolve(this.cursorPos), rect;\n if (!$pos.parent.inlineContent) {\n var before = $pos.nodeBefore, after = $pos.nodeAfter;\n if (before || after) {\n var nodeRect = this.editorView.nodeDOM(this.cursorPos - (before ?before.nodeSize : 0)).getBoundingClientRect();\n var top = before ? nodeRect.bottom : nodeRect.top;\n if (before && after)\n { top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2; }\n rect = {left: nodeRect.left, right: nodeRect.right, top: top - this.width / 2, bottom: top + this.width / 2};\n }\n }\n if (!rect) {\n var coords = this.editorView.coordsAtPos(this.cursorPos);\n rect = {left: coords.left - this.width / 2, right: coords.left + this.width / 2, top: coords.top, bottom: coords.bottom};\n }\n\n var parent = this.editorView.dom.offsetParent;\n if (!this.element) {\n this.element = parent.appendChild(document.createElement(\"div\"));\n if (this.class) { this.element.className = this.class; }\n this.element.style.cssText = \"position: absolute; z-index: 50; pointer-events: none; background-color: \" + this.color;\n }\n var parentRect = !parent || parent == document.body && getComputedStyle(parent).position == \"static\"\n ? {left: -pageXOffset, top: -pageYOffset} : parent.getBoundingClientRect();\n this.element.style.left = (rect.left - parentRect.left) + \"px\";\n this.element.style.top = (rect.top - parentRect.top) + \"px\";\n this.element.style.width = (rect.right - rect.left) + \"px\";\n this.element.style.height = (rect.bottom - rect.top) + \"px\";\n};\n\nDropCursorView.prototype.scheduleRemoval = function scheduleRemoval (timeout) {\n var this$1 = this;\n\n clearTimeout(this.timeout);\n this.timeout = setTimeout(function () { return this$1.setCursor(null); }, timeout);\n};\n\nDropCursorView.prototype.dragover = function dragover (event) {\n if (!this.editorView.editable) { return }\n var pos = this.editorView.posAtCoords({left: event.clientX, top: event.clientY});\n if (pos) {\n var target = pos.pos;\n if (this.editorView.dragging && this.editorView.dragging.slice) {\n target = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice);\n if (target == null) { target = pos.pos; }\n }\n this.setCursor(target);\n this.scheduleRemoval(5000);\n }\n};\n\nDropCursorView.prototype.dragend = function dragend () {\n this.scheduleRemoval(20);\n};\n\nDropCursorView.prototype.drop = function drop () {\n this.scheduleRemoval(20);\n};\n\nDropCursorView.prototype.dragleave = function dragleave (event) {\n if (event.target == this.editorView.dom || !this.editorView.dom.contains(event.relatedTarget))\n { this.setCursor(null); }\n};\n\nexport { dropCursor };\n//# sourceMappingURL=index.es.js.map\n","import { keydownHandler } from 'prosemirror-keymap';\nimport { NodeSelection, Selection, Plugin, TextSelection } from 'prosemirror-state';\nimport { DecorationSet, Decoration } from 'prosemirror-view';\nimport { Slice } from 'prosemirror-model';\n\n// ::- Gap cursor selections are represented using this class. Its\n// `$anchor` and `$head` properties both point at the cursor position.\nvar GapCursor = /*@__PURE__*/(function (Selection) {\n function GapCursor($pos) {\n Selection.call(this, $pos, $pos);\n }\n\n if ( Selection ) GapCursor.__proto__ = Selection;\n GapCursor.prototype = Object.create( Selection && Selection.prototype );\n GapCursor.prototype.constructor = GapCursor;\n\n GapCursor.prototype.map = function map (doc, mapping) {\n var $pos = doc.resolve(mapping.map(this.head));\n return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos)\n };\n\n GapCursor.prototype.content = function content () { return Slice.empty };\n\n GapCursor.prototype.eq = function eq (other) {\n return other instanceof GapCursor && other.head == this.head\n };\n\n GapCursor.prototype.toJSON = function toJSON () {\n return {type: \"gapcursor\", pos: this.head}\n };\n\n GapCursor.fromJSON = function fromJSON (doc, json) {\n if (typeof json.pos != \"number\") { throw new RangeError(\"Invalid input for GapCursor.fromJSON\") }\n return new GapCursor(doc.resolve(json.pos))\n };\n\n GapCursor.prototype.getBookmark = function getBookmark () { return new GapBookmark(this.anchor) };\n\n GapCursor.valid = function valid ($pos) {\n var parent = $pos.parent;\n if (parent.isTextblock || !closedBefore($pos) || !closedAfter($pos)) { return false }\n var override = parent.type.spec.allowGapCursor;\n if (override != null) { return override }\n var deflt = parent.contentMatchAt($pos.index()).defaultType;\n return deflt && deflt.isTextblock\n };\n\n GapCursor.findFrom = function findFrom ($pos, dir, mustMove) {\n search: for (;;) {\n if (!mustMove && GapCursor.valid($pos)) { return $pos }\n var pos = $pos.pos, next = null;\n // Scan up from this position\n for (var d = $pos.depth;; d--) {\n var parent = $pos.node(d);\n if (dir > 0 ? $pos.indexAfter(d) < parent.childCount : $pos.index(d) > 0) {\n next = parent.child(dir > 0 ? $pos.indexAfter(d) : $pos.index(d) - 1);\n break\n } else if (d == 0) {\n return null\n }\n pos += dir;\n var $cur = $pos.doc.resolve(pos);\n if (GapCursor.valid($cur)) { return $cur }\n }\n\n // And then down into the next node\n for (;;) {\n var inside = dir > 0 ? next.firstChild : next.lastChild;\n if (!inside) {\n if (next.isAtom && !next.isText && !NodeSelection.isSelectable(next)) {\n $pos = $pos.doc.resolve(pos + next.nodeSize * dir);\n mustMove = false;\n continue search\n }\n break\n }\n next = inside;\n pos += dir;\n var $cur$1 = $pos.doc.resolve(pos);\n if (GapCursor.valid($cur$1)) { return $cur$1 }\n }\n\n return null\n }\n };\n\n return GapCursor;\n}(Selection));\n\nGapCursor.prototype.visible = false;\n\nSelection.jsonID(\"gapcursor\", GapCursor);\n\nvar GapBookmark = function GapBookmark(pos) {\n this.pos = pos;\n};\nGapBookmark.prototype.map = function map (mapping) {\n return new GapBookmark(mapping.map(this.pos))\n};\nGapBookmark.prototype.resolve = function resolve (doc) {\n var $pos = doc.resolve(this.pos);\n return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos)\n};\n\nfunction closedBefore($pos) {\n for (var d = $pos.depth; d >= 0; d--) {\n var index = $pos.index(d);\n // At the start of this parent, look at next one\n if (index == 0) { continue }\n // See if the node before (or its first ancestor) is closed\n for (var before = $pos.node(d).child(index - 1);; before = before.lastChild) {\n if ((before.childCount == 0 && !before.inlineContent) || before.isAtom || before.type.spec.isolating) { return true }\n if (before.inlineContent) { return false }\n }\n }\n // Hit start of document\n return true\n}\n\nfunction closedAfter($pos) {\n for (var d = $pos.depth; d >= 0; d--) {\n var index = $pos.indexAfter(d), parent = $pos.node(d);\n if (index == parent.childCount) { continue }\n for (var after = parent.child(index);; after = after.firstChild) {\n if ((after.childCount == 0 && !after.inlineContent) || after.isAtom || after.type.spec.isolating) { return true }\n if (after.inlineContent) { return false }\n }\n }\n return true\n}\n\n// :: () → Plugin\n// Create a gap cursor plugin. When enabled, this will capture clicks\n// near and arrow-key-motion past places that don't have a normally\n// selectable position nearby, and create a gap cursor selection for\n// them. The cursor is drawn as an element with class\n// `ProseMirror-gapcursor`. You can either include\n// `style/gapcursor.css` from the package's directory or add your own\n// styles to make it visible.\nvar gapCursor = function() {\n return new Plugin({\n props: {\n decorations: drawGapCursor,\n\n createSelectionBetween: function createSelectionBetween(_view, $anchor, $head) {\n if ($anchor.pos == $head.pos && GapCursor.valid($head)) { return new GapCursor($head) }\n },\n\n handleClick: handleClick,\n handleKeyDown: handleKeyDown\n }\n })\n};\n\nvar handleKeyDown = keydownHandler({\n \"ArrowLeft\": arrow(\"horiz\", -1),\n \"ArrowRight\": arrow(\"horiz\", 1),\n \"ArrowUp\": arrow(\"vert\", -1),\n \"ArrowDown\": arrow(\"vert\", 1)\n});\n\nfunction arrow(axis, dir) {\n var dirStr = axis == \"vert\" ? (dir > 0 ? \"down\" : \"up\") : (dir > 0 ? \"right\" : \"left\");\n return function(state, dispatch, view) {\n var sel = state.selection;\n var $start = dir > 0 ? sel.$to : sel.$from, mustMove = sel.empty;\n if (sel instanceof TextSelection) {\n if (!view.endOfTextblock(dirStr) || $start.depth == 0) { return false }\n mustMove = false;\n $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before());\n }\n var $found = GapCursor.findFrom($start, dir, mustMove);\n if (!$found) { return false }\n if (dispatch) { dispatch(state.tr.setSelection(new GapCursor($found))); }\n return true\n }\n}\n\nfunction handleClick(view, pos, event) {\n if (!view.editable) { return false }\n var $pos = view.state.doc.resolve(pos);\n if (!GapCursor.valid($pos)) { return false }\n var ref = view.posAtCoords({left: event.clientX, top: event.clientY});\n var inside = ref.inside;\n if (inside > -1 && NodeSelection.isSelectable(view.state.doc.nodeAt(inside))) { return false }\n view.dispatch(view.state.tr.setSelection(new GapCursor($pos)));\n return true\n}\n\nfunction drawGapCursor(state) {\n if (!(state.selection instanceof GapCursor)) { return null }\n var node = document.createElement(\"div\");\n node.className = \"ProseMirror-gapcursor\";\n return DecorationSet.create(state.doc, [Decoration.widget(state.selection.head, node, {key: \"gapcursor\"})])\n}\n\nexport { GapCursor, gapCursor };\n//# sourceMappingURL=index.es.js.map\n","export default function crelt() {\n var elt = arguments[0]\n if (typeof elt == \"string\") elt = document.createElement(elt)\n var i = 1, next = arguments[1]\n if (next && typeof next == \"object\" && next.nodeType == null && !Array.isArray(next)) {\n for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) {\n var value = next[name]\n if (typeof value == \"string\") elt.setAttribute(name, value)\n else if (value != null) elt[name] = value\n }\n i++\n }\n for (; i < arguments.length; i++) add(elt, arguments[i])\n return elt\n}\n\nfunction add(elt, child) {\n if (typeof child == \"string\") {\n elt.appendChild(document.createTextNode(child))\n } else if (child == null) {\n } else if (child.nodeType != null) {\n elt.appendChild(child)\n } else if (Array.isArray(child)) {\n for (var i = 0; i < child.length; i++) add(elt, child[i])\n } else {\n throw new RangeError(\"Unsupported child node: \" + child)\n }\n}\n","import crel from 'crelt';\nimport { joinUp, lift, selectParentNode, setBlockType, wrapIn } from 'prosemirror-commands';\nimport { undo, redo } from 'prosemirror-history';\nimport { Plugin } from 'prosemirror-state';\n\nvar SVG = \"http://www.w3.org/2000/svg\";\nvar XLINK = \"http://www.w3.org/1999/xlink\";\n\nvar prefix = \"ProseMirror-icon\";\n\nfunction hashPath(path) {\n var hash = 0;\n for (var i = 0; i < path.length; i++)\n { hash = (((hash << 5) - hash) + path.charCodeAt(i)) | 0; }\n return hash\n}\n\nfunction getIcon(icon) {\n var node = document.createElement(\"div\");\n node.className = prefix;\n if (icon.path) {\n var name = \"pm-icon-\" + hashPath(icon.path).toString(16);\n if (!document.getElementById(name)) { buildSVG(name, icon); }\n var svg = node.appendChild(document.createElementNS(SVG, \"svg\"));\n svg.style.width = (icon.width / icon.height) + \"em\";\n var use = svg.appendChild(document.createElementNS(SVG, \"use\"));\n use.setAttributeNS(XLINK, \"href\", /([^#]*)/.exec(document.location)[1] + \"#\" + name);\n } else if (icon.dom) {\n node.appendChild(icon.dom.cloneNode(true));\n } else {\n node.appendChild(document.createElement(\"span\")).textContent = icon.text || '';\n if (icon.css) { node.firstChild.style.cssText = icon.css; }\n }\n return node\n}\n\nfunction buildSVG(name, data) {\n var collection = document.getElementById(prefix + \"-collection\");\n if (!collection) {\n collection = document.createElementNS(SVG, \"svg\");\n collection.id = prefix + \"-collection\";\n collection.style.display = \"none\";\n document.body.insertBefore(collection, document.body.firstChild);\n }\n var sym = document.createElementNS(SVG, \"symbol\");\n sym.id = name;\n sym.setAttribute(\"viewBox\", \"0 0 \" + data.width + \" \" + data.height);\n var path = sym.appendChild(document.createElementNS(SVG, \"path\"));\n path.setAttribute(\"d\", data.path);\n collection.appendChild(sym);\n}\n\nvar prefix$1 = \"ProseMirror-menu\";\n\n// ::- An icon or label that, when clicked, executes a command.\nvar MenuItem = function MenuItem(spec) {\n // :: MenuItemSpec\n // The spec used to create the menu item.\n this.spec = spec;\n};\n\n// :: (EditorView) → {dom: dom.Node, update: (EditorState) → bool}\n// Renders the icon according to its [display\n// spec](#menu.MenuItemSpec.display), and adds an event handler which\n// executes the command when the representation is clicked.\nMenuItem.prototype.render = function render (view) {\n var spec = this.spec;\n var dom = spec.render ? spec.render(view)\n : spec.icon ? getIcon(spec.icon)\n : spec.label ? crel(\"div\", null, translate(view, spec.label))\n : null;\n if (!dom) { throw new RangeError(\"MenuItem without icon or label property\") }\n if (spec.title) {\n var title = (typeof spec.title === \"function\" ? spec.title(view.state) : spec.title);\n dom.setAttribute(\"title\", translate(view, title));\n }\n if (spec.class) { dom.classList.add(spec.class); }\n if (spec.css) { dom.style.cssText += spec.css; }\n\n dom.addEventListener(\"mousedown\", function (e) {\n e.preventDefault();\n if (!dom.classList.contains(prefix$1 + \"-disabled\"))\n { spec.run(view.state, view.dispatch, view, e); }\n });\n\n function update(state) {\n if (spec.select) {\n var selected = spec.select(state);\n dom.style.display = selected ? \"\" : \"none\";\n if (!selected) { return false }\n }\n var enabled = true;\n if (spec.enable) {\n enabled = spec.enable(state) || false;\n setClass(dom, prefix$1 + \"-disabled\", !enabled);\n }\n if (spec.active) {\n var active = enabled && spec.active(state) || false;\n setClass(dom, prefix$1 + \"-active\", active);\n }\n return true\n }\n\n return {dom: dom, update: update}\n};\n\nfunction translate(view, text) {\n return view._props.translate ? view._props.translate(text) : text\n}\n\n// MenuItemSpec:: interface\n// The configuration object passed to the `MenuItem` constructor.\n//\n// run:: (EditorState, (Transaction), EditorView, dom.Event)\n// The function to execute when the menu item is activated.\n//\n// select:: ?(EditorState) → bool\n// Optional function that is used to determine whether the item is\n// appropriate at the moment. Deselected items will be hidden.\n//\n// enable:: ?(EditorState) → bool\n// Function that is used to determine if the item is enabled. If\n// given and returning false, the item will be given a disabled\n// styling.\n//\n// active:: ?(EditorState) → bool\n// A predicate function to determine whether the item is 'active' (for\n// example, the item for toggling the strong mark might be active then\n// the cursor is in strong text).\n//\n// render:: ?(EditorView) → dom.Node\n// A function that renders the item. You must provide either this,\n// [`icon`](#menu.MenuItemSpec.icon), or [`label`](#MenuItemSpec.label).\n//\n// icon:: ?Object\n// Describes an icon to show for this item. The object may specify\n// an SVG icon, in which case its `path` property should be an [SVG\n// path\n// spec](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/d),\n// and `width` and `height` should provide the viewbox in which that\n// path exists. Alternatively, it may have a `text` property\n// specifying a string of text that makes up the icon, with an\n// optional `css` property giving additional CSS styling for the\n// text. _Or_ it may contain `dom` property containing a DOM node.\n//\n// label:: ?string\n// Makes the item show up as a text label. Mostly useful for items\n// wrapped in a [drop-down](#menu.Dropdown) or similar menu. The object\n// should have a `label` property providing the text to display.\n//\n// title:: ?union\n// Defines DOM title (mouseover) text for the item.\n//\n// class:: ?string\n// Optionally adds a CSS class to the item's DOM representation.\n//\n// css:: ?string\n// Optionally adds a string of inline CSS to the item's DOM\n// representation.\n\nvar lastMenuEvent = {time: 0, node: null};\nfunction markMenuEvent(e) {\n lastMenuEvent.time = Date.now();\n lastMenuEvent.node = e.target;\n}\nfunction isMenuEvent(wrapper) {\n return Date.now() - 100 < lastMenuEvent.time &&\n lastMenuEvent.node && wrapper.contains(lastMenuEvent.node)\n}\n\n// ::- A drop-down menu, displayed as a label with a downwards-pointing\n// triangle to the right of it.\nvar Dropdown = function Dropdown(content, options) {\n this.options = options || {};\n this.content = Array.isArray(content) ? content : [content];\n};\n\n// :: (EditorView) → {dom: dom.Node, update: (EditorState)}\n// Render the dropdown menu and sub-items.\nDropdown.prototype.render = function render (view) {\n var this$1 = this;\n\n var content = renderDropdownItems(this.content, view);\n\n var label = crel(\"div\", {class: prefix$1 + \"-dropdown \" + (this.options.class || \"\"),\n style: this.options.css},\n translate(view, this.options.label));\n if (this.options.title) { label.setAttribute(\"title\", translate(view, this.options.title)); }\n var wrap = crel(\"div\", {class: prefix$1 + \"-dropdown-wrap\"}, label);\n var open = null, listeningOnClose = null;\n var close = function () {\n if (open && open.close()) {\n open = null;\n window.removeEventListener(\"mousedown\", listeningOnClose);\n }\n };\n label.addEventListener(\"mousedown\", function (e) {\n e.preventDefault();\n markMenuEvent(e);\n if (open) {\n close();\n } else {\n open = this$1.expand(wrap, content.dom);\n window.addEventListener(\"mousedown\", listeningOnClose = function () {\n if (!isMenuEvent(wrap)) { close(); }\n });\n }\n });\n\n function update(state) {\n var inner = content.update(state);\n wrap.style.display = inner ? \"\" : \"none\";\n return inner\n }\n\n return {dom: wrap, update: update}\n};\n\nDropdown.prototype.expand = function expand (dom, items) {\n var menuDOM = crel(\"div\", {class: prefix$1 + \"-dropdown-menu \" + (this.options.class || \"\")}, items);\n\n var done = false;\n function close() {\n if (done) { return }\n done = true;\n dom.removeChild(menuDOM);\n return true\n }\n dom.appendChild(menuDOM);\n return {close: close, node: menuDOM}\n};\n\nfunction renderDropdownItems(items, view) {\n var rendered = [], updates = [];\n for (var i = 0; i < items.length; i++) {\n var ref = items[i].render(view);\n var dom = ref.dom;\n var update = ref.update;\n rendered.push(crel(\"div\", {class: prefix$1 + \"-dropdown-item\"}, dom));\n updates.push(update);\n }\n return {dom: rendered, update: combineUpdates(updates, rendered)}\n}\n\nfunction combineUpdates(updates, nodes) {\n return function (state) {\n var something = false;\n for (var i = 0; i < updates.length; i++) {\n var up = updates[i](state);\n nodes[i].style.display = up ? \"\" : \"none\";\n if (up) { something = true; }\n }\n return something\n }\n}\n\n// ::- Represents a submenu wrapping a group of elements that start\n// hidden and expand to the right when hovered over or tapped.\nvar DropdownSubmenu = function DropdownSubmenu(content, options) {\n this.options = options || {};\n this.content = Array.isArray(content) ? content : [content];\n};\n\n// :: (EditorView) → {dom: dom.Node, update: (EditorState) → bool}\n// Renders the submenu.\nDropdownSubmenu.prototype.render = function render (view) {\n var items = renderDropdownItems(this.content, view);\n\n var label = crel(\"div\", {class: prefix$1 + \"-submenu-label\"}, translate(view, this.options.label));\n var wrap = crel(\"div\", {class: prefix$1 + \"-submenu-wrap\"}, label,\n crel(\"div\", {class: prefix$1 + \"-submenu\"}, items.dom));\n var listeningOnClose = null;\n label.addEventListener(\"mousedown\", function (e) {\n e.preventDefault();\n markMenuEvent(e);\n setClass(wrap, prefix$1 + \"-submenu-wrap-active\");\n if (!listeningOnClose)\n { window.addEventListener(\"mousedown\", listeningOnClose = function () {\n if (!isMenuEvent(wrap)) {\n wrap.classList.remove(prefix$1 + \"-submenu-wrap-active\");\n window.removeEventListener(\"mousedown\", listeningOnClose);\n listeningOnClose = null;\n }\n }); }\n });\n\n function update(state) {\n var inner = items.update(state);\n wrap.style.display = inner ? \"\" : \"none\";\n return inner\n }\n return {dom: wrap, update: update}\n};\n\n// :: (EditorView, [union]) → {dom: ?dom.DocumentFragment, update: (EditorState) → bool}\n// Render the given, possibly nested, array of menu elements into a\n// document fragment, placing separators between them (and ensuring no\n// superfluous separators appear when some of the groups turn out to\n// be empty).\nfunction renderGrouped(view, content) {\n var result = document.createDocumentFragment();\n var updates = [], separators = [];\n for (var i = 0; i < content.length; i++) {\n var items = content[i], localUpdates = [], localNodes = [];\n for (var j = 0; j < items.length; j++) {\n var ref = items[j].render(view);\n var dom = ref.dom;\n var update$1 = ref.update;\n var span = crel(\"span\", {class: prefix$1 + \"item\"}, dom);\n result.appendChild(span);\n localNodes.push(span);\n localUpdates.push(update$1);\n }\n if (localUpdates.length) {\n updates.push(combineUpdates(localUpdates, localNodes));\n if (i < content.length - 1)\n { separators.push(result.appendChild(separator())); }\n }\n }\n\n function update(state) {\n var something = false, needSep = false;\n for (var i = 0; i < updates.length; i++) {\n var hasContent = updates[i](state);\n if (i) { separators[i - 1].style.display = needSep && hasContent ? \"\" : \"none\"; }\n needSep = hasContent;\n if (hasContent) { something = true; }\n }\n return something\n }\n return {dom: result, update: update}\n}\n\nfunction separator() {\n return crel(\"span\", {class: prefix$1 + \"separator\"})\n}\n\n// :: Object\n// A set of basic editor-related icons. Contains the properties\n// `join`, `lift`, `selectParentNode`, `undo`, `redo`, `strong`, `em`,\n// `code`, `link`, `bulletList`, `orderedList`, and `blockquote`, each\n// holding an object that can be used as the `icon` option to\n// `MenuItem`.\nvar icons = {\n join: {\n width: 800, height: 900,\n path: \"M0 75h800v125h-800z M0 825h800v-125h-800z M250 400h100v-100h100v100h100v100h-100v100h-100v-100h-100z\"\n },\n lift: {\n width: 1024, height: 1024,\n path: \"M219 310v329q0 7-5 12t-12 5q-8 0-13-5l-164-164q-5-5-5-13t5-13l164-164q5-5 13-5 7 0 12 5t5 12zM1024 749v109q0 7-5 12t-12 5h-987q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h987q7 0 12 5t5 12zM1024 530v109q0 7-5 12t-12 5h-621q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h621q7 0 12 5t5 12zM1024 310v109q0 7-5 12t-12 5h-621q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h621q7 0 12 5t5 12zM1024 91v109q0 7-5 12t-12 5h-987q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h987q7 0 12 5t5 12z\"\n },\n selectParentNode: {text: \"\\u2b1a\", css: \"font-weight: bold\"},\n undo: {\n width: 1024, height: 1024,\n path: \"M761 1024c113-206 132-520-313-509v253l-384-384 384-384v248c534-13 594 472 313 775z\"\n },\n redo: {\n width: 1024, height: 1024,\n path: \"M576 248v-248l384 384-384 384v-253c-446-10-427 303-313 509-280-303-221-789 313-775z\"\n },\n strong: {\n width: 805, height: 1024,\n path: \"M317 869q42 18 80 18 214 0 214-191 0-65-23-102-15-25-35-42t-38-26-46-14-48-6-54-1q-41 0-57 5 0 30-0 90t-0 90q0 4-0 38t-0 55 2 47 6 38zM309 442q24 4 62 4 46 0 81-7t62-25 42-51 14-81q0-40-16-70t-45-46-61-24-70-8q-28 0-74 7 0 28 2 86t2 86q0 15-0 45t-0 45q0 26 0 39zM0 950l1-53q8-2 48-9t60-15q4-6 7-15t4-19 3-18 1-21 0-19v-37q0-561-12-585-2-4-12-8t-25-6-28-4-27-2-17-1l-2-47q56-1 194-6t213-5q13 0 39 0t38 0q40 0 78 7t73 24 61 40 42 59 16 78q0 29-9 54t-22 41-36 32-41 25-48 22q88 20 146 76t58 141q0 57-20 102t-53 74-78 48-93 27-100 8q-25 0-75-1t-75-1q-60 0-175 6t-132 6z\"\n },\n em: {\n width: 585, height: 1024,\n path: \"M0 949l9-48q3-1 46-12t63-21q16-20 23-57 0-4 35-165t65-310 29-169v-14q-13-7-31-10t-39-4-33-3l10-58q18 1 68 3t85 4 68 1q27 0 56-1t69-4 56-3q-2 22-10 50-17 5-58 16t-62 19q-4 10-8 24t-5 22-4 26-3 24q-15 84-50 239t-44 203q-1 5-7 33t-11 51-9 47-3 32l0 10q9 2 105 17-1 25-9 56-6 0-18 0t-18 0q-16 0-49-5t-49-5q-78-1-117-1-29 0-81 5t-69 6z\"\n },\n code: {\n width: 896, height: 1024,\n path: \"M608 192l-96 96 224 224-224 224 96 96 288-320-288-320zM288 192l-288 320 288 320 96-96-224-224 224-224-96-96z\"\n },\n link: {\n width: 951, height: 1024,\n path: \"M832 694q0-22-16-38l-118-118q-16-16-38-16-24 0-41 18 1 1 10 10t12 12 8 10 7 14 2 15q0 22-16 38t-38 16q-8 0-15-2t-14-7-10-8-12-12-10-10q-18 17-18 41 0 22 16 38l117 118q15 15 38 15 22 0 38-14l84-83q16-16 16-38zM430 292q0-22-16-38l-117-118q-16-16-38-16-22 0-38 15l-84 83q-16 16-16 38 0 22 16 38l118 118q15 15 38 15 24 0 41-17-1-1-10-10t-12-12-8-10-7-14-2-15q0-22 16-38t38-16q8 0 15 2t14 7 10 8 12 12 10 10q18-17 18-41zM941 694q0 68-48 116l-84 83q-47 47-116 47-69 0-116-48l-117-118q-47-47-47-116 0-70 50-119l-50-50q-49 50-118 50-68 0-116-48l-118-118q-48-48-48-116t48-116l84-83q47-47 116-47 69 0 116 48l117 118q47 47 47 116 0 70-50 119l50 50q49-50 118-50 68 0 116 48l118 118q48 48 48 116z\"\n },\n bulletList: {\n width: 768, height: 896,\n path: \"M0 512h128v-128h-128v128zM0 256h128v-128h-128v128zM0 768h128v-128h-128v128zM256 512h512v-128h-512v128zM256 256h512v-128h-512v128zM256 768h512v-128h-512v128z\"\n },\n orderedList: {\n width: 768, height: 896,\n path: \"M320 512h448v-128h-448v128zM320 768h448v-128h-448v128zM320 128v128h448v-128h-448zM79 384h78v-256h-36l-85 23v50l43-2v185zM189 590c0-36-12-78-96-78-33 0-64 6-83 16l1 66c21-10 42-15 67-15s32 11 32 28c0 26-30 58-110 112v50h192v-67l-91 2c49-30 87-66 87-113l1-1z\"\n },\n blockquote: {\n width: 640, height: 896,\n path: \"M0 448v256h256v-256h-128c0 0 0-128 128-128v-128c0 0-256 0-256 256zM640 320v-128c0 0-256 0-256 256v256h256v-256h-128c0 0 0-128 128-128z\"\n }\n};\n\n// :: MenuItem\n// Menu item for the `joinUp` command.\nvar joinUpItem = new MenuItem({\n title: \"Join with above block\",\n run: joinUp,\n select: function (state) { return joinUp(state); },\n icon: icons.join\n});\n\n// :: MenuItem\n// Menu item for the `lift` command.\nvar liftItem = new MenuItem({\n title: \"Lift out of enclosing block\",\n run: lift,\n select: function (state) { return lift(state); },\n icon: icons.lift\n});\n\n// :: MenuItem\n// Menu item for the `selectParentNode` command.\nvar selectParentNodeItem = new MenuItem({\n title: \"Select parent node\",\n run: selectParentNode,\n select: function (state) { return selectParentNode(state); },\n icon: icons.selectParentNode\n});\n\n// :: MenuItem\n// Menu item for the `undo` command.\nvar undoItem = new MenuItem({\n title: \"Undo last change\",\n run: undo,\n enable: function (state) { return undo(state); },\n icon: icons.undo\n});\n\n// :: MenuItem\n// Menu item for the `redo` command.\nvar redoItem = new MenuItem({\n title: \"Redo last undone change\",\n run: redo,\n enable: function (state) { return redo(state); },\n icon: icons.redo\n});\n\n// :: (NodeType, Object) → MenuItem\n// Build a menu item for wrapping the selection in a given node type.\n// Adds `run` and `select` properties to the ones present in\n// `options`. `options.attrs` may be an object or a function.\nfunction wrapItem(nodeType, options) {\n var passedOptions = {\n run: function run(state, dispatch) {\n // FIXME if (options.attrs instanceof Function) options.attrs(state, attrs => wrapIn(nodeType, attrs)(state))\n return wrapIn(nodeType, options.attrs)(state, dispatch)\n },\n select: function select(state) {\n return wrapIn(nodeType, options.attrs instanceof Function ? null : options.attrs)(state)\n }\n };\n for (var prop in options) { passedOptions[prop] = options[prop]; }\n return new MenuItem(passedOptions)\n}\n\n// :: (NodeType, Object) → MenuItem\n// Build a menu item for changing the type of the textblock around the\n// selection to the given type. Provides `run`, `active`, and `select`\n// properties. Others must be given in `options`. `options.attrs` may\n// be an object to provide the attributes for the textblock node.\nfunction blockTypeItem(nodeType, options) {\n var command = setBlockType(nodeType, options.attrs);\n var passedOptions = {\n run: command,\n enable: function enable(state) { return command(state) },\n active: function active(state) {\n var ref = state.selection;\n var $from = ref.$from;\n var to = ref.to;\n var node = ref.node;\n if (node) { return node.hasMarkup(nodeType, options.attrs) }\n return to <= $from.end() && $from.parent.hasMarkup(nodeType, options.attrs)\n }\n };\n for (var prop in options) { passedOptions[prop] = options[prop]; }\n return new MenuItem(passedOptions)\n}\n\n// Work around classList.toggle being broken in IE11\nfunction setClass(dom, cls, on) {\n if (on) { dom.classList.add(cls); }\n else { dom.classList.remove(cls); }\n}\n\nvar prefix$2 = \"ProseMirror-menubar\";\n\nfunction isIOS() {\n if (typeof navigator == \"undefined\") { return false }\n var agent = navigator.userAgent;\n return !/Edge\\/\\d/.test(agent) && /AppleWebKit/.test(agent) && /Mobile\\/\\w+/.test(agent)\n}\n\n// :: (Object) → Plugin\n// A plugin that will place a menu bar above the editor. Note that\n// this involves wrapping the editor in an additional `
`.\n//\n// options::-\n// Supports the following options:\n//\n// content:: [[MenuElement]]\n// Provides the content of the menu, as a nested array to be\n// passed to `renderGrouped`.\n//\n// floating:: ?bool\n// Determines whether the menu floats, i.e. whether it sticks to\n// the top of the viewport when the editor is partially scrolled\n// out of view.\nfunction menuBar(options) {\n return new Plugin({\n view: function view(editorView) { return new MenuBarView(editorView, options) }\n })\n}\n\nvar MenuBarView = function MenuBarView(editorView, options) {\n var this$1 = this;\n\n this.editorView = editorView;\n this.options = options;\n\n this.wrapper = crel(\"div\", {class: prefix$2 + \"-wrapper\"});\n this.menu = this.wrapper.appendChild(crel(\"div\", {class: prefix$2}));\n this.menu.className = prefix$2;\n this.spacer = null;\n\n editorView.dom.parentNode.replaceChild(this.wrapper, editorView.dom);\n this.wrapper.appendChild(editorView.dom);\n\n this.maxHeight = 0;\n this.widthForMaxHeight = 0;\n this.floating = false;\n\n var ref = renderGrouped(this.editorView, this.options.content);\n var dom = ref.dom;\n var update = ref.update;\n this.contentUpdate = update;\n this.menu.appendChild(dom);\n this.update();\n\n if (options.floating && !isIOS()) {\n this.updateFloat();\n var potentialScrollers = getAllWrapping(this.wrapper);\n this.scrollFunc = function (e) {\n var root = this$1.editorView.root;\n if (!(root.body || root).contains(this$1.wrapper)) {\n potentialScrollers.forEach(function (el) { return el.removeEventListener(\"scroll\", this$1.scrollFunc); });\n } else {\n this$1.updateFloat(e.target.getBoundingClientRect && e.target);\n }\n };\n potentialScrollers.forEach(function (el) { return el.addEventListener('scroll', this$1.scrollFunc); });\n }\n};\n\nMenuBarView.prototype.update = function update () {\n this.contentUpdate(this.editorView.state);\n\n if (this.floating) {\n this.updateScrollCursor();\n } else {\n if (this.menu.offsetWidth != this.widthForMaxHeight) {\n this.widthForMaxHeight = this.menu.offsetWidth;\n this.maxHeight = 0;\n }\n if (this.menu.offsetHeight > this.maxHeight) {\n this.maxHeight = this.menu.offsetHeight;\n this.menu.style.minHeight = this.maxHeight + \"px\";\n }\n }\n};\n\nMenuBarView.prototype.updateScrollCursor = function updateScrollCursor () {\n var selection = this.editorView.root.getSelection();\n if (!selection.focusNode) { return }\n var rects = selection.getRangeAt(0).getClientRects();\n var selRect = rects[selectionIsInverted(selection) ? 0 : rects.length - 1];\n if (!selRect) { return }\n var menuRect = this.menu.getBoundingClientRect();\n if (selRect.top < menuRect.bottom && selRect.bottom > menuRect.top) {\n var scrollable = findWrappingScrollable(this.wrapper);\n if (scrollable) { scrollable.scrollTop -= (menuRect.bottom - selRect.top); }\n }\n};\n\nMenuBarView.prototype.updateFloat = function updateFloat (scrollAncestor) {\n var parent = this.wrapper, editorRect = parent.getBoundingClientRect(),\n top = scrollAncestor ? Math.max(0, scrollAncestor.getBoundingClientRect().top) : 0;\n\n if (this.floating) {\n if (editorRect.top >= top || editorRect.bottom < this.menu.offsetHeight + 10) {\n this.floating = false;\n this.menu.style.position = this.menu.style.left = this.menu.style.top = this.menu.style.width = \"\";\n this.menu.style.display = \"\";\n this.spacer.parentNode.removeChild(this.spacer);\n this.spacer = null;\n } else {\n var border = (parent.offsetWidth - parent.clientWidth) / 2;\n this.menu.style.left = (editorRect.left + border) + \"px\";\n this.menu.style.display = (editorRect.top > window.innerHeight ? \"none\" : \"\");\n if (scrollAncestor) { this.menu.style.top = top + \"px\"; }\n }\n } else {\n if (editorRect.top < top && editorRect.bottom >= this.menu.offsetHeight + 10) {\n this.floating = true;\n var menuRect = this.menu.getBoundingClientRect();\n this.menu.style.left = menuRect.left + \"px\";\n this.menu.style.width = menuRect.width + \"px\";\n if (scrollAncestor) { this.menu.style.top = top + \"px\"; }\n this.menu.style.position = \"fixed\";\n this.spacer = crel(\"div\", {class: prefix$2 + \"-spacer\", style: (\"height: \" + (menuRect.height) + \"px\")});\n parent.insertBefore(this.spacer, this.menu);\n }\n }\n};\n\nMenuBarView.prototype.destroy = function destroy () {\n if (this.wrapper.parentNode)\n { this.wrapper.parentNode.replaceChild(this.editorView.dom, this.wrapper); }\n};\n\n// Not precise, but close enough\nfunction selectionIsInverted(selection) {\n if (selection.anchorNode == selection.focusNode) { return selection.anchorOffset > selection.focusOffset }\n return selection.anchorNode.compareDocumentPosition(selection.focusNode) == Node.DOCUMENT_POSITION_FOLLOWING\n}\n\nfunction findWrappingScrollable(node) {\n for (var cur = node.parentNode; cur; cur = cur.parentNode)\n { if (cur.scrollHeight > cur.clientHeight) { return cur } }\n}\n\nfunction getAllWrapping(node) {\n var res = [window];\n for (var cur = node.parentNode; cur; cur = cur.parentNode)\n { res.push(cur); }\n return res\n}\n\nexport { Dropdown, DropdownSubmenu, MenuItem, blockTypeItem, icons, joinUpItem, liftItem, menuBar, redoItem, renderGrouped, selectParentNodeItem, undoItem, wrapItem };\n//# sourceMappingURL=index.es.js.map\n","import { findWrapping, ReplaceAroundStep, canSplit, liftTarget } from 'prosemirror-transform';\nimport { NodeRange, Fragment, Slice } from 'prosemirror-model';\n\nvar olDOM = [\"ol\", 0], ulDOM = [\"ul\", 0], liDOM = [\"li\", 0];\n\n// :: NodeSpec\n// An ordered list [node spec](#model.NodeSpec). Has a single\n// attribute, `order`, which determines the number at which the list\n// starts counting, and defaults to 1. Represented as an `
    `\n// element.\nvar orderedList = {\n attrs: {order: {default: 1}},\n parseDOM: [{tag: \"ol\", getAttrs: function getAttrs(dom) {\n return {order: dom.hasAttribute(\"start\") ? +dom.getAttribute(\"start\") : 1}\n }}],\n toDOM: function toDOM(node) {\n return node.attrs.order == 1 ? olDOM : [\"ol\", {start: node.attrs.order}, 0]\n }\n};\n\n// :: NodeSpec\n// A bullet list node spec, represented in the DOM as `