{"_id":"@ac-synth/yjs","name":"@ac-synth/yjs","dist-tags":{"latest":"13.5.39-alpha1"},"versions":{"13.5.39-alpha1":{"name":"@ac-synth/yjs","version":"13.5.39-alpha1","description":"Shared Editing Library","main":"./dist/yjs.cjs","module":"./dist/yjs.mjs","types":"./dist/src/index.d.ts","type":"module","sideEffects":false,"funding":{"type":"GitHub Sponsors ❤","url":"https://github.com/sponsors/dmonad"},"scripts":{"test":"npm run dist && node ./dist/tests.cjs --repetition-time 50","test-extensive":"npm run lint && npm run dist && node ./dist/tests.cjs --production --repetition-time 10000","dist":"rm -rf dist && rollup -c && tsc","watch":"rollup -wc","lint":"markdownlint README.md && standard && tsc","docs":"rm -rf docs; jsdoc --configure ./.jsdoc.json --verbose --readme ./README.md --package ./package.json || true","serve-docs":"npm run docs && http-server ./docs/","preversion":"npm run lint && PRODUCTION=1 npm run dist && npm run docs && node ./dist/tests.cjs --repetition-time 1000 && test -e dist/src/index.d.ts && test -e dist/yjs.cjs && test -e dist/yjs.cjs","debug":"concurrently 'http-server -o test.html' 'npm run watch'","trace-deopt":"clear && rollup -c  && node --trace-deopt dist/test.cjs","trace-opt":"clear && rollup -c  && node --trace-opt dist/test.cjs"},"exports":{".":{"types":"./dist/src/index.d.ts","import":"./dist/yjs.mjs","require":"./dist/yjs.cjs"},"./src/index.js":"./src/index.js","./tests/testHelper.js":"./tests/testHelper.js","./testHelper":"./dist/testHelper.mjs","./package.json":"./package.json"},"dictionaries":{"test":"tests"},"standard":{"ignore":["/dist","/node_modules","/docs"]},"repository":{"type":"git","url":"git+https://github.com/yjs/yjs.git"},"keywords":["Yjs","CRDT","offline","offline-first","shared-editing","concurrency","collaboration"],"author":{"name":"Kevin Jahns"},"email":"kevin.jahns@protonmail.com","license":"MIT","bugs":{"url":"https://github.com/yjs/yjs/issues"},"homepage":"https://docs.yjs.dev","dependencies":{"lib0":"^0.2.49"},"devDependencies":{"@rollup/plugin-commonjs":"^17.0.0","@rollup/plugin-node-resolve":"^11.2.1","concurrently":"^3.6.1","http-server":"^0.12.3","jsdoc":"^3.6.7","markdownlint-cli":"^0.23.2","rollup":"^2.60.0","standard":"^16.0.4","tui-jsdoc-template":"^1.2.2","typescript":"^4.4.4","y-protocols":"^1.0.5"},"gitHead":"a5e0448a92b86d6ec2edc5d486e361e30e29a5d5","_id":"@ac-synth/yjs@13.5.39-alpha1","_nodeVersion":"18.0.0","_npmVersion":"8.6.0","dist":{"integrity":"sha512-2c2+e2XdBLvIShA9WrSn3GTEoBzoIkQzRBEXaPN4BW9OO/W8FooCuYISNiy5ZkzNml+bHQB1W91GgqlTCQ47Xg==","shasum":"81b0257ea3191fe6e5f0fb6520101d91a5c96a8e","tarball":"https://registry.npmjs.org/@ac-synth/yjs/-/yjs-13.5.39-alpha1.tgz","fileCount":93,"unpackedSize":2114367,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCo2QHeqixh8KU1e3XJHWI74wV4JeecWP1G1qbcPtp+GgIgGh8WB3KDnHA99hRX4gM4UgAT9nnl94z9xjEhWUOMPHE="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJiqv+0ACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmplEg//VKL+RJg8TmACoRPEcAyjj7AxkMZhMlj+tlxedLjYO+sxNhd6\r\npaKuY+D0rJLtL6y0TMo575VDHVrMoUKgRcDACvk1lNx6uB+KmW+bvxJyIRbc\r\nuFJ3d9L8ovqFhmYclGX6IXKL1c2ki7RcesRzAOfxjXbj5J2Bxitl7MBptD25\r\nti5FJJ9zd4Ya/hVjIHXFXBlumCW97EIOvcqAYKboCfeksO+qCiJdm5OgRRpW\r\ntk+b5Pgz4HVdoKVnBONosSzmV32SILCUoSIhkZShNewFM/9YgdL+teEuvfE8\r\nx7PaSW9bf0EBq3NA+e8lGWwIWHkZd55YYGa8Kx5XOSfRJmfmUiTb8uSt9jsj\r\npRjAu31SwDMwnIbNEKahF8nRsZS6v144e7C1Q2xc6aFvxq1m1EQUw2tPVP+L\r\neHiv7o6Pnh1nEMDLRGgOZTHloH+NIWXgH6cMqFOhvODnr6t2L32EbSF8dq7h\r\ncJmZkR2WSSdqwyCJ2zdf8Be13W3x9L2T/gYe+uNzZW8iNRaxaXbpxT0auCbZ\r\nq2iVZsqCcEr3g20LjSb4cT7Vr3hoivWMSEZkXsFwqoQONlAmblzM/ZW3JaTR\r\nPZth3ouowyQQCt/gNa2AXuIgTJa/OFEISbkJz7WUFEN00znr8v/fLUaWnNY2\r\nUCJMCWaM2WTNH7UKKrL09WNHMz4AxXyO6QE=\r\n=7u3U\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"ac-synth","email":"adam@synthesia.io"},"directories":{},"maintainers":[{"name":"ac-synth","email":"adam@synthesia.io"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/yjs_13.5.39-alpha1_1655373748271_0.3314641966735621"},"_hasShrinkwrap":false}},"time":{"created":"2022-06-16T10:02:28.216Z","13.5.39-alpha1":"2022-06-16T10:02:28.513Z","modified":"2022-06-16T10:02:28.672Z"},"maintainers":[{"name":"ac-synth","email":"adam@synthesia.io"}],"description":"Shared Editing Library","homepage":"https://docs.yjs.dev","keywords":["Yjs","CRDT","offline","offline-first","shared-editing","concurrency","collaboration"],"repository":{"type":"git","url":"git+https://github.com/yjs/yjs.git"},"author":{"name":"Kevin Jahns"},"bugs":{"url":"https://github.com/yjs/yjs/issues"},"license":"MIT","readme":"\n# ![Yjs](https://yjs.dev/images/logo/yjs-120x120.png)\n\n> A CRDT framework with a powerful abstraction of shared data\n\nYjs is a [CRDT implementation](#Yjs-CRDT-Algorithm) that exposes its internal\ndata structure as *shared types*. Shared types are common data types like `Map`\nor `Array` with superpowers: changes are automatically distributed to other\npeers and merged without merge conflicts.\n\nYjs is **network agnostic** (p2p!), supports many existing **rich text\neditors**, **offline editing**, **version snapshots**, **undo/redo** and\n**shared cursors**. It scales well with an unlimited number of users and is well\nsuited for even large documents.\n\n* Demos: [https://github.com/yjs/yjs-demos](https://github.com/yjs/yjs-demos)\n* Discuss: [https://discuss.yjs.dev](https://discuss.yjs.dev)\n* Chat: [Gitter](https://gitter.im/Yjs/community) | [Discord](https://discord.gg/T3nqMT6qbM)\n* Benchmark Yjs vs. Automerge:\n  [https://github.com/dmonad/crdt-benchmarks](https://github.com/dmonad/crdt-benchmarks)\n* Podcast [**\"Yjs Deep Dive into real time collaborative editing solutions\":**](https://www.tag1consulting.com/blog/deep-dive-real-time-collaborative-editing-solutions-tagteamtalk-001-0)\n* Podcast [**\"Google Docs-style editing in Gutenberg with the YJS framework\":**](https://publishpress.com/blog/yjs/)\n\n:construction_worker_woman: If you are looking for professional support, please\nconsider supporting this project via a \"support contract\" on\n[GitHub Sponsors](https://github.com/sponsors/dmonad). I will attend your issues\nquicker and we can discuss questions and problems in regular video conferences.\nOtherwise you can find help on our community [discussion board](https://discuss.yjs.dev).\n\n## Sponsorship\n\nPlease contribute to the project financially - especially if your company relies\non Yjs. [![Become a Sponsor](https://img.shields.io/static/v1?label=Become%20a%20Sponsor&message=%E2%9D%A4&logo=GitHub&style=flat&color=d42f2d)](https://github.com/sponsors/dmonad)\n\n## Who is using Yjs\n\n* [Dynaboard](https://dynaboard.com/) Build web apps collaboratively. :star2:\n* [Relm](https://www.relm.us/) A collaborative gameworld for teamwork and\n  community. :star:\n* [Room.sh](https://room.sh/) A meeting application with integrated\n  collaborative drawing, editing, and coding tools. :star:\n* [Nimbus Note](https://nimbusweb.me/note.php) A note-taking app designed by\n  Nimbus Web. :star:\n* [Pluxbox RadioManager](https://getradiomanager.com/) A web-based app to\n  collaboratively organize radio broadcasts. :star:\n* [Serenity Notes](https://www.serenity.re/en/notes) End-to-end encrypted\n  collaborative notes app.\n* [PRSM](https://prsm.uk/) Collaborative mind-mapping and system visualisation. *[(source)](https://github.com/micrology/prsm)*\n* [Alldone](https://alldone.app/) A next-gen project management and\n  collaboration platform.\n* [Living Spec](https://livingspec.com/) A modern way for product teams to collaborate.\n* [Slidebeamer](https://slidebeamer.com/) Presentation app.\n* [BlockSurvey](https://blocksurvey.io) End-to-end encryption for your forms/surveys.\n* [Skiff](https://skiff.org/) Private, decentralized workspace.\n\n## Table of Contents\n\n* [Overview](#Overview)\n  * [Bindings](#Bindings)\n  * [Providers](#Providers)\n* [Getting Started](#Getting-Started)\n* [API](#API)\n  * [Shared Types](#Shared-Types)\n  * [Y.Doc](#YDoc)\n  * [Document Updates](#Document-Updates)\n  * [Relative Positions](#Relative-Positions)\n  * [Y.UndoManager](#YUndoManager)\n* [Yjs CRDT Algorithm](#Yjs-CRDT-Algorithm)\n* [License and Author](#License-and-Author)\n\n## Overview\n\nThis repository contains a collection of shared types that can be observed for\nchanges and manipulated concurrently. Network functionality and two-way-bindings\nare implemented in separate modules.\n\n### Bindings\n\n| Name | Cursors | Binding |  Demo |\n|---|:-:|---|---|\n| [ProseMirror](https://prosemirror.net/) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | ✔ | [y-prosemirror](https://github.com/yjs/y-prosemirror) | [demo](https://demos.yjs.dev/prosemirror/prosemirror.html) |\n| [Quill](https://quilljs.com/) | ✔ | [y-quill](https://github.com/yjs/y-quill) | [demo](https://demos.yjs.dev/quill/quill.html) |\n| [CodeMirror](https://codemirror.net/) | ✔ | [y-codemirror](https://github.com/yjs/y-codemirror) | [demo](https://demos.yjs.dev/codemirror/codemirror.html) |\n| [Monaco](https://microsoft.github.io/monaco-editor/) | ✔ | [y-monaco](https://github.com/yjs/y-monaco) | [demo](https://demos.yjs.dev/monaco/monaco.html) |\n| [Slate](https://github.com/ianstormtaylor/slate) | ✔ | [slate-yjs](https://github.com/bitphinix/slate-yjs) | [demo](https://bitphinix.github.io/slate-yjs-example) |\n| [valtio](https://github.com/pmndrs/valtio) |  | [valtio-yjs](https://github.com/dai-shi/valtio-yjs) | [demo](https://codesandbox.io/s/valtio-yjs-demo-ox3iy) |\n| [immer](https://github.com/immerjs/immer) |  | [immer-yjs](https://github.com/sep2/immer-yjs) | [demo](https://codesandbox.io/s/immer-yjs-demo-6e0znb) |\n| React / Vue / Svelte / MobX | | [SyncedStore](https://syncedstore.org) | [demo](https://syncedstore.org/docs/react) |\n\n### Providers\n\nSetting up the communication between clients, managing awareness information,\nand storing shared data for offline usage is quite a hassle. **Providers**\nmanage all that for you and are the perfect starting point for your\ncollaborative app.\n\n<dl>\n  <dt><a href=\"https://github.com/yjs/y-webrtc\">y-webrtc</a></dt>\n  <dd>\nPropagates document updates peer-to-peer using WebRTC. The peers exchange\nsignaling data over signaling servers. Publically available signaling servers\nare available. Communication over the signaling servers can be encrypted by\nproviding a shared secret, keeping the connection information and the shared\ndocument private.\n  </dd>\n  <dt><a href=\"https://github.com/yjs/y-websocket\">y-websocket</a></dt>\n  <dd>\nA module that contains a simple websocket backend and a websocket client that\nconnects to that backend. The backend can be extended to persist updates in a\nleveldb database.\n  </dd>\n  <dt><a href=\"https://github.com/yjs/y-indexeddb\">y-indexeddb</a></dt>\n  <dd>\nEfficiently persists document updates to the browsers indexeddb database.\nThe document is immediately available and only diffs need to be synced through the\nnetwork provider.\n  </dd>\n  <dt><a href=\"https://github.com/marcopolo/y-libp2p\">y-libp2p</a></dt>\n  <dd>\nUses <a href=\"https://libp2p.io/\">libp2p</a> to propagate updates via\n<a href=\"https://github.com/libp2p/specs/tree/master/pubsub/gossipsub\">GossipSub</a>.\nAlso includes a peer-sync mechanism to catch up on missed updates.\n  </dd>\n  <dt><a href=\"https://github.com/yjs/y-dat\">y-dat</a></dt>\n  <dd>\n[WIP] Write document updates efficiently to the dat network using\n<a href=\"https://github.com/kappa-db/multifeed\">multifeed</a>. Each client has\nan append-only log of CRDT local updates (hypercore). Multifeed manages and sync\nhypercores and y-dat listens to changes and applies them to the Yjs document.\n</dd>\n  <dt><a href=\"https://github.com/yousefED/matrix-crdt\">Matrix-CRDT</a></dt>\n  <dd>\nUse <a href=\"https://www.matrix.org\">Matrix</a> as an off-the-shelf backend for\nYjs by using the <a href=\"https://github.com/yousefED/matrix-crdt\">MatrixProvider</a>.\nUse Matrix as transport and storage of Yjs updates, so you can focus building\nyour client app and Matrix can provide powerful features like Authentication,\nAuthorization, Federation, hosting (self-hosting or SaaS) and even End-to-End\nEncryption (E2EE).\n</dd>\n</dl>\n\n## Getting Started\n\nInstall Yjs and a provider with your favorite package manager:\n\n```sh\nnpm i yjs y-websocket\n```\n\nStart the y-websocket server:\n\n```sh\nPORT=1234 node ./node_modules/y-websocket/bin/server.js\n```\n\n### Example: Observe types\n\n```js\nconst yarray = doc.getArray('my-array')\nyarray.observe(event => {\n  console.log('yarray was modified')\n})\n// every time a local or remote client modifies yarray, the observer is called\nyarray.insert(0, ['val']) // => \"yarray was modified\"\n```\n\n### Example: Nest types\n\nRemember, shared types are just plain old data types. The only limitation is\nthat a shared type must exist only once in the shared document.\n\n```js\nconst ymap = doc.getMap('map')\nconst foodArray = new Y.Array()\nfoodArray.insert(0, ['apple', 'banana'])\nymap.set('food', foodArray)\nymap.get('food') === foodArray // => true\nymap.set('fruit', foodArray) // => Error! foodArray is already defined\n```\n\nNow you understand how types are defined on a shared document. Next you can jump\nto the [demo repository](https://github.com/yjs/yjs-demos) or continue reading\nthe API docs.\n\n### Example: Using and combining providers\n\nAny of the Yjs providers can be combined with each other. So you can sync data\nover different network technologies.\n\nIn most cases you want to use a network provider (like y-websocket or y-webrtc)\nin combination with a persistence provider (y-indexeddb in the browser).\nPersistence allows you to load the document faster and to persist data that is\ncreated while offline.\n\nFor the sake of this demo we combine two different network providers with a\npersistence provider.\n\n```js\nimport * as Y from 'yjs'\nimport { WebrtcProvider } from 'y-webrtc'\nimport { WebsocketProvider } from 'y-websocket'\nimport { IndexeddbPersistence } from 'y-indexeddb'\n\nconst ydoc = new Y.Doc()\n\n// this allows you to instantly get the (cached) documents data\nconst indexeddbProvider = new IndexeddbPersistence('count-demo', ydoc)\nindexeddbProvider.whenSynced.then(() => {\n  console.log('loaded data from indexed db')\n})\n\n// Sync clients with the y-webrtc provider.\nconst webrtcProvider = new WebrtcProvider('count-demo', ydoc)\n\n// Sync clients with the y-websocket provider\nconst websocketProvider = new WebsocketProvider(\n  'wss://demos.yjs.dev', 'count-demo', ydoc\n)\n\n// array of numbers which produce a sum\nconst yarray = ydoc.getArray('count')\n\n// observe changes of the sum\nyarray.observe(event => {\n  // print updates when the data changes\n  console.log('new sum: ' + yarray.toArray().reduce((a,b) => a + b))\n})\n\n// add 1 to the sum\nyarray.push([1]) // => \"new sum: 1\"\n```\n\n## API\n\n```js\nimport * as Y from 'yjs'\n```\n\n### Shared Types\n\n<details>\n  <summary><b>Y.Array</b></summary>\n  <br>\n  <p>\nA shareable Array-like type that supports efficient insert/delete of elements\nat any position. Internally it uses a linked list of Arrays that is split when\nnecessary.\n  </p>\n  <pre>const yarray = new Y.Array()</pre>\n  <dl>\n    <b><code>parent:Y.AbstractType|null</code></b>\n    <dd></dd>\n    <b><code>insert(index:number, content:Array&lt;object|boolean|Array|string|number|null|Uint8Array|Y.Type&gt;)</code></b>\n    <dd>\nInsert content at <var>index</var>. Note that content is an array of elements.\nI.e. <code>array.insert(0, [1])</code> splices the list and inserts 1 at\nposition 0.\n    </dd>\n    <b><code>push(Array&lt;Object|boolean|Array|string|number|null|Uint8Array|Y.Type&gt;)</code></b>\n    <dd></dd>\n    <b><code>unshift(Array&lt;Object|boolean|Array|string|number|null|Uint8Array|Y.Type&gt;)</code></b>\n    <dd></dd>\n    <b><code>delete(index:number, length:number)</code></b>\n    <dd></dd>\n    <b><code>get(index:number)</code></b>\n    <dd></dd>\n    <b><code>slice(start:number, end:number):Array&lt;Object|boolean|Array|string|number|null|Uint8Array|Y.Type&gt;</code></b>\n    <dd>Retrieve a range of content</dd>\n    <b><code>length:number</code></b>\n    <dd></dd>\n    <b>\n      <code>\nforEach(function(value:object|boolean|Array|string|number|null|Uint8Array|Y.Type,\n index:number, array: Y.Array))\n      </code>\n    </b>\n    <dd></dd>\n    <b><code>map(function(T, number, YArray):M):Array&lt;M&gt;</code></b>\n    <dd></dd>\n    <b><code>toArray():Array&lt;object|boolean|Array|string|number|null|Uint8Array|Y.Type&gt;</code></b>\n    <dd>Copies the content of this YArray to a new Array.</dd>\n    <b><code>toJSON():Array&lt;Object|boolean|Array|string|number|null&gt;</code></b>\n    <dd>\nCopies the content of this YArray to a new Array. It transforms all child types\nto JSON using their <code>toJSON</code> method.\n    </dd>\n    <b><code>[Symbol.Iterator]</code></b>\n    <dd>\n      Returns an YArray Iterator that contains the values for each index in the array.\n      <pre>for (let value of yarray) { .. }</pre>\n    </dd>\n    <b><code>observe(function(YArrayEvent, Transaction):void)</code></b>\n    <dd>\nAdds an event listener to this type that will be called synchronously every time\nthis type is modified. In the case this type is modified in the event listener,\nthe event listener will be called again after the current event listener returns.\n    </dd>\n    <b><code>unobserve(function(YArrayEvent, Transaction):void)</code></b>\n    <dd>\n      Removes an <code>observe</code> event listener from this type.\n    </dd>\n    <b><code>observeDeep(function(Array&lt;YEvent&gt;, Transaction):void)</code></b>\n    <dd>\nAdds an event listener to this type that will be called synchronously every time\nthis type or any of its children is modified. In the case this type is modified\nin the event listener, the event listener will be called again after the current\nevent listener returns. The event listener receives all Events created by itself\nor any of its children.\n    </dd>\n    <b><code>unobserveDeep(function(Array&lt;YEvent&gt;, Transaction):void)</code></b>\n    <dd>\n      Removes an <code>observeDeep</code> event listener from this type.\n    </dd>\n  </dl>\n</details>\n<details>\n  <summary><b>Y.Map</b></summary>\n  <br>\n  <p>\n    A shareable Map type.\n  </p>\n  <pre><code>const ymap = new Y.Map()</code></pre>\n  <dl>\n    <b><code>parent:Y.AbstractType|null</code></b>\n    <dd></dd>\n    <b><code>size: number</code></b>\n    <dd>Total number of key/value pairs.</dd>\n    <b><code>get(key:string):object|boolean|string|number|null|Uint8Array|Y.Type</code></b>\n    <dd></dd>\n    <b><code>set(key:string, value:object|boolean|string|number|null|Uint8Array|Y.Type)</code></b>\n    <dd></dd>\n    <b><code>delete(key:string)</code></b>\n    <dd></dd>\n    <b><code>has(key:string):boolean</code></b>\n    <dd></dd>\n    <b><code>get(index:number)</code></b>\n    <dd></dd>\n    <b><code>clear()</code></b>\n    <dd>Removes all elements from this YMap.</dd>\n    <b><code>clone():Y.Map</code></b>\n    <dd>Clone this type into a fresh Yjs type.</dd>\n    <b><code>toJSON():Object&lt;string, Object|boolean|Array|string|number|null|Uint8Array&gt;</code></b>\n    <dd>\nCopies the <code>[key,value]</code> pairs of this YMap to a new Object.It\ntransforms all child types to JSON using their <code>toJSON</code> method.\n    </dd>\n    <b><code>forEach(function(value:object|boolean|Array|string|number|null|Uint8Array|Y.Type,\n key:string, map: Y.Map))</code></b>\n    <dd>\n      Execute the provided function once for every key-value pair.\n    </dd>\n    <b><code>[Symbol.Iterator]</code></b>\n    <dd>\n      Returns an Iterator of <code>[key, value]</code> pairs.\n      <pre>for (let [key, value] of ymap) { .. }</pre>\n    </dd>\n    <b><code>entries()</code></b>\n    <dd>\n      Returns an Iterator of <code>[key, value]</code> pairs.\n    </dd>\n    <b><code>values()</code></b>\n    <dd>\n      Returns an Iterator of all values.\n    </dd>\n    <b><code>keys()</code></b>\n    <dd>\n      Returns an Iterator of all keys.\n    </dd>\n    <b><code>observe(function(YMapEvent, Transaction):void)</code></b>\n    <dd>\nAdds an event listener to this type that will be called synchronously every time\nthis type is modified. In the case this type is modified in the event listener,\nthe event listener will be called again after the current event listener returns.\n    </dd>\n    <b><code>unobserve(function(YMapEvent, Transaction):void)</code></b>\n    <dd>\n      Removes an <code>observe</code> event listener from this type.\n    </dd>\n    <b><code>observeDeep(function(Array&lt;YEvent&gt;, Transaction):void)</code></b>\n    <dd>\nAdds an event listener to this type that will be called synchronously every time\nthis type or any of its children is modified. In the case this type is modified\nin the event listener, the event listener will be called again after the current\nevent listener returns. The event listener receives all Events created by itself\nor any of its children.\n    </dd>\n    <b><code>unobserveDeep(function(Array&lt;YEvent&gt;, Transaction):void)</code></b>\n    <dd>\n      Removes an <code>observeDeep</code> event listener from this type.\n    </dd>\n  </dl>\n</details>\n\n<details>\n  <summary><b>Y.Text</b></summary>\n  <br>\n  <p>\nA shareable type that is optimized for shared editing on text. It allows to\nassign properties to ranges in the text. This makes it possible to implement\nrich-text bindings to this type.\n  </p>\n  <p>\nThis type can also be transformed to the\n<a href=\"https://quilljs.com/docs/delta\">delta format</a>. Similarly the\nYTextEvents compute changes as deltas.\n  </p>\n  <pre>const ytext = new Y.Text()</pre>\n  <dl>\n    <b><code>parent:Y.AbstractType|null</code></b>\n    <dd></dd>\n    <b><code>insert(index:number, content:string, [formattingAttributes:Object&lt;string,string&gt;])</code></b>\n    <dd>\n      Insert a string at <var>index</var> and assign formatting attributes to it.\n      <pre>ytext.insert(0, 'bold text', { bold: true })</pre>\n    </dd>\n    <b><code>delete(index:number, length:number)</code></b>\n    <dd></dd>\n    <b><code>format(index:number, length:number, formattingAttributes:Object&lt;string,string&gt;)</code></b>\n    <dd>Assign formatting attributes to a range in the text</dd>\n    <b><code>applyDelta(delta: Delta, opts:Object&lt;string,any&gt;)</code></b>\n    <dd>\n        See <a href=\"https://quilljs.com/docs/delta/\">Quill Delta</a>\n        Can set options for preventing remove ending newLines, default is true.\n        <pre>ytext.applyDelta(delta, { sanitize: false })</pre>\n    </dd>\n    <b><code>length:number</code></b>\n    <dd></dd>\n    <b><code>toString():string</code></b>\n    <dd>Transforms this type, without formatting options, into a string.</dd>\n    <b><code>toJSON():string</code></b>\n    <dd>See <code>toString</code></dd>\n    <b><code>toDelta():Delta</code></b>\n    <dd>\nTransforms this type to a <a href=\"https://quilljs.com/docs/delta/\">Quill Delta</a>\n    </dd>\n    <b><code>observe(function(YTextEvent, Transaction):void)</code></b>\n    <dd>\nAdds an event listener to this type that will be called synchronously every time\nthis type is modified. In the case this type is modified in the event listener,\nthe event listener will be called again after the current event listener returns.\n    </dd>\n    <b><code>unobserve(function(YTextEvent, Transaction):void)</code></b>\n    <dd>\n      Removes an <code>observe</code> event listener from this type.\n    </dd>\n    <b><code>observeDeep(function(Array&lt;YEvent&gt;, Transaction):void)</code></b>\n    <dd>\nAdds an event listener to this type that will be called synchronously every time\nthis type or any of its children is modified. In the case this type is modified\nin the event listener, the event listener will be called again after the current\nevent listener returns. The event listener receives all Events created by itself\nor any of its children.\n    </dd>\n    <b><code>unobserveDeep(function(Array&lt;YEvent&gt;, Transaction):void)</code></b>\n    <dd>\n      Removes an <code>observeDeep</code> event listener from this type.\n    </dd>\n  </dl>\n</details>\n\n<details>\n  <summary><b>Y.XmlFragment</b></summary>\n  <br>\n  <p>\n    A container that holds an Array of Y.XmlElements.\n  </p>\n  <pre><code>const yxml = new Y.XmlFragment()</code></pre>\n  <dl>\n    <b><code>parent:Y.AbstractType|null</code></b>\n    <dd></dd>\n    <b><code>firstChild:Y.XmlElement|Y.XmlText|null</code></b>\n    <dd></dd>\n    <b><code>insert(index:number, content:Array&lt;Y.XmlElement|Y.XmlText&gt;)</code></b>\n    <dd></dd>\n    <b><code>delete(index:number, length:number)</code></b>\n    <dd></dd>\n    <b><code>get(index:number)</code></b>\n    <dd></dd>\n    <b><code>slice(start:number, end:number):Array&lt;Y.XmlElement|Y.XmlText&gt;</code></b>\n    <dd>Retrieve a range of content</dd>\n    <b><code>length:number</code></b>\n    <dd></dd>\n    <b><code>clone():Y.XmlFragment</code></b>\n    <dd>Clone this type into a fresh Yjs type.</dd>\n    <b><code>toArray():Array&lt;Y.XmlElement|Y.XmlText&gt;</code></b>\n    <dd>Copies the children to a new Array.</dd>\n    <b><code>toDOM():DocumentFragment</code></b>\n    <dd>Transforms this type and all children to new DOM elements.</dd>\n    <b><code>toString():string</code></b>\n    <dd>Get the XML serialization of all descendants.</dd>\n    <b><code>toJSON():string</code></b>\n    <dd>See <code>toString</code>.</dd>\n    <b><code>createTreeWalker(filter: function(AbstractType&lt;any&gt;):boolean):Iterable</code></b>\n    <dd>Create an Iterable that walks through the children.</dd>\n    <b><code>observe(function(YXmlEvent, Transaction):void)</code></b>\n    <dd>\nAdds an event listener to this type that will be called synchronously every time\nthis type is modified. In the case this type is modified in the event listener,\nthe event listener will be called again after the current event listener returns.\n    </dd>\n    <b><code>unobserve(function(YXmlEvent, Transaction):void)</code></b>\n    <dd>\n      Removes an <code>observe</code> event listener from this type.\n    </dd>\n    <b><code>observeDeep(function(Array&lt;YEvent&gt;, Transaction):void)</code></b>\n    <dd>\nAdds an event listener to this type that will be called synchronously every time\nthis type or any of its children is modified. In the case this type is modified\nin the event listener, the event listener will be called again after the current\nevent listener returns. The event listener receives all Events created by itself\nor any of its children.\n    </dd>\n    <b><code>unobserveDeep(function(Array&lt;YEvent&gt;, Transaction):void)</code></b>\n    <dd>\n      Removes an <code>observeDeep</code> event listener from this type.\n    </dd>\n  </dl>\n</details>\n\n<details>\n  <summary><b>Y.XmlElement</b></summary>\n  <br>\n  <p>\nA shareable type that represents an XML Element. It has a <code>nodeName</code>,\nattributes, and a list of children. But it makes no effort to validate its\ncontent and be actually XML compliant.\n  </p>\n  <pre><code>const yxml = new Y.XmlElement()</code></pre>\n  <dl>\n    <b><code>parent:Y.AbstractType|null</code></b>\n    <dd></dd>\n    <b><code>firstChild:Y.XmlElement|Y.XmlText|null</code></b>\n    <dd></dd>\n    <b><code>nextSibling:Y.XmlElement|Y.XmlText|null</code></b>\n    <dd></dd>\n    <b><code>prevSibling:Y.XmlElement|Y.XmlText|null</code></b>\n    <dd></dd>\n    <b><code>insert(index:number, content:Array&lt;Y.XmlElement|Y.XmlText&gt;)</code></b>\n    <dd></dd>\n    <b><code>delete(index:number, length:number)</code></b>\n    <dd></dd>\n    <b><code>get(index:number)</code></b>\n    <dd></dd>\n    <b><code>length:number</code></b>\n    <dd></dd>\n    <b><code>setAttribute(attributeName:string, attributeValue:string)</code></b>\n    <dd></dd>\n    <b><code>removeAttribute(attributeName:string)</code></b>\n    <dd></dd>\n    <b><code>getAttribute(attributeName:string):string</code></b>\n    <dd></dd>\n    <b><code>getAttributes():Object&lt;string,string&gt;</code></b>\n    <dd></dd>\n    <b><code>get(i:number):Y.XmlElement|Y.XmlText</code></b>\n    <dd>Retrieve the i-th element.</dd>\n    <b><code>slice(start:number, end:number):Array&lt;Y.XmlElement|Y.XmlText&gt;</code></b>\n    <dd>Retrieve a range of content</dd>\n    <b><code>clone():Y.XmlElement</code></b>\n    <dd>Clone this type into a fresh Yjs type.</dd>\n    <b><code>toArray():Array&lt;Y.XmlElement|Y.XmlText&gt;</code></b>\n    <dd>Copies the children to a new Array.</dd>\n    <b><code>toDOM():Element</code></b>\n    <dd>Transforms this type and all children to a new DOM element.</dd>\n    <b><code>toString():string</code></b>\n    <dd>Get the XML serialization of all descendants.</dd>\n    <b><code>toJSON():string</code></b>\n    <dd>See <code>toString</code>.</dd>\n    <b><code>observe(function(YXmlEvent, Transaction):void)</code></b>\n    <dd>\nAdds an event listener to this type that will be called synchronously every\ntime this type is modified. In the case this type is modified in the event\nlistener, the event listener will be called again after the current event\nlistener returns.\n    </dd>\n    <b><code>unobserve(function(YXmlEvent, Transaction):void)</code></b>\n    <dd>\n      Removes an <code>observe</code> event listener from this type.\n    </dd>\n    <b><code>observeDeep(function(Array&lt;YEvent&gt;, Transaction):void)</code></b>\n    <dd>\nAdds an event listener to this type that will be called synchronously every time\nthis type or any of its children is modified. In the case this type is modified\nin the event listener, the event listener will be called again after the current\nevent listener returns. The event listener receives all Events created by itself\nor any of its children.\n    </dd>\n    <b><code>unobserveDeep(function(Array&lt;YEvent&gt;, Transaction):void)</code></b>\n    <dd>\n      Removes an <code>observeDeep</code> event listener from this type.\n    </dd>\n  </dl>\n</details>\n\n### Y.Doc\n\n```js\nconst doc = new Y.Doc()\n```\n\n<dl>\n  <b><code>clientID</code></b>\n  <dd>A unique id that identifies this client. (readonly)</dd>\n  <b><code>gc</code></b>\n  <dd>\nWhether garbage collection is enabled on this doc instance. Set `doc.gc = false`\nin order to disable gc and be able to restore old content. See https://github.com/yjs/yjs#yjs-crdt-algorithm\nfor more information about gc in Yjs.\n  </dd>\n  <b><code>transact(function(Transaction):void [, origin:any])</code></b>\n  <dd>\nEvery change on the shared document happens in a transaction. Observer calls and\nthe <code>update</code> event are called after each transaction. You should\n<i>bundle</i> changes into a single transaction to reduce the amount of event\ncalls. I.e. <code>doc.transact(() => { yarray.insert(..); ymap.set(..) })</code>\ntriggers a single change event. <br>You can specify an optional <code>origin</code>\nparameter that is stored on <code>transaction.origin</code> and\n<code>on('update', (update, origin) => ..)</code>.\n  </dd>\n  <b><code>toJSON():any</code></b>\n  <dd>\nDeprecated: It is recommended to call toJSON directly on the shared types.\nConverts the entire document into a js object, recursively traversing each yjs\ntype. Doesn't log types that have not been defined (using\n<code>ydoc.getType(..)</code>).\n  </dd>\n  <b><code>get(string, Y.[TypeClass]):[Type]</code></b>\n  <dd>Define a shared type.</dd>\n  <b><code>getArray(string):Y.Array</code></b>\n  <dd>Define a shared Y.Array type. Is equivalent to <code>y.get(string, Y.Array)</code>.</dd>\n  <b><code>getMap(string):Y.Map</code></b>\n  <dd>Define a shared Y.Map type. Is equivalent to <code>y.get(string, Y.Map)</code>.</dd>\n  <b><code>getXmlFragment(string):Y.XmlFragment</code></b>\n  <dd>Define a shared Y.XmlFragment type. Is equivalent to <code>y.get(string, Y.XmlFragment)</code>.</dd>\n  <b><code>on(string, function)</code></b>\n  <dd>Register an event listener on the shared type</dd>\n  <b><code>off(string, function)</code></b>\n  <dd>Unregister an event listener from the shared type</dd>\n</dl>\n\n#### Y.Doc Events\n\n<dl>\n  <b><code>on('update', function(updateMessage:Uint8Array, origin:any, Y.Doc):void)</code></b>\n  <dd>\nListen to document updates. Document updates must be transmitted to all other\npeers. You can apply document updates in any order and multiple times.\n  </dd>\n  <b><code>on('beforeTransaction', function(Y.Transaction, Y.Doc):void)</code></b>\n  <dd>Emitted before each transaction.</dd>\n  <b><code>on('afterTransaction', function(Y.Transaction, Y.Doc):void)</code></b>\n  <dd>Emitted after each transaction.</dd>\n  <b><code>on('beforeAllTransactions', function(Y.Doc):void)</code></b>\n  <dd>\nTransactions can be nested (e.g. when an event within a transaction calls another\ntransaction). Emitted before the first transaction.\n  </dd>\n  <b><code>on('afterAllTransactions', function(Y.Doc, Array&lt;Y.Transaction&gt;):void)</code></b>\n  <dd>Emitted after the last transaction is cleaned up.</dd>\n</dl>\n\n### Document Updates\n\nChanges on the shared document are encoded into *document updates*. Document\nupdates are *commutative* and *idempotent*. This means that they can be applied\nin any order and multiple times.\n\n#### Example: Listen to update events and apply them on remote client\n\n```js\nconst doc1 = new Y.Doc()\nconst doc2 = new Y.Doc()\n\ndoc1.on('update', update => {\n  Y.applyUpdate(doc2, update)\n})\n\ndoc2.on('update', update => {\n  Y.applyUpdate(doc1, update)\n})\n\n// All changes are also applied to the other document\ndoc1.getArray('myarray').insert(0, ['Hello doc2, you got this?'])\ndoc2.getArray('myarray').get(0) // => 'Hello doc2, you got this?'\n```\n\nYjs internally maintains a [state vector](#State-Vector) that denotes the next\nexpected clock from each client. In a different interpretation it holds the\nnumber of structs created by each client. When two clients sync, you can either\nexchange the complete document structure or only the differences by sending the\nstate vector to compute the differences.\n\n#### Example: Sync two clients by exchanging the complete document structure\n\n```js\nconst state1 = Y.encodeStateAsUpdate(ydoc1)\nconst state2 = Y.encodeStateAsUpdate(ydoc2)\nY.applyUpdate(ydoc1, state2)\nY.applyUpdate(ydoc2, state1)\n```\n\n#### Example: Sync two clients by computing the differences\n\nThis example shows how to sync two clients with the minimal amount of exchanged\ndata by computing only the differences using the state vector of the remote\nclient. Syncing clients using the state vector requires another roundtrip, but\ncan save a lot of bandwidth.\n\n```js\nconst stateVector1 = Y.encodeStateVector(ydoc1)\nconst stateVector2 = Y.encodeStateVector(ydoc2)\nconst diff1 = Y.encodeStateAsUpdate(ydoc1, stateVector2)\nconst diff2 = Y.encodeStateAsUpdate(ydoc2, stateVector1)\nY.applyUpdate(ydoc1, diff2)\nY.applyUpdate(ydoc2, diff1)\n```\n\n#### Example: Syncing clients without loading the Y.Doc\n\nIt is possible to sync clients and compute delta updates without loading the Yjs\ndocument to memory. Yjs exposes an API to compute the differences directly on the\nbinary document updates.\n\n```js\n// encode the current state as a binary buffer\nlet currentState1 = Y.encodeStateAsUpdate(ydoc1)\nlet currentState2 = Y.encodeStateAsUpdate(ydoc2)\n// now we can continue syncing clients using state vectors without using the Y.Doc\nydoc1.destroy()\nydoc2.destroy()\n\nconst stateVector1 = Y.encodeStateVectorFromUpdate(currentState1)\nconst stateVector2 = Y.encodeStateVectorFromUpdate(currentState2)\nconst diff1 = Y.diffUpdate(currentState1, stateVector2)\nconst diff2 = Y.diffUpdate(currentState2, stateVector1)\n\n// sync clients\ncurrentState1 = Y.mergeUpdates([currentState1, diff2])\ncurrentState1 = Y.mergeUpdates([currentState1, diff1])\n```\n\n#### Using V2 update format\n\nYjs implements two update formats. By default you are using the V1 update format.\nYou can opt-in into the V2 update format wich provides much better compression.\nIt is not yet used by all providers. However, you can already use it if\nyou are building your own provider. All below functions are available with the\nsuffix \"V2\". E.g. `Y.applyUpdate` ⇒ `Y.applyUpdateV2`. We also support conversion\nfunctions between both formats: `Y.convertUpdateFormatV1ToV2` & `Y.convertUpdateFormatV2ToV1`.\n\n#### Update API\n\n<dl>\n  <b><code>Y.applyUpdate(Y.Doc, update:Uint8Array, [transactionOrigin:any])</code></b>\n  <dd>\nApply a document update on the shared document. Optionally you can specify\n<code>transactionOrigin</code> that will be stored on\n<code>transaction.origin</code>\nand <code>ydoc.on('update', (update, origin) => ..)</code>.\n  </dd>\n  <b><code>Y.encodeStateAsUpdate(Y.Doc, [encodedTargetStateVector:Uint8Array]):Uint8Array</code></b>\n  <dd>\nEncode the document state as a single update message that can be applied on the\nremote document. Optionally specify the target state vector to only write the\ndifferences to the update message.\n  </dd>\n  <b><code>Y.encodeStateVector(Y.Doc):Uint8Array</code></b>\n  <dd>Computes the state vector and encodes it into an Uint8Array.</dd>\n  <b><code>Y.mergeUpdates(Array&lt;Uint8Array&gt;)</code></b>\n  <dd>\nMerge several document updates into a single document update while removing\nduplicate information. The merged document update is always smaller than\nthe separate updates because of the compressed encoding.\n  </dd>\n  <b><code>Y.encodeStateVectorFromUpdate(Uint8Array): Uint8Array</code></b>\n  <dd>\nComputes the state vector from a document update and encodes it into an Uint8Array.\n  </dd>\n  <b><code>Y.diffUpdate(update: Uint8Array, stateVector: Uint8Array): Uint8Array</code></b>\n  <dd>\nEncode the missing differences to another update message. This function works\nsimilarly to <code>Y.encodeStateAsUpdate(ydoc, stateVector)</code> but works\non updates instead.\n  </dd>\n  <b><code>convertUpdateFormatV1ToV2</code></b>\n  <dd>\nConvert V1 update format to the V2 update format.\n  </dd>\n  <b><code>convertUpdateFormatV2ToV1</code></b>\n  <dd>\nConvert V2 update format to the V1 update format.\n  </dd>\n</dl>\n\n### Relative Positions\n\nWhen working with collaborative documents, we often need to work with positions.\nPositions may represent cursor locations, selection ranges, or even assign a\ncomment to a range of text. Normal index-positions (expressed as integers) are\nnot convenient to use because the index-range is invalidated as soon as a remote\nchange manipulates the document. Relative positions give you a powerful API to\nexpress positions.\n\nA relative position is fixated to an element in the shared document and is not\naffected by remote changes. I.e. given the document `\"a|c\"`, the relative\nposition is attached to `c`. When a remote user modifies the document by\ninserting a character before the cursor, the cursor will stay attached to the\ncharacter `c`. `insert(1, 'x')(\"a|c\") = \"ax|c\"`. When the relative position is\nset to the end of the document, it will stay attached to the end of the\ndocument.\n\n#### Example: Transform to RelativePosition and back\n\n```js\nconst relPos = Y.createRelativePositionFromTypeIndex(ytext, 2)\nconst pos = Y.createAbsolutePositionFromRelativePosition(relPos, doc)\npos.type === ytext // => true\npos.index === 2 // => true\n```\n\n#### Example: Send relative position to remote client (json)\n\n```js\nconst relPos = Y.createRelativePositionFromTypeIndex(ytext, 2)\nconst encodedRelPos = JSON.stringify(relPos)\n// send encodedRelPos to remote client..\nconst parsedRelPos = JSON.parse(encodedRelPos)\nconst pos = Y.createAbsolutePositionFromRelativePosition(parsedRelPos, remoteDoc)\npos.type === remoteytext // => true\npos.index === 2 // => true\n```\n\n#### Example: Send relative position to remote client (Uint8Array)\n\n```js\nconst relPos = Y.createRelativePositionFromTypeIndex(ytext, 2)\nconst encodedRelPos = Y.encodeRelativePosition(relPos)\n// send encodedRelPos to remote client..\nconst parsedRelPos = Y.decodeRelativePosition(encodedRelPos)\nconst pos = Y.createAbsolutePositionFromRelativePosition(parsedRelPos, remoteDoc)\npos.type === remoteytext // => true\npos.index === 2 // => true\n```\n\n<dl>\n  <b><code>\nY.createRelativePositionFromTypeIndex(type:Uint8Array|Y.Type, index: number\n[, assoc=0])\n  </code></b>\n  <dd>\nCreate a relative position fixated to the i-th element in any sequence-like\nshared type (if <code>assoc >= 0</code>). By default, the position associates\nwith the character that comes after the specified index position. If\n<code>assoc < 0</code>, then the relative position associates with the character\nbefore the specified index position.\n  </dd>\n  <b><code>\nY.createAbsolutePositionFromRelativePosition(RelativePosition, Y.Doc):\n{ type: Y.AbstractType, index: number, assoc: number } | null\n  </code></b>\n  <dd>\nCreate an absolute position from a relative position. If the relative position\ncannot be referenced, or the type is deleted, then the result is null.\n  </dd>\n  <b><code>\nY.encodeRelativePosition(RelativePosition):Uint8Array\n  </code></b>\n  <dd>\nEncode a relative position to an Uint8Array. Binary data is the preferred\nencoding format for document updates. If you prefer JSON encoding, you can\nsimply JSON.stringify / JSON.parse the relative position instead.\n  </dd>\n  <b><code>Y.decodeRelativePosition(Uint8Array):RelativePosition</code></b>\n  <dd>Decode a binary-encoded relative position to a RelativePositon object.</dd>\n</dl>\n\n### Y.UndoManager\n\nYjs ships with an Undo/Redo manager for selective undo/redo of changes on a\nYjs type. The changes can be optionally scoped to transaction origins.\n\n```js\nconst ytext = doc.getText('text')\nconst undoManager = new Y.UndoManager(ytext)\n\nytext.insert(0, 'abc')\nundoManager.undo()\nytext.toString() // => ''\nundoManager.redo()\nytext.toString() // => 'abc'\n```\n\n<dl>\n  <b><code>constructor(scope:Y.AbstractType|Array&lt;Y.AbstractType&gt;\n  [, {captureTimeout:number,trackedOrigins:Set&lt;any&gt;,deleteFilter:function(item):boolean}])</code></b>\n  <dd>Accepts either single type as scope or an array of types.</dd>\n  <b><code>undo()</code></b>\n  <dd></dd>\n  <b><code>redo()</code></b>\n  <dd></dd>\n  <b><code>stopCapturing()</code></b>\n  <dd></dd>\n  <b>\n    <code>\non('stack-item-added', { stackItem: { meta: Map&lt;any,any&gt; }, type: 'undo'\n| 'redo' })\n    </code>\n  </b>\n  <dd>\nRegister an event that is called when a <code>StackItem</code> is added to the\nundo- or the redo-stack.\n  </dd>\n  <b>\n    <code>\non('stack-item-updated', { stackItem: { meta: Map&lt;any,any&gt; }, type: 'undo'\n| 'redo' })\n    </code>\n  </b>\n  <dd>\nRegister an event that is called when an existing <code>StackItem</code> is updated.\nThis happens when two changes happen within a \"captureInterval\".\n  </dd>\n  <b>\n    <code>\non('stack-item-popped', { stackItem: { meta: Map&lt;any,any&gt; }, type: 'undo'\n| 'redo' })\n    </code>\n  </b>\n  <dd>\nRegister an event that is called when a <code>StackItem</code> is popped from\nthe undo- or the redo-stack.\n  </dd>\n  <b>\n    <code>\non('stack-cleared', { undoStackCleared: boolean, redoStackCleared: boolean })\n    </code>\n  </b>\n  <dd>\nRegister an event that is called when the undo- and/or the redo-stack is cleared.\n  </dd>\n</dl>\n\n#### Example: Stop Capturing\n\nUndoManager merges Undo-StackItems if they are created within time-gap\nsmaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next\nStackItem won't be merged.\n\n```js\n// without stopCapturing\nytext.insert(0, 'a')\nytext.insert(1, 'b')\nundoManager.undo()\nytext.toString() // => '' (note that 'ab' was removed)\n// with stopCapturing\nytext.insert(0, 'a')\nundoManager.stopCapturing()\nytext.insert(0, 'b')\nundoManager.undo()\nytext.toString() // => 'a' (note that only 'b' was removed)\n```\n\n#### Example: Specify tracked origins\n\nEvery change on the shared document has an origin. If no origin was specified,\nit defaults to `null`. By specifying `trackedOrigins` you can\nselectively specify which changes should be tracked by `UndoManager`. The\nUndoManager instance is always added to `trackedOrigins`.\n\n```js\nclass CustomBinding {}\n\nconst ytext = doc.getText('text')\nconst undoManager = new Y.UndoManager(ytext, {\n  trackedOrigins: new Set([42, CustomBinding])\n})\n\nytext.insert(0, 'abc')\nundoManager.undo()\nytext.toString() // => 'abc' (does not track because origin `null` and not part\n                 //           of `trackedTransactionOrigins`)\nytext.delete(0, 3) // revert change\n\ndoc.transact(() => {\n  ytext.insert(0, 'abc')\n}, 42)\nundoManager.undo()\nytext.toString() // => '' (tracked because origin is an instance of `trackedTransactionorigins`)\n\ndoc.transact(() => {\n  ytext.insert(0, 'abc')\n}, 41)\nundoManager.undo()\nytext.toString() // => '' (not tracked because 41 is not an instance of\n                 //        `trackedTransactionorigins`)\nytext.delete(0, 3) // revert change\n\ndoc.transact(() => {\n  ytext.insert(0, 'abc')\n}, new CustomBinding())\nundoManager.undo()\nytext.toString() // => '' (tracked because origin is a `CustomBinding` and\n                 //        `CustomBinding` is in `trackedTransactionorigins`)\n```\n\n#### Example: Add additional information to the StackItems\n\nWhen undoing or redoing a previous action, it is often expected to restore\nadditional meta information like the cursor location or the view on the\ndocument. You can assign meta-information to Undo-/Redo-StackItems.\n\n```js\nconst ytext = doc.getText('text')\nconst undoManager = new Y.UndoManager(ytext, {\n  trackedOrigins: new Set([42, CustomBinding])\n})\n\nundoManager.on('stack-item-added', event => {\n  // save the current cursor location on the stack-item\n  event.stackItem.meta.set('cursor-location', getRelativeCursorLocation())\n})\n\nundoManager.on('stack-item-popped', event => {\n  // restore the current cursor location on the stack-item\n  restoreCursorLocation(event.stackItem.meta.get('cursor-location'))\n})\n```\n\n## Yjs CRDT Algorithm\n\n*Conflict-free replicated data types* (CRDT) for collaborative editing are an\nalternative approach to *operational transformation* (OT). A very simple\ndifferentiation between the two approaches is that OT attempts to transform\nindex positions to ensure convergence (all clients end up with the same\ncontent), while CRDTs use mathematical models that usually do not involve index\ntransformations, like linked lists. OT is currently the de-facto standard for\nshared editing on text. OT approaches that support shared editing without a\ncentral source of truth (a central server) require too much bookkeeping to be\nviable in practice. CRDTs are better suited for distributed systems, provide\nadditional guarantees that the document can be synced with remote clients, and\ndo not require a central source of truth.\n\nYjs implements a modified version of the algorithm described in [this\npaper](https://www.researchgate.net/publication/310212186_Near_Real-Time_Peer-to-Peer_Shared_Editing_on_Extensible_Data_Types).\nThis [article](https://blog.kevinjahns.de/are-crdts-suitable-for-shared-editing/)\nexplains a simple optimization on the CRDT model and\ngives more insight about the performance characteristics in Yjs.\nMore information about the specific implementation is available in\n[INTERNALS.md](./INTERNALS.md) and in\n[this walkthrough of the Yjs codebase](https://youtu.be/0l5XgnQ6rB4).\n\nCRDTs that suitable for shared text editing suffer from the fact that they only grow\nin size. There are CRDTs that do not grow in size, but they do not have the\ncharacteristics that are benificial for shared text editing (like intention\npreservation). Yjs implements many improvements to the original algorithm that\ndiminish the trade-off that the document only grows in size. We can't garbage\ncollect deleted structs (tombstones) while ensuring a unique order of the\nstructs. But we can 1. merge preceeding structs into a single struct to reduce\nthe amount of meta information, 2. we can delete content from the struct if it\nis deleted, and 3. we can garbage collect tombstones if we don't care about the\norder of the structs anymore (e.g. if the parent was deleted).\n\n**Examples:**\n\n1. If a user inserts elements in sequence, the struct will be merged into a\n   single struct. E.g. `text.insert(0, 'a'), text.insert(1, 'b');` is\n   first represented as two structs (`[{id: {client, clock: 0}, content: 'a'},\n   {id: {client, clock: 1}, content: 'b'}`) and then merged into a single\n   struct: `[{id: {client, clock: 0}, content: 'ab'}]`.\n2. When a struct that contains content (e.g. `ItemString`) is deleted, the\n   struct will be replaced with an `ItemDeleted` that does not contain content\n   anymore.\n3. When a type is deleted, all child elements are transformed to `GC` structs. A\n   `GC` struct only denotes the existence of a struct and that it is deleted.\n   `GC` structs can always be merged with other `GC` structs if the id's are\n   adjacent.\n\nEspecially when working on structured content (e.g. shared editing on\nProseMirror), these improvements yield very good results when\n[benchmarking](https://github.com/dmonad/crdt-benchmarks) random document edits.\nIn practice they show even better results, because users usually edit text in\nsequence, resulting in structs that can easily be merged. The benchmarks show\nthat even in the worst case scenario that a user edits text from right to left,\nYjs achieves good performance even for huge documents.\n\n### State Vector\n\nYjs has the ability to exchange only the differences when syncing two clients.\nWe use lamport timestamps to identify structs and to track in which order a\nclient created them. Each struct has an `struct.id = { client: number, clock:\nnumber}` that uniquely identifies a struct. We define the next expected `clock`\nby each client as the *state vector*. This data structure is similar to the\n[version vectors](https://en.wikipedia.org/wiki/Version_vector) data structure.\nBut we use state vectors only to describe the state of the local document, so we\ncan compute the missing struct of the remote client. We do not use it to track\ncausality.\n\n## License and Author\n\nYjs and all related projects are [**MIT licensed**](./LICENSE).\n\nYjs is based on my research as a student at the [RWTH\ni5](http://dbis.rwth-aachen.de/). Now I am working on Yjs in my spare time.\n\nFund this project by donating on [GitHub Sponsors](https://github.com/sponsors/dmonad)\nor hiring [me](https://github.com/dmonad) as a contractor for your collaborative\napp.\n","readmeFilename":"README.md"}