From e100df49041a27746f177ea532d738199ff124ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 07:17:48 +0300 Subject: [PATCH] Baseline: server-rendered app with TypeScript ProseMirror editor Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 + Cargo.lock | 5199 +++++++++++++++++ Cargo.toml | 21 + assets/editor.css | 1 + assets/editor.js | 16 + assets/editor.js.map | 37 + assets/loro-856987111b05.wasm | Bin 0 -> 3595346 bytes build.rs | 6 + components.toml | 45 + fonts/OFL.txt | 93 + ...son-hyperlegible-mono-latin-ext-wght.woff2 | Bin 0 -> 10740 bytes ...tkinson-hyperlegible-mono-latin-wght.woff2 | Bin 0 -> 17752 bytes ...son-hyperlegible-next-latin-ext-wght.woff2 | Bin 0 -> 19092 bytes ...tkinson-hyperlegible-next-latin-wght.woff2 | Bin 0 -> 33996 bytes src/app.rs | 310 + src/app/export_all.rs | 156 + src/app/import.rs | 270 + src/app/lang.rs | 41 + src/app/notebooks.rs | 42 + src/app/notebooks/notebook_id.rs | 201 + src/app/notes.rs | 212 + src/app/notes/note_id.rs | 479 ++ src/app/notes/note_id/history.rs | 222 + src/app/notes/note_id/ws.rs | 30 + src/app/palette.rs | 527 ++ src/app/pane.rs | 268 + src/app/scheme.rs | 31 + src/app/search.rs | 162 + src/app/shell.rs | 930 +++ src/app/trash.rs | 171 + src/app/trash/note_id.rs | 35 + src/app/unfiled.rs | 38 + src/components.rs | 10 + src/components/badge.rs | 78 + src/components/button.rs | 154 + src/components/dialog.rs | 177 + src/components/dropdown_menu.rs | 327 ++ src/components/floating.rs | 167 + src/components/input.rs | 31 + src/components/kbd.rs | 44 + src/components/segmented.rs | 15 + src/components/separator.rs | 77 + src/components/tooltip.rs | 92 + src/export.rs | 669 +++ src/export/html.rs | 324 + src/hub.rs | 441 ++ src/i18n.rs | 414 ++ src/import.rs | 743 +++ src/main.rs | 46 + src/matcher.rs | 320 + src/scheme.rs | 117 + src/store.rs | 976 ++++ styles.css | 1006 ++++ web/build.ts | 48 + web/bun.lock | 58 + web/package.json | 23 + web/src/dom.ts | 76 + web/src/editing.ts | 294 + web/src/editor.css | 800 +++ web/src/editor.ts | 394 ++ web/src/floating.ts | 453 ++ web/src/i18n.ts | 109 + web/src/noteLinks.ts | 334 ++ web/src/toolbar.ts | 279 + 64 files changed, 18642 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 assets/editor.css create mode 100644 assets/editor.js create mode 100644 assets/editor.js.map create mode 100644 assets/loro-856987111b05.wasm create mode 100644 build.rs create mode 100644 components.toml create mode 100644 fonts/OFL.txt create mode 100644 fonts/atkinson-hyperlegible-mono-latin-ext-wght.woff2 create mode 100644 fonts/atkinson-hyperlegible-mono-latin-wght.woff2 create mode 100644 fonts/atkinson-hyperlegible-next-latin-ext-wght.woff2 create mode 100644 fonts/atkinson-hyperlegible-next-latin-wght.woff2 create mode 100644 src/app.rs create mode 100644 src/app/export_all.rs create mode 100644 src/app/import.rs create mode 100644 src/app/lang.rs create mode 100644 src/app/notebooks.rs create mode 100644 src/app/notebooks/notebook_id.rs create mode 100644 src/app/notes.rs create mode 100644 src/app/notes/note_id.rs create mode 100644 src/app/notes/note_id/history.rs create mode 100644 src/app/notes/note_id/ws.rs create mode 100644 src/app/palette.rs create mode 100644 src/app/pane.rs create mode 100644 src/app/scheme.rs create mode 100644 src/app/search.rs create mode 100644 src/app/shell.rs create mode 100644 src/app/trash.rs create mode 100644 src/app/trash/note_id.rs create mode 100644 src/app/unfiled.rs create mode 100644 src/components.rs create mode 100644 src/components/badge.rs create mode 100644 src/components/button.rs create mode 100644 src/components/dialog.rs create mode 100644 src/components/dropdown_menu.rs create mode 100644 src/components/floating.rs create mode 100644 src/components/input.rs create mode 100644 src/components/kbd.rs create mode 100644 src/components/segmented.rs create mode 100644 src/components/separator.rs create mode 100644 src/components/tooltip.rs create mode 100644 src/export.rs create mode 100644 src/export/html.rs create mode 100644 src/hub.rs create mode 100644 src/i18n.rs create mode 100644 src/import.rs create mode 100644 src/main.rs create mode 100644 src/matcher.rs create mode 100644 src/scheme.rs create mode 100644 src/store.rs create mode 100644 styles.css create mode 100644 web/build.ts create mode 100644 web/bun.lock create mode 100644 web/package.json create mode 100644 web/src/dom.ts create mode 100644 web/src/editing.ts create mode 100644 web/src/editor.css create mode 100644 web/src/editor.ts create mode 100644 web/src/floating.ts create mode 100644 web/src/i18n.ts create mode 100644 web/src/noteLinks.ts create mode 100644 web/src/toolbar.ts diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..51fe5fb --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/target +web/node_modules +*.db* diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..48d1d21 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,5199 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array", +] + +[[package]] +name = "aegis" +version = "0.9.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41585f248ed9406567ae6d61ca2a55ed3dc7348e65203a01229881253acb95e3" +dependencies = [ + "cc", + "softaes", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + +[[package]] +name = "alloc-stdlib" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "allocator-api2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c880a97d28a3681c0267bd29cff89621202715b065127cd445fa0f0fe0aa2880" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "antithesis_sdk" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8ed6751597568a284314fd9e2db420665898600109dedc7d8d9b588f00ae9c4" +dependencies = [ + "libc", + "libloading", + "linkme", + "once_cell", + "rand 0.8.8", + "rustc_version_runtime", + "serde", + "serde_json", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "anymap3" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9" + +[[package]] +name = "append-only-bytes" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac436601d6bdde674a0d7fb593e829ffe7b3387c351b356dd20e2d40f5bf3ee5" + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +dependencies = [ + "derive_arbitrary", +] + +[[package]] +name = "arc-swap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e" +dependencies = [ + "rustversion", +] + +[[package]] +name = "aristo" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcdeefa800110050103e2459a2f8dbdbd560ad046e30f1f87e24ce19c2cb8bde" +dependencies = [ + "aristo-macros", +] + +[[package]] +name = "aristo-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d64a66d21a80182b35b1741997a6d2456911f54b7eb1918aa4e2382fc205268d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "arref" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ccd462b64c3c72f1be8305905a85d85403d768e8690c9b8bd3b9009a5761679" + +[[package]] +name = "assoc" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfdc70193dadb9d7287fa4b633f15f90c876915b31f6af17da307fc59c9859a8" + +[[package]] +name = "async-compression" +version = "0.4.51" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d5755640120b24961f8231e05892e4a4f7e0d04e8aeca161508c9c397946970" +dependencies = [ + "compression-codecs", + "compression-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-polyfill" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cf2bce30dfe09ef0bfaef228b9d414faaf7e563035494d7fe092dba54b300f4" +dependencies = [ + "critical-section", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bigdecimal" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fa3f3d8cbf4dffcfe4991de61d012bef509a409ecbe9dd41049bfe32b4d4653" +dependencies = [ + "autocfg", + "libm", + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "bindgen" +version = "0.69.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools 0.12.1", + "lazy_static", + "lazycell", + "log", + "prettyplease 0.2.37", + "proc-macro2", + "quote", + "regex", + "rustc-hash 1.1.0", + "shlex 1.3.0", + "syn 2.0.119", + "which", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bitmaps" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031043d04099746d8db04daf1fa424b2bc8bd69d92b25962dcde24da39ab64a2" +dependencies = [ + "typenum", +] + +[[package]] +name = "bitpacking" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96a7139abd3d9cebf8cd6f920a389cf3dc9576172e32f4563f188cae3c3eb019" +dependencies = [ + "crunchy", +] + +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures 0.3.1", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bon" +version = "3.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05442cd7005532d0cfedec676b5b9333d2b4c7c3afabe2b1a9ce2742fbe2ee6" +dependencies = [ + "bon-macros", +] + +[[package]] +name = "bon-macros" +version = "3.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93833e97ac7c46ba97045afcf247238c27057538fcf2f06344662ddd5f567be6" +dependencies = [ + "darling 0.24.1", + "ident_case", + "prettyplease 0.3.0", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "branches" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7436b21fd6195415058eb41c9090e156b556bc7e0377bb57c5c026a421521525" +dependencies = [ + "rustc_version", +] + +[[package]] +name = "brotli" +version = "9.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "6.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34c6783f42c21c952ad7112b354f0ba2f10760e9decea5b1b60523d6e270faaf" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex 2.0.1", +] + +[[package]] +name = "census" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f4c707c6a209cbe82d10abd08e1ea8995e9ea937d2550646e02798948992be0" + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom 7.1.3", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cfg_block" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18758054972164c3264f7c8386f5fc6da6114cb46b619fd365d4e3b2dc3ae487" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout", +] + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "compression-codecs" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cae36683101b2899f48bd31f8db9839437356188e3b1ff23096e73dab09ba8fe" +dependencies = [ + "brotli", + "compression-core", + "flate2", + "memchr", +] + +[[package]] +name = "compression-core" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a" + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + +[[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "aes-gcm", + "base64 0.22.1", + "hkdf", + "hmac", + "percent-encoding", + "rand 0.8.8", + "sha2 0.10.9", + "subtle", + "time", + "version_check", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32c" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47" +dependencies = [ + "rustc_version", +] + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core 0.20.11", + "darling_macro 0.20.11", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core 0.24.1", + "darling_macro 0.24.1", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.9", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core 0.20.11", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core 0.24.1", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "datasketches" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745" + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] + +[[package]] +name = "derive_arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "diff" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "downcast-rs" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "elsa" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9abf33c656a7256451ebb7d0082c5a471820c31269e49d807c538c252352186e" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "email-encoding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "420b9da095f052ea597503e39073b5b3c522f7db933fbac202d91d24492693fd" +dependencies = [ + "base64 0.23.1", + "memchr", +] + +[[package]] +name = "email_address" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" + +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + +[[package]] +name = "ensure-cov" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33753185802e107b8fa907192af1f0eca13b1fb33327a59266d650fef29b2b4e" + +[[package]] +name = "enum-as-inner" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9720bba047d567ffc8a3cba48bf19126600e249ab7f128e9233e6376976a116" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "enum-as-inner" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "enum_dispatch" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd" +dependencies = [ + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "env_filter" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6" +dependencies = [ + "env_filter", + "log", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "erased-serde" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fastbloom" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7f34442dbe69c60fe8eaf58a8cafff81a1f278816d8ab4db255b3bef4ac3c4" +dependencies = [ + "getrandom 0.3.4", + "libm", + "siphasher", +] + +[[package]] +name = "fastdivide" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afc2bd4d5a73106dd53d10d73d3401c2f32730ba2c0b93ddb888a8983680471" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs4" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4" +dependencies = [ + "rustix 1.1.6", + "windows-sys 0.59.0", +] + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-sink", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "genawaiter" +version = "0.99.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86bd0361bcbde39b13475e6e36cb24c329964aa2611be285289d1e4b751c1a0" +dependencies = [ + "genawaiter-macro", +] + +[[package]] +name = "genawaiter-macro" +version = "0.99.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b32dfe1fdfc0bbde1f22a5da25355514b5e450c33a6af6770884c8750aedfbc" + +[[package]] +name = "generator" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1be81b31c9ce4caf7f3178eeb90662bb1864d3ad363ec6bdada3201adff19c37" +dependencies = [ + "cc", + "cfg-if", + "libc", + "log", + "rustversion", + "windows-link", + "windows-result", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "generic-btree" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0c1bce85c110ab718fd139e0cc89c51b63bd647b14a767e24bdfc77c83df79b" +dependencies = [ + "arref", + "heapless 0.9.3", + "itertools 0.11.0", + "loro-thunderdome", + "proc-macro2", + "rustc-hash 2.1.3", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "wasm-bindgen", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hash32" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67" +dependencies = [ + "byteorder", +] + +[[package]] +name = "hash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" +dependencies = [ + "byteorder", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2 0.2.21", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heapless" +version = "0.7.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f" +dependencies = [ + "atomic-polyfill", + "hash32 0.2.1", + "rustc_version", + "serde", + "spin", + "stable_deref_trait", +] + +[[package]] +name = "heapless" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" +dependencies = [ + "hash32 0.3.1", + "stable_deref_trait", +] + +[[package]] +name = "heapless" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ba4bd83f9415b58b4ed8dc5714c76e626a105be4646c02630ad730ad3b5aa4" +dependencies = [ + "hash32 0.3.1", + "stable_deref_trait", +] + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "hostname" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd" +dependencies = [ + "cfg-if", + "libc", + "windows-link", +] + +[[package]] +name = "htmlescape" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9025058dae765dee5070ec375f591e2ba14638c63feff74f13805a72e523163" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collator" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24cb0205c419b2036da3f9082964905d6849b3f2130dd4a517940c45899a544b" +dependencies = [ + "icu_collator_data", + "icu_collections", + "icu_locale_core", + "icu_locale_fallback", + "icu_normalizer", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "zerovec", +] + +[[package]] +name = "icu_collator_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "183f47e821a327661c1ebe152f61d5b6c2000010d228cadbbf226e0e2b8c2634" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe8fa57bcddc15cb921582ee5259c5b77da39f946f188ca5213fad24d9241236" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_locale_data", + "icu_locale_fallback", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locale_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a64014dac577a11d8d2cee48517c73c1984bd72ab11031e934269bd3cefb2ad9" + +[[package]] +name = "icu_locale_fallback" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "write16", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "im" +version = "15.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0acd33ff0285af998aaf9b57342af478078f53492322fafc47450e09397e0e9" +dependencies = [ + "bitmaps", + "rand_core 0.6.4", + "rand_xoshiro", + "serde", + "sized-chunks", + "typenum", + "version_check", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "intrusive-collections" +version = "0.9.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86" +dependencies = [ + "memoffset", +] + +[[package]] +name = "inventory" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c" +dependencies = [ + "rustversion", +] + +[[package]] +name = "io-uring" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb" +dependencies = [ + "bitflags", + "cfg-if", + "libc", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itertools" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "lazycell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "lettre" +version = "0.11.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2c646bd5cc763b1087b15493e29a64be6147ba8f19342004fa52048ee596eae" +dependencies = [ + "email-encoding", + "email_address", + "fastrand", + "hostname", + "httpdate", + "idna", + "mime", + "nom 8.0.0", + "quoted_printable", +] + +[[package]] +name = "levenshtein_automata" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c2cdeb66e45e9f36bfad5bbdb4d2384e70936afbee843c6f6543f0c551ebb25" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libmimalloc-sys" +version = "0.1.49" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9" +dependencies = [ + "cc", +] + +[[package]] +name = "linkme" +version = "0.3.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3045e122bd98aef8ec3ad58ce84f0791f64e70163d1a02710af4aa11a4d54cc5" +dependencies = [ + "linkme-impl", +] + +[[package]] +name = "linkme-impl" +version = "0.3.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77060ebe535362c3da75682cd17b0431017b6e7c5661e714fc69a7ad017d1301" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "loom" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "419e0dc8046cb947daa77eb95ae174acfbddb7673b4151f56d1eed8e93fbfaca" +dependencies = [ + "cfg-if", + "generator", + "scoped-tls", + "serde", + "serde_json", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "loro" +version = "1.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "410c939fe3bee34b8ed61f7aea93201fb136629f685ffa557039c4d9952f9988" +dependencies = [ + "enum-as-inner 0.6.1", + "generic-btree", + "loro-common", + "loro-delta", + "loro-internal", + "loro-kv-store", + "rustc-hash 2.1.3", + "tracing", +] + +[[package]] +name = "loro-common" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd3f7afbafc4db85aefe9620e7e99fa49c974477563904f226ae96fc9674eade" +dependencies = [ + "arbitrary", + "enum-as-inner 0.6.1", + "leb128", + "loro-rle", + "nonmax", + "rustc-hash 2.1.3", + "serde", + "serde_columnar", + "serde_json", + "thiserror 1.0.69", +] + +[[package]] +name = "loro-delta" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96f381e7fb5d4bf5605b4f4a9241f3adf61403ded978d757552004c8302cccbb" +dependencies = [ + "arrayvec", + "enum-as-inner 0.5.1", + "generic-btree", + "heapless 0.8.0", +] + +[[package]] +name = "loro-internal" +version = "1.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e533c1688430aa4fcdd933f00861e331c169a4158ee6d27d054e0558892d447" +dependencies = [ + "append-only-bytes", + "arref", + "bytes", + "either", + "ensure-cov", + "enum-as-inner 0.6.1", + "enum_dispatch", + "generic-btree", + "getrandom 0.2.17", + "im", + "itertools 0.12.1", + "leb128", + "loom", + "loro-common", + "loro-delta", + "loro-kv-store", + "loro-rle", + "loro_fractional_index", + "md5", + "nonmax", + "num", + "num-traits", + "once_cell", + "parking_lot", + "pest", + "pest_derive", + "postcard", + "pretty_assertions", + "rand 0.8.8", + "rustc-hash 2.1.3", + "serde", + "serde_columnar", + "serde_json", + "smallvec", + "thiserror 1.0.69", + "thread_local", + "tracing", + "wasm-bindgen", + "xxhash-rust", +] + +[[package]] +name = "loro-kv-store" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7331ebe6902effeb0c3d52aba9e30fb0118bc926faed6f3848487aab40c1a4e" +dependencies = [ + "bytes", + "ensure-cov", + "loro-common", + "lz4_flex 0.11.6", + "once_cell", + "quick_cache", + "rustc-hash 2.1.3", + "tracing", + "xxhash-rust", +] + +[[package]] +name = "loro-rle" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76400c3eea6bb39b013406acce964a8db39311534e308286c8d8721baba8ee20" +dependencies = [ + "append-only-bytes", + "num", + "smallvec", +] + +[[package]] +name = "loro-thunderdome" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3d053a135388e6b1df14e8af1212af5064746e9b87a06a345a7a779ee9695a" + +[[package]] +name = "loro_fractional_index" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aca7180674d0273ddf37049a5efcde4547fd5330d24abb7519bb9d9eb6780d5b" +dependencies = [ + "once_cell", + "rand 0.8.8", + "serde", +] + +[[package]] +name = "lru" +version = "0.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39" +dependencies = [ + "hashbrown 0.16.1", +] + +[[package]] +name = "lz4_flex" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a" +dependencies = [ + "twox-hash", +] + +[[package]] +name = "lz4_flex" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef0d4ed8669f8f8826eb00dc878084aa8f253506c4fd5e8f58f5bce72ddb97e" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8863b587001c1b9a8a4e36008cebc6b3612cb1226fe2de94858e06092687b608" + +[[package]] +name = "md5" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" + +[[package]] +name = "measure_time" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51c55d61e72fc3ab704396c5fa16f4c184db37978ae4e94ca8959693a235fc0e" +dependencies = [ + "log", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "miette" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" +dependencies = [ + "cfg-if", + "miette-derive", + "unicode-width", +] + +[[package]] +name = "miette-derive" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "mimalloc" +version = "0.1.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862" +dependencies = [ + "libmimalloc-sys", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "murmurhash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2195bf6aa996a481483b29d62a7663eed3fe39600c460e323f8ff41e90bdd89b" + +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "nonmax" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "610a5acd306ec67f907abe5567859a3c693fb9886eb1f012ab8f2a47bef3db51" + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "oneshot" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "269bca4c2591a28585d6bf10d9ed0332b7d76900a1b02bec41bdc3a2cdcda107" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "ordered-float" +version = "5.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ownedbytes" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fbd56f7631767e61784dc43f8580f403f4475bd4aaa4da003e6295e1bab4a7e" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "owo-colors" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f" + +[[package]] +name = "pack1" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3b7bb0ecf2e447b1f20ee94ee79ef6eed1e9d4b3c36ce1903b9dea3bf205523" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pest" +version = "2.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8db75153506001cb36ed924f08cadc862eb3f8c4d0d534139f29074769d7660" +dependencies = [ + "memchr", + "pest_stack_guard", + "ucd-trie", +] + +[[package]] +name = "pest_derive" +version = "2.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20aa17e11fb35664b67d5214a0afac57a360d231b6ec53d6eba0700b27d933b4" +dependencies = [ + "pest", + "pest_generator", +] + +[[package]] +name = "pest_generator" +version = "2.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626ec5afccf44ccbfeb2b232316510bb55b4bf34d891afcb0fb07d2b17d7fe9d" +dependencies = [ + "pest", + "pest_meta", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "pest_meta" +version = "2.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3f45b6caa65c1b08186832745159c2529994146340a7bf44168095469720f5d" +dependencies = [ + "pest", +] + +[[package]] +name = "pest_stack_guard" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97e6cd2217057fa86b6eaa512917e58089d875b957a31e35e7ab729977e0a5f2" +dependencies = [ + "psm", + "stacker", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", + "heapless 0.7.17", + "serde", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "serde_core", + "writeable", + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "pretty_assertions" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d" +dependencies = [ + "diff", + "yansi", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn 3.0.9", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "project_note" +version = "0.1.0" +dependencies = [ + "anyhow", + "blake3", + "loro", + "pulldown-cmark", + "regex", + "serde", + "serde_json", + "tokio", + "topcoat", + "turso", + "uuid", + "zip", +] + +[[package]] +name = "prost" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" +dependencies = [ + "anyhow", + "itertools 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "psm" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "200b9ff220857e53e184257720a14553b2f4aa02577d2ed9842d45d4b9654810" +dependencies = [ + "cc", +] + +[[package]] +name = "pulldown-cmark" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "278e9268c93b9e498a2da46c34d90ba93a3255eb99009646398f34bc73ab36eb" +dependencies = [ + "bitflags", + "memchr", + "unicase", +] + +[[package]] +name = "quick_cache" +version = "0.6.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9c6658afe513a3b484e3abfdaa0d03ef3c0bbf017542c178dd55f94eb3051f9" +dependencies = [ + "ahash", + "equivalent", + "hashbrown 0.16.1", + "parking_lot", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "quoted_printable" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478e0585659a122aa407eb7e3c0e1fa51b1d8a870038bd29f0cf4a8551eea972" + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_pcg" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59cad018caf63deb318e5a4586d99a24424a364f40f1e5778c29aca23f4fc73e" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "rand_xoshiro" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f97cdb2a36ed4183de61b2f824cc45c9f1037f28afe0a322e9fff4c108b5aaa" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "rapidhash" +version = "4.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5da7e78a036ce858e8d55b7e7dc8ba3a88b78350fd2155d3591bbd966b58589e" +dependencies = [ + "rustversion", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "roaring" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18bd8a37d17a58532776dcdf6041ce64929adca78e8489d5cacbafe99229d3e1" +dependencies = [ + "bytemuck", + "byteorder", +] + +[[package]] +name = "rust-stemmers" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e46a2036019fdb888131db7a4c847a1063a7493f971ed94ea82c67eada63ca54" +dependencies = [ + "serde", + "serde_derive", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustc_version_runtime" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dd18cd2bae1820af0b6ad5e54f4a51d0f3fcc53b05f845675074efcc7af071d" +dependencies = [ + "rustc_version", + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_columnar" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a16e404f17b16d0273460350e29b02d76ba0d70f34afdc9a4fa034c97d6c6eb" +dependencies = [ + "itertools 0.11.0", + "postcard", + "serde", + "serde_columnar_derive", + "thiserror 1.0.69", +] + +[[package]] +name = "serde_columnar_derive" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45958fce4903f67e871fbf15ac78e289269b21ebd357d6fecacdba233629112e" +dependencies = [ + "darling 0.20.11", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "shuttle" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab17edba38d63047f46780cf7360acf7467fec2c048928689a5c1dd1c2b4e31" +dependencies = [ + "assoc", + "bitvec", + "cfg-if", + "generator", + "hex", + "owo-colors", + "rand 0.8.8", + "rand_core 0.6.4", + "rand_pcg", + "scoped-tls", + "smallvec", + "tracing", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "simsimd" +version = "6.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4fb3bc3cdce07a7d7d4caa4c54f8aa967f6be41690482b54b24100a2253fa70" +dependencies = [ + "cc", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "sized-chunks" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16d69225bde7a69b235da73377861095455d298f2b970996eec25ddbb42b3d1e" +dependencies = [ + "bitmaps", + "typenum", +] + +[[package]] +name = "sketches-ddsketch" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e53e2f8d4e9c692f23a90208fad6a64862f413e286d533f1f649f160e2d5caee" +dependencies = [ + "serde", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "softaes" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4fdfe13e1c42e45f497416afb8dc4e783bf0e25b7be9077c1c77c5fb14cb998" + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tantivy" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "861facfabd71044968f364837f9a083b56464ba5a59079f88706ee5c451ca069" +dependencies = [ + "aho-corasick", + "arc-swap", + "base64 0.22.1", + "bitpacking", + "bon", + "byteorder", + "census", + "crc32fast", + "crossbeam-channel", + "datasketches", + "downcast-rs", + "fastdivide", + "fnv", + "fs4", + "htmlescape", + "itertools 0.14.0", + "levenshtein_automata", + "log", + "lru", + "lz4_flex 0.13.1", + "measure_time", + "memmap2", + "once_cell", + "oneshot", + "rayon", + "regex", + "rust-stemmers", + "rustc-hash 2.1.3", + "serde", + "serde_json", + "sketches-ddsketch", + "smallvec", + "tantivy-bitpacker", + "tantivy-columnar", + "tantivy-common", + "tantivy-fst", + "tantivy-query-grammar", + "tantivy-stacker", + "tantivy-tokenizer-api", + "tempfile", + "thiserror 2.0.21", + "time", + "typetag", + "uuid", + "winapi", +] + +[[package]] +name = "tantivy-bitpacker" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fed3d674429bcd2de5d0a6d1aa5495fed8afd9c5ecce993019caf7615f53fa4" +dependencies = [ + "bitpacking", +] + +[[package]] +name = "tantivy-columnar" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c57166f5bcfd478f370ab8445afb4678dce44801fa5ce5c451aaf8595583c5dc" +dependencies = [ + "downcast-rs", + "fastdivide", + "itertools 0.14.0", + "serde", + "tantivy-bitpacker", + "tantivy-common", + "tantivy-sstable", + "tantivy-stacker", +] + +[[package]] +name = "tantivy-common" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbf10915aa75da3c3b0d58b58853d2e889efbaf32d4982a4c3715dde6bba23e5" +dependencies = [ + "async-trait", + "byteorder", + "ownedbytes", + "serde", + "time", +] + +[[package]] +name = "tantivy-fst" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d60769b80ad7953d8a7b2c70cdfe722bbcdcac6bccc8ac934c40c034d866fc18" +dependencies = [ + "byteorder", + "regex-syntax", + "utf8-ranges", +] + +[[package]] +name = "tantivy-query-grammar" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfadb8526b6da90704feb293b0701a6aae62ea14983143344be2dc5ce30f1d82" +dependencies = [ + "fnv", + "nom 7.1.3", + "ordered-float", + "serde", + "serde_json", +] + +[[package]] +name = "tantivy-sstable" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a2cfc3ac5164cbadc28965ffb145a8f47582a60ae5897859ad8d4316596c606" +dependencies = [ + "futures-util", + "itertools 0.14.0", + "tantivy-bitpacker", + "tantivy-common", + "tantivy-fst", + "zstd", +] + +[[package]] +name = "tantivy-stacker" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cbb051742da9d53ca9e8fff43a9b10e319338b24e2c0e15d0372df19ffeb951" +dependencies = [ + "murmurhash32", + "tantivy-common", +] + +[[package]] +name = "tantivy-tokenizer-api" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eac258c2c6390673f2685813afeeafcb8c4e0ee7de8dd3fc46838dcc37263f98" +dependencies = [ + "serde", +] + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "topcoat" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70b5093d8133b513742b7461a28d374107b8bf9168aa60f4f567ad89acd2ed9e" +dependencies = [ + "futures-util", + "inventory", + "serde", + "tokio", + "tokio-tungstenite", + "topcoat-asset", + "topcoat-cookie", + "topcoat-core", + "topcoat-core-macro", + "topcoat-font", + "topcoat-font-macro", + "topcoat-icon", + "topcoat-icon-macro", + "topcoat-l10n", + "topcoat-mail", + "topcoat-router", + "topcoat-router-macro", + "topcoat-runtime", + "topcoat-runtime-macro", + "topcoat-session", + "topcoat-tailwind", + "topcoat-ui-registry", + "topcoat-view", + "topcoat-view-macro", +] + +[[package]] +name = "topcoat-asset" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac70debf9eee62714ce45416eae27b283c3a44a0f9ebcb2ac088fda48b533f3e" +dependencies = [ + "http", + "memchr", + "percent-encoding", + "serde", + "sha2 0.11.1", + "thiserror 2.0.21", + "tokio", + "toml", + "topcoat-core", + "topcoat-router", + "topcoat-view", +] + +[[package]] +name = "topcoat-cookie" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79aba10192abe21fbd01dfcb46bb04dab5ae64adb4432d9f078eb05f94e6a5" +dependencies = [ + "cookie", + "getrandom 0.2.17", + "http", + "serde", + "serde_json", + "topcoat-core", + "topcoat-router", +] + +[[package]] +name = "topcoat-core" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffff49b885744cdb89ee158c5d81cc8c619692bd9f4ab3cae92ad1adc0ce612e" +dependencies = [ + "anyhow", + "anymap3", + "base64 0.22.1", + "elsa", + "http", + "pin-project-lite", + "siphasher", + "thiserror 2.0.21", + "tokio", +] + +[[package]] +name = "topcoat-core-grammar" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b788a2010234cd29fc050268e52ceb393d2124b20f669a83d8f61a9dbf895bb6" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "topcoat-core-macro" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e3786bf2ee2c8b4f728d3fb53c41f639aa66583788b3135acbd63c11458b25b" +dependencies = [ + "quote", + "syn 3.0.9", + "topcoat-core-grammar", +] + +[[package]] +name = "topcoat-font" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa4656294aac116def1e7633f03117a84b65126c503242793ff4adc78577fb8" +dependencies = [ + "heck 0.5.0", + "inventory", + "serde", + "serde_json", + "topcoat-asset", + "topcoat-core", + "topcoat-router", + "topcoat-view", + "topcoat-view-macro", +] + +[[package]] +name = "topcoat-font-grammar" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b462fae28641a1bb24eab1fa9c473520389ca690331ca53fd6143d5b2746045e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "topcoat-core-grammar", + "topcoat-font", +] + +[[package]] +name = "topcoat-font-macro" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40776cd3087aaea5e0c8b597126b1c09dbfb0d69833088d7f3b229305bbbb87f" +dependencies = [ + "quote", + "syn 3.0.9", + "topcoat-font-grammar", +] + +[[package]] +name = "topcoat-icon" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b58c90b0c0a5a8d14efa25eff58b7f11ed8abf6e0aaa2190f52a2af052c60c2a" +dependencies = [ + "topcoat-core", + "topcoat-view", + "topcoat-view-macro", +] + +[[package]] +name = "topcoat-icon-grammar" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d026a6a99399fef6a27dafded373c9a7a187f6942be8a0b7d63eb2463c532c7" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "serde_json", + "syn 3.0.9", + "topcoat-core-grammar", + "topcoat-icon", +] + +[[package]] +name = "topcoat-icon-macro" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a27d93f6f993a66acd5cef7f499abf9b76990e49a3cc2ec6c86f3c33fe7b4b7" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "topcoat-icon-grammar", +] + +[[package]] +name = "topcoat-l10n" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34da63b3a5aea3d6c243d9fa8c98ca79b181b985f6a0a042f630672f54d12e9e" +dependencies = [ + "icu_locale", + "icu_locale_core", + "topcoat-core", + "topcoat-view", +] + +[[package]] +name = "topcoat-mail" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54a13c10c6399d9eb9b0bde38bd3d947eba56ddfaea99d9a4f971b74b6a651db" +dependencies = [ + "lettre", + "thiserror 2.0.21", + "time", + "topcoat-core", + "topcoat-router", + "topcoat-view", +] + +[[package]] +name = "topcoat-router" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9488065b08f293208b0f1aeb6667d5836b66c12dfced5e330f9a8f1d7f1ca1a" +dependencies = [ + "bytes", + "form_urlencoded", + "futures-core", + "futures-sink", + "futures-util", + "heck 0.5.0", + "http", + "http-body", + "http-body-util", + "httpdate", + "hyper", + "hyper-util", + "inventory", + "ipnet", + "matchit", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "ref-cast", + "serde", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "tokio", + "tokio-tungstenite", + "tokio-util", + "topcoat-core", + "topcoat-view", + "tower", + "tower-http", +] + +[[package]] +name = "topcoat-router-grammar" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3f51fa1a1e538bd34e02f88ebba554ac5931e55c688303a58a8e78123dfb04" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 3.0.9", + "topcoat-core-grammar", +] + +[[package]] +name = "topcoat-router-macro" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c1b56d3bf19d54bddf300d6d57ca754531d7ad5481afca0b2302ac33f5d43af" +dependencies = [ + "quote", + "syn 3.0.9", + "topcoat-router-grammar", +] + +[[package]] +name = "topcoat-runtime" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03b22136b99694b349a950cd757387a04b080fdb131eecdd51d0511e1a45ebf5" +dependencies = [ + "futures-util", + "pin-project-lite", + "ref-cast", + "serde", + "serde_json", + "tokio", + "topcoat-asset", + "topcoat-core", + "topcoat-router", + "topcoat-view", + "topcoat-view-macro", +] + +[[package]] +name = "topcoat-runtime-grammar" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab93a83c38a045a4f541c2e548d30ba5dfdd3173c18de8b1c7b049709c29db97" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "serde_json", + "syn 3.0.9", + "topcoat-core-grammar", + "topcoat-router", + "topcoat-runtime", +] + +[[package]] +name = "topcoat-runtime-macro" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5acb1db0bdba3c36e4f80f7ef530945779a1b0294b1087e7d877e33005da6283" +dependencies = [ + "quote", + "syn 3.0.9", + "topcoat-runtime-grammar", +] + +[[package]] +name = "topcoat-session" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2325c30a484b1b1b6f5012b50bc18994d37c33c6bd2f71be8ff509b591a17457" +dependencies = [ + "base64 0.22.1", + "getrandom 0.4.3", + "sha2 0.11.1", + "thiserror 2.0.21", + "tokio", + "topcoat-cookie", + "topcoat-core", + "topcoat-router", + "web-time", +] + +[[package]] +name = "topcoat-tailwind" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efbc592cc87155ed9e2fd464407e0f7708d340966c4cc8a22ce0b55006fe5136" +dependencies = [ + "sha2 0.11.1", + "thiserror 2.0.21", + "topcoat-core", + "ureq", +] + +[[package]] +name = "topcoat-ui-registry" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0bd66ac0e18d782a28fb7be6a289ee460629e7a06d7dfa432ae6ccb5d7f218" + +[[package]] +name = "topcoat-view" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db4553b91f30e30c71c2bd95ae8e931a33326c6ffb604663b9d214008f12947c" +dependencies = [ + "futures-core", + "futures-util", + "http", + "memchr", + "pin-project-lite", + "siphasher", + "smallvec", + "topcoat-core", +] + +[[package]] +name = "topcoat-view-grammar" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75dd093ffc848370da4cce7670ccdfd4e98eab48e178d5d0da5509f747d85ca6" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 3.0.9", + "topcoat-core-grammar", + "topcoat-view", +] + +[[package]] +name = "topcoat-view-macro" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffa1688d165704f08d58c03710453d0d39553292bea61b18be7959a996c3e39b" +dependencies = [ + "quote", + "syn 3.0.9", + "topcoat-view-grammar", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" +dependencies = [ + "async-compression", + "bitflags", + "bytes", + "futures-core", + "http", + "http-body", + "percent-encoding", + "pin-project-lite", + "tokio", + "tokio-util", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-appender" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" +dependencies = [ + "crossbeam-channel", + "symlink", + "thiserror 2.0.21", + "time", + "tracing-subscriber", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror 2.0.21", +] + +[[package]] +name = "turso" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1cf9c519a3a971e845a42c870930557cb53c2368c5737d4c78f8fbfd0444e98" +dependencies = [ + "mimalloc", + "thiserror 2.0.21", + "tracing", + "tracing-subscriber", + "turso_core", + "turso_sdk_kit", + "turso_sync_sdk_kit", +] + +[[package]] +name = "turso_core" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "810ee7b139fd6aa9304cb2fa278c1be0bb964c92457e2a24c1d384196ce5e217" +dependencies = [ + "aegis", + "aes", + "aes-gcm", + "allocator-api2 0.4.0", + "antithesis_sdk", + "arc-swap", + "aristo", + "bigdecimal", + "bitflags", + "branches", + "bumpalo", + "bytemuck", + "cfg_aliases", + "cfg_block", + "chrono", + "crc32c", + "crc32fast", + "crossbeam-epoch", + "crossbeam-utils", + "either", + "fallible-iterator", + "fastbloom", + "getrandom 0.2.17", + "getrandom 0.3.4", + "hex", + "icu_collator", + "icu_locale", + "intrusive-collections", + "io-uring", + "libc", + "libloading", + "libm", + "loom", + "miette", + "num-bigint", + "num-traits", + "pack1", + "parking_lot", + "pastey", + "polling", + "rand 0.9.5", + "rapidhash", + "regex", + "regex-syntax", + "roaring", + "rustc-hash 2.1.3", + "rustix 1.1.6", + "ryu", + "serde_json", + "shuttle", + "simdutf8", + "simsimd", + "smallvec", + "strum", + "strum_macros", + "tantivy", + "tempfile", + "thiserror 2.0.21", + "tracing", + "tracing-subscriber", + "turso_ext", + "turso_macros", + "turso_parser", + "twox-hash", + "uncased", + "uuid", + "windows-sys 0.61.2", +] + +[[package]] +name = "turso_ext" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5003ed7e98f082fe4114627c8d7c7ab569c27766e9bd350a0c09af06ad3fd46" +dependencies = [ + "chrono", + "getrandom 0.4.3", + "turso_macros", +] + +[[package]] +name = "turso_macros" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74770c0d0c8b272b479b5343f19dbd2f8f2677d85a4d6222fc214dcac2882beb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "turso_parser" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a69bb856ec8306ad7ed1c13fc61de6a79452bf646ca53d99bb4cc646d5bfc4ff" +dependencies = [ + "bitflags", + "memchr", + "miette", + "strum", + "strum_macros", + "thiserror 2.0.21", + "turso_macros", +] + +[[package]] +name = "turso_sdk_kit" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819a17926d04dbeb5b03f00cdab6ed7351bbb6778d00840364b9af62bca02914" +dependencies = [ + "bindgen", + "env_logger", + "parking_lot", + "tracing", + "tracing-appender", + "tracing-subscriber", + "turso_core", + "turso_ext", + "turso_sdk_kit_macros", +] + +[[package]] +name = "turso_sdk_kit_macros" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f315d7f8c5bba49d1c7ca000664a455085cb95f0fa8031c6dc1f67d6d0f28e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "turso_sync_engine" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8d37dca9e05cc090ca3d73083f82fc63b0d11c33550308ca5d93668a8441b71" +dependencies = [ + "base64 0.22.1", + "bytes", + "crc32c", + "genawaiter", + "http", + "libc", + "prost", + "roaring", + "serde", + "serde_json", + "thiserror 2.0.21", + "tracing", + "turso_core", + "turso_parser", + "uuid", +] + +[[package]] +name = "turso_sync_sdk_kit" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fe4b961c9cc90f6339447dabfe83ed13a498721e41378932ab7eaf8ddd6976" +dependencies = [ + "bindgen", + "env_logger", + "genawaiter", + "parking_lot", + "tracing", + "tracing-appender", + "tracing-subscriber", + "turso_core", + "turso_sdk_kit", + "turso_sdk_kit_macros", + "turso_sync_engine", +] + +[[package]] +name = "twox-hash" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" +dependencies = [ + "rand 0.9.5", +] + +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "typetag" +version = "0.2.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c90e86058a30d42a1a928dfb4b49bb33c98c3a2b4909492e6b0881cd94798ec2" +dependencies = [ + "erased-serde", + "inventory", + "once_cell", + "serde", + "typetag-impl", +] + +[[package]] +name = "typetag-impl" +version = "0.2.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f153acc4e99a5f2a5aefa09fb078be54e26271b2813f6041200b224c098d8328" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "ucd-trie" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" + +[[package]] +name = "uncased" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" +dependencies = [ + "version_check", +] + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" +dependencies = [ + "base64 0.23.1", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + +[[package]] +name = "utf16_iter" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" + +[[package]] +name = "utf8-ranges" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fcfc827f90e53a02eaef5e535ee14266c1d569214c6aa70133a624d8a3164ba" + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "sha1_smol", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix 0.38.44", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "xxhash-rust" +version = "0.8.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7" + +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zip" +version = "9.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec2e3161de27091f18a831d9494e9c53378a34833af5c1dda35ad85849da18d6" +dependencies = [ + "crc32fast", + "flate2", + "getrandom 0.4.3", + "indexmap", + "memchr", + "nix", + "typed-path", + "windows-sys 0.61.2", + "zopfli", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.2+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..8e473c1 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "project_note" +version = "0.1.0" +edition = "2024" + +[dependencies] +anyhow = "1.0.104" +blake3 = "1.8.7" +loro = "1.17.1" +tokio = { version = "1.54.1", features = ["full"] } +topcoat = { version = "0.11.0", features = ["anyhow", "asset", "discover", "font-fontsource", "fs", "tailwind", "ui", "websocket"] } +turso = "0.8.3" +uuid = { version = "1.29.0", features = ["v7"] } +serde = { version = "1", features = ["derive"] } +zip = { version = "9.1.2", default-features = false, features = ["deflate"] } +pulldown-cmark = { version = "0.13.5", default-features = false } +serde_json = "1.0.154" +regex = "1.13.1" + +[build-dependencies] +topcoat = { version = "0.11.0", default-features = false, features = ["tailwind"] } diff --git a/assets/editor.css b/assets/editor.css new file mode 100644 index 0000000..bf2822e --- /dev/null +++ b/assets/editor.css @@ -0,0 +1 @@ +.ProseMirror{position:relative;word-wrap:break-word;white-space:pre-wrap;white-space:break-spaces;-webkit-font-variant-ligatures:none;font-variant-ligatures:none;font-feature-settings:"liga" 0}.ProseMirror pre{white-space:pre-wrap}.ProseMirror li{position:relative}.ProseMirror-hideselection *::selection{background:0 0}.ProseMirror-hideselection *::selection{background:0 0}.ProseMirror-hideselection{caret-color:transparent}.ProseMirror [draggable][contenteditable=false]{user-select:text}.ProseMirror-selectednode{outline:2px solid #8cf}li.ProseMirror-selectednode{outline:none}li.ProseMirror-selectednode:after{content:"";position:absolute;pointer-events:none;border:2px solid #8cf;inset:-2px -2px -2px -32px}img.ProseMirror-separator{display:inline!important;border:none!important;margin:0!important}.ProseMirror-gapcursor{display:none;pointer-events:none;position:absolute}.ProseMirror-gapcursor:after{content:"";display:block;position:absolute;animation:1.1s steps(2,start) infinite ProseMirror-cursor-blink;border-top:1px solid #000;width:20px;top:-2px}@keyframes ProseMirror-cursor-blink{to{visibility:hidden}}.ProseMirror-focused .ProseMirror-gapcursor{display:block}.sr-only{position:absolute;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;width:1px;height:1px;margin:-1px;padding:0}.keycaps{display:inline-flex;vertical-align:middle;align-items: center;gap:3px;margin-inline-start:6px}.keycap{display:inline-flex;border:1px solid var(--border,#e3e5ea);background:var(--keycap-bg,#fff);color:var(--muted-foreground,#5b6270);font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);font-variant-numeric:tabular-nums;border-bottom-width:2px;border-radius:6px;justify-content:center;align-items: center;min-width:18px;height:18px;padding:0 4px;font-size:11px;font-weight:500;line-height:1}.tip{position:absolute;z-index:40;display:flex;border:1px solid var(--border,#e3e5ea);background:var(--popover,#fff);color:var(--popover-foreground,#16181d);box-shadow:var(--shadow-float,0 8px 24px #0000001f);font-family:var(--font-sans,"Atkinson Hyperlegible Next",sans-serif);white-space:nowrap;pointer-events:none;opacity:0;border-radius:10px;flex-wrap:wrap;align-items: center;gap:2px;max-width:240px;padding:4px 6px 4px 8px;transition:opacity .15s ease-out,transform .15s ease-out;font-size:12px;font-weight:500;line-height:16px;top:calc(100% + 6px);left:50%;transform:translate(-50%,-2px)}.tip .keycaps{margin-inline-start:4px}.tip-reason{display:none;color:var(--muted-foreground,#5b6270);flex-basis:100%;font-weight:400}.editor-toolbar-btn:disabled .tip-reason{display:block}.editor-toolbar-btn:hover .tip,.bubble-btn:hover .tip{opacity:1;transition-delay:.3s;transform:translate(-50%)}.editor-toolbar-btn:focus-visible .tip{opacity:1;transition-delay:.3s;transform:translate(-50%)}.bubble-btn:focus-visible .tip{opacity:1;transition-delay:.3s;transform:translate(-50%)}.bubble .tip{top:auto;bottom:calc(100% + 6px)}#sync-status{display:inline-flex;border:1px solid var(--border,#e3e5ea);background:var(--card,#fff);color:var(--muted-foreground,#5b6270);font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);white-space:nowrap;border-radius:999px;align-items: center;gap:6px;height:24px;padding:0 10px 0 8px;transition:color .15s ease-out;font-size:12px;font-weight:400;line-height:16px}#sync-status:before{content:"";background:currentColor;border-radius:50%;flex:none;width:6px;height:6px}#sync-status[data-state=saved]{color:var(--ok,#1f7a4d)}#sync-status[data-state=saving]{color:var(--muted-foreground,#5b6270)}#sync-status[data-state=local],#sync-status[data-state=reconnecting]{color:var(--warn,#9a5b00)}#note-header{container:note-header/inline-size}.editor-toolbar{display:flex;flex-wrap:nowrap;flex:none;align-items: center;gap:2px}.editor-toolbar-group{display:flex;align-items: center;gap:2px}.editor-toolbar-group+.editor-toolbar-group:before{content:"";background:var(--border,#e3e5ea);width:1px;height:16px;margin:0 4px}@container note-header (width<=879px){.note-crumb-notebook{display:none}}@container note-header (width<=779px){.editor-toolbar-group[data-group=blocks]{display:none}}@container note-header (width<=619px){.editor-toolbar-btn[data-command=h1],.editor-toolbar-btn[data-command=h2],.editor-toolbar-btn[data-command=h3]{display:none}}@container note-header (width<=559px){#sync-status{gap:0;padding:0 8px;font-size:0}}@container note-header (width<=469px){.editor-toolbar-group[data-group=history]{display:none}}@container note-header (width<=419px){.editor-toolbar-btn[data-command=paragraph],.editor-toolbar-group[data-group=headings]{display:none}.note-crumb{min-width:6rem}}.editor-toolbar-btn{position:relative;display:inline-grid;color:var(--muted-foreground,#5b6270);cursor:pointer;background:0 0;border:0;border-radius:6px;place-items: center;width:28px;height:28px;margin:0;padding:0;transition:background-color .15s ease-out,color .15s ease-out}.editor-toolbar-icon{display:grid;place-items: center}.editor-toolbar-icon svg{display:block}.editor-toolbar-btn:hover:not(:disabled){background:var(--sidebar-accent,#e3e6eb);color:var(--foreground,#16181d)}.editor-toolbar-btn[aria-pressed=true]{background:var(--active-row,#d9ebd3);color:var(--active-row-foreground,#1f3d22)}.editor-toolbar-btn:disabled{opacity:.4;cursor:not-allowed}.editor-toolbar-btn:focus-visible{outline:2px solid var(--ring,#8a5a00);outline-offset:2px}.bubble-btn:focus-visible{outline:2px solid var(--ring,#8a5a00);outline-offset:2px}.btn:focus-visible{outline:2px solid var(--ring,#8a5a00);outline-offset:2px}.link-input:focus-visible{outline:2px solid var(--ring,#8a5a00);outline-offset:2px}.slash-item:focus-visible{outline:2px solid var(--ring,#8a5a00);outline-offset:2px}.bubble,.popover{position:fixed;z-index:50;color:var(--popover-foreground,#16181d);background:var(--popover,#fff);border:1px solid var(--border,#e3e5ea);box-shadow:var(--shadow-float,0 8px 24px #0000001f);font-family:var(--font-sans,"Atkinson Hyperlegible Next",sans-serif);border-radius:10px;font-size:14px;line-height:20px}.bubble[hidden],.popover[hidden],.link-view[hidden],.link-edit[hidden],.link-error[hidden]{display:none}.bubble{display:flex;align-items: center;gap:2px;padding:4px}.bubble-btn{position:relative;display:inline-grid;color:var(--foreground,#16181d);font-family:var(--font-sans,"Atkinson Hyperlegible Next",sans-serif);cursor:pointer;background:0 0;border:0;border-radius:6px;place-items: center;min-width:28px;height:28px;margin:0;padding:0 6px;transition:background-color .15s ease-out;font-size:13px;font-weight:700;line-height:1}.bubble-btn:hover:not(:disabled){background:var(--sidebar-accent,#e3e6eb)}.bubble-btn[aria-pressed=true]{background:var(--active-row,#d9ebd3)}.bubble-btn:disabled{opacity:.4;cursor:not-allowed}.bubble-btn[data-command=italic] .bubble-glyph{font-style:italic;font-weight:500}.bubble-btn[data-command=bold] .bubble-glyph{font-weight:800}.bubble-btn[data-command=code] .bubble-glyph{font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);font-size:12px;font-weight:500}.link-popover{box-sizing:border-box;width:min(360px,100vw - 16px);padding:10px}.link-row{display:flex;gap:6px}.link-input{border:1px solid var(--border,#e3e5ea);background:var(--card,#fff);color:var(--foreground,#16181d);font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);border-radius:6px;flex:1;min-width:0;height:32px;padding:0 10px;font-size:13px}.link-input[aria-invalid=true]{border-color:var(--bad,#b3261e)}.link-input::placeholder{color:var(--muted-foreground,#5b6270)}.link-error{color:var(--bad,#b3261e);margin:6px 0 0;font-size:12px;line-height:16px}.link-actions{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}.link-view{display:grid;gap:2px}.link-href{display:block;color:var(--link,#8a5a00);font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);overflow-wrap:anywhere;font-size:13px;line-height:18px}.btn{display:inline-flex;border:1px solid var(--border,#e3e5ea);background:var(--card,#fff);color:var(--foreground,#16181d);font-family:var(--font-sans,"Atkinson Hyperlegible Next",sans-serif);cursor:pointer;border-radius:6px;align-items: center;gap:6px;height:28px;padding:0 10px;transition:background-color .15s ease-out;font-size:13px;font-weight:500;line-height:1}.btn:hover:not(:disabled){background:var(--sidebar-accent,#e3e6eb)}.btn:disabled{opacity:.45;cursor:not-allowed}.btn-primary{background:var(--primary,#f2b600);color:var(--primary-foreground,#16181d);border-color:#0000}.btn-primary:hover:not(:disabled){background:var(--primary,#f2b600);opacity:.9}.btn-primary .keycaps{margin-inline-start:2px}.btn-primary .keycap{border-color:#0000;border-bottom-color:color-mix(in srgb,var(--primary-foreground,#16181d)35%,transparent);color:inherit;background:0 0}.slash-menu{box-sizing:border-box;width:264px;max-width:calc(100vw - 16px);padding:4px}.slash-list{overflow-y:auto;max-height:288px}.slash-item{display:flex;color:var(--foreground,#16181d);cursor:pointer;border-radius:6px;justify-content:space-between;align-items: center;gap:12px;min-height:32px;padding:0 8px}.slash-item[aria-selected=true]{background:var(--active-row,#d9ebd3)}.slash-item .keycaps{margin-inline-start:0}.slash-empty{color:var(--muted-foreground,#5b6270);padding:8px;font-size:13px}.slash-footer{display:flex;border-top:1px solid var(--border,#e3e5ea);color:var(--muted-foreground,#5b6270);font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);flex-wrap:wrap;align-items: center;gap:2px;margin-top:4px;padding:6px 8px 2px;font-size:11px;line-height:16px}.slash-footer .keycaps{margin-inline-start:0}.note-menu .slash-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}#editor{box-sizing:border-box;max-width:calc(68ch + 48px);margin:0 auto;padding:32px 24px 30vh}#editor .ProseMirror{outline:none;color:var(--foreground,#16181d);caret-color:var(--foreground,#16181d);font-family:var(--font-sans,"Atkinson Hyperlegible Next",sans-serif);overflow-wrap:break-word;word-wrap:break-word;font-variant-ligatures:common-ligatures;max-width:68ch;min-height:60vh;margin:0 auto;font-size:17px;line-height:1.65}#editor .ProseMirror:focus{outline:none}#editor .ProseMirror:focus-visible{outline:none}#editor .ProseMirror>*+*{margin-top:.75em}#editor .ProseMirror ::selection,#editor .ProseMirror::selection{background:var(--mark,#ffe08a);color:var(--foreground,#16181d)}#editor .ProseMirror p{margin:0}#editor .ProseMirror p.is-placeholder:before{content:attr(data-placeholder);float:left;color:var(--muted-foreground,#5b6270);pointer-events:none;height:0}#editor .ProseMirror h1,#editor .ProseMirror h2,#editor .ProseMirror h3{color:var(--foreground,#16181d);letter-spacing:-.01em;margin:0;font-weight:700}#editor .ProseMirror>*+h1,#editor .ProseMirror>*+h2,#editor .ProseMirror>*+h3{margin-top:1.4em}#editor .ProseMirror h1{font-size:30px;line-height:36px}#editor .ProseMirror h2{font-size:23px;line-height:30px}#editor .ProseMirror h3{font-size:19px;line-height:26px}#editor .ProseMirror ul,#editor .ProseMirror ol{margin:0;padding-left:1.6em}#editor .ProseMirror ul{list-style:disc}#editor .ProseMirror ol{list-style:decimal}#editor .ProseMirror ul ul{list-style:circle}#editor .ProseMirror ul ul ul{list-style:square}#editor .ProseMirror li{margin:.2em 0}#editor .ProseMirror li::marker{color:var(--muted-foreground,#5b6270)}#editor .ProseMirror li>p+p,#editor .ProseMirror li>*+ul,#editor .ProseMirror li>*+ol{margin-top:.2em}#editor .ProseMirror blockquote{border-left:3px solid var(--border,#e3e5ea);color:var(--muted-foreground,#5b6270);margin:0;padding:2px 0 2px 16px}#editor .ProseMirror code{border:1px solid var(--border,#e3e5ea);background:var(--background,#f5f6f8);color:var(--foreground,#16181d);font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);border-radius:6px;padding:1px 5px;font-size:.88em}#editor .ProseMirror pre{border:1px solid var(--border,#e3e5ea);background:var(--background,#f5f6f8);color:var(--foreground,#16181d);font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);overflow-x:auto;white-space:pre;border-radius:10px;margin:0;padding:12px 14px;font-size:14px;line-height:22px}#editor .ProseMirror pre code{font-size:inherit;background:0 0;border:0;border-radius:0;padding:0}#editor .ProseMirror mark{background:var(--mark,#ffe08a);color:inherit;border-radius:3px;padding:0 .1em}#editor .ProseMirror a{color:var(--link,#8a5a00);text-decoration-line:underline;text-decoration-thickness:1px;text-decoration-color:color-mix(in srgb,var(--link,#8a5a00)45%,transparent);text-underline-offset:3px;cursor:pointer}#editor .ProseMirror a:hover{text-decoration-color:var(--link,#8a5a00)}#editor .ProseMirror a[href^="/notes/"]{background:color-mix(in srgb,var(--link,#8a5a00)12%,transparent);text-decoration-line:none;box-decoration-break:clone;-webkit-box-decoration-break:clone;border-radius:4px;padding:0 .2em}#editor .ProseMirror a[href^="/notes/"]:hover{text-decoration-line:underline}#editor .ProseMirror hr{border:0;border-top:1px solid var(--border,#e3e5ea);margin:2em 0}#editor .ProseMirror hr.ProseMirror-selectednode{outline:2px solid var(--ring,#8a5a00);outline-offset:4px;border-radius:2px}.ProseMirror-loro-cursor{position:relative;word-break:normal;pointer-events:none;border-left:2px solid;margin-left:-1px;margin-right:-1px}.ProseMirror-loro-cursor>div{position:absolute;color:#fff;font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);white-space:nowrap;user-select:none;border-radius:4px 4px 4px 0;padding:0 5px;font-size:11px;font-weight:500;line-height:16px;top:-1.5em;left:-2px}.loro-selection{border-radius:2px}@media (prefers-reduced-motion:reduce){.editor-toolbar-btn,.bubble-btn,.btn,.tip,#sync-status{transition-duration:0s!important;transition-delay:0s!important}}@media (forced-colors:active){.editor-toolbar-btn[aria-pressed=true],.bubble-btn[aria-pressed=true],.slash-item[aria-selected=true]{outline:2px solid canvastext}} diff --git a/assets/editor.js b/assets/editor.js new file mode 100644 index 0000000..3b07f42 --- /dev/null +++ b/assets/editor.js @@ -0,0 +1,16 @@ +var ri=["Map","List","MovableList","Text","Tree","Counter"];function Ro(t,e){if(typeof t!=="object"||t===null||Array.isArray(t))throw Error("Invalid toContainerTree options");for(let n of Object.keys(t))if(n!=="text"&&!(e&&n==="roots"))throw Error("Unknown toContainerTree option: "+n);if(e&&t.roots!==void 0&&!Array.isArray(t.roots))throw Error("roots must be an array");return t}function Lo(t,e,n){return{cid:t.cid,start:e,totalLength:n,items:t.value}}function Po(t,e,n){return{type:ri[t],cid:e,value:n}}function Bo(t,e,n){return"cid:"+e+"@"+t+":"+ri[n]}function zo(t,e){return"cid:root-"+t+":"+ri[e]}function Fo(t){return{type:"Value",value:t}}function Vo(t){return t.slice()}function Wo(t,e,n){Object.defineProperty(t,e,{value:n,enumerable:!0,writable:!0,configurable:!0})}function qo(t,e,n){Object.defineProperty(t,e,{value:n,enumerable:!0,writable:!0,configurable:!0})}var a,tt=Array(128).fill(void 0);tt.push(void 0,null,!0,!1);function x(t){return tt[t]}var M=0,An=null;function Ze(){if(An===null||An.byteLength===0)An=new Uint8Array(a.memory.buffer);return An}var ur=typeof TextEncoder<"u"?new TextEncoder("utf-8"):{encode:()=>{throw Error("TextEncoder not available")}},kc=typeof ur.encodeInto==="function"?function(t,e){return ur.encodeInto(t,e)}:function(t,e){let n=ur.encode(t);return e.set(n),{read:t.length,written:n.length}};function q(t,e,n){if(n===void 0){let l=ur.encode(t),c=e(l.length,1)>>>0;return Ze().subarray(c,c+l.length).set(l),M=l.length,c}let r=t.length,i=e(r,1)>>>0,o=Ze(),s=0;for(;s127)break;o[i+s]=l}if(s!==r){if(s!==0)t=t.slice(s);i=n(i,r,r=s+t.length*3,1)>>>0;let l=Ze().subarray(i+s,i+r),c=kc(t,l);s+=c.written,i=n(i,r,s,1)>>>0}return M=s,i}var De=null;function u(){if(De===null||De.buffer.detached===!0||De.buffer.detached===void 0&&De.buffer!==a.memory.buffer)De=new DataView(a.memory.buffer);return De}var En=tt.length;function w(t){if(En===tt.length)tt.push(tt.length+1);let e=En;return En=tt[e],tt[e]=t,e}function gt(t,e){try{return t.apply(this,e)}catch(n){a.__wbindgen_exn_store(w(n))}}var Xo=typeof TextDecoder<"u"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};if(typeof TextDecoder<"u")Xo.decode();function it(t,e){return t=t>>>0,Xo.decode(Ze().subarray(t,t+e))}function xc(t){if(t<132)return;tt[t]=En,En=t}function _(t){let e=x(t);return xc(t),e}function Te(t,e){return t=t>>>0,Ze().subarray(t/1,t/1+e)}function K(t){return t===void 0||t===null}var Uo=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>{a.__wbindgen_export_4.get(t.dtor)(t.a,t.b)});function $o(t,e,n,r){let i={a:t,b:e,cnt:1,dtor:n},o=(...s)=>{i.cnt++;let l=i.a;i.a=0;try{return r(l,i.b,...s)}finally{if(--i.cnt===0)a.__wbindgen_export_4.get(i.dtor)(l,i.b),Uo.unregister(i);else i.a=l}};return o.original=i,Uo.register(o,i,i),o}function hi(t){let e=typeof t;if(e=="number"||e=="boolean"||t==null)return`${t}`;if(e=="string")return`"${t}"`;if(e=="symbol"){let i=t.description;if(i==null)return"Symbol";else return`Symbol(${i})`}if(e=="function"){let i=t.name;if(typeof i=="string"&&i.length>0)return`Function(${i})`;else return"Function"}if(Array.isArray(t)){let i=t.length,o="[";if(i>0)o+=hi(t[0]);for(let s=1;s1)r=n[1];else return toString.call(t);if(r=="Object")try{return"Object("+JSON.stringify(t)+")"}catch(i){return"Object"}if(t instanceof Error)return`${t.name}: ${t.message} +${t.stack}`;return r}function Nn(t,e){let n=e(t.length*1,1)>>>0;return Ze().set(t,n/1),M=t.length,n}function fr(){a.callPendingEvents()}function pi(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M;return a.isValidContainerId(e,n)!==0}function Wt(t,e){let n=e(t.length*4,4)>>>0,r=u();for(let i=0;i>>0;let n=u(),r=[];for(let i=t;i"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_awarenesswasm_free(t>>>0,1));var Jo=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_changemodifier_free(t>>>0,1));class tn{static __wrap(t){t=t>>>0;let e=Object.create(tn.prototype);return e.__wbg_ptr=t,Jo.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Jo.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_changemodifier_free(t,0)}setMessage(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M,r=a.changemodifier_setMessage(this.__wbg_ptr,e,n);return tn.__wrap(r)}setTimestamp(t){let e=a.changemodifier_setTimestamp(this.__wbg_ptr,t);return tn.__wrap(e)}}var jo=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_cursor_free(t>>>0,1));class Tt{static __wrap(t){t=t>>>0;let e=Object.create(Tt.prototype);return e.__wbg_ptr=t,jo.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,jo.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_cursor_free(t,0)}containerId(){let t=a.cursor_containerId(this.__wbg_ptr);return _(t)}pos(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.cursor_pos(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}kind(){let t=a.cursor_kind(this.__wbg_ptr);return _(t)}side(){let t=a.cursor_side(this.__wbg_ptr);return _(t)}static decode(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Nn(t,a.__wbindgen_malloc),s=M;a.cursor_decode(i,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Tt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}encode(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.cursor_encode(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=Te(t,e).slice();return a.__wbindgen_free(t,e*1,1),n}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var Ho=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_ephemeralstorewasm_free(t>>>0,1));class Dn{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Ho.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_ephemeralstorewasm_free(t,0)}getAllStates(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.ephemeralstorewasm_getAllStates(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}removeOutdated(){a.ephemeralstorewasm_removeOutdated(this.__wbg_ptr)}subscribeLocalUpdates(t){let e=a.ephemeralstorewasm_subscribeLocalUpdates(this.__wbg_ptr,w(t));return _(e)}get(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M,r=a.ephemeralstorewasm_get(this.__wbg_ptr,e,n);return _(r)}constructor(t){let e=a.ephemeralstorewasm_new(t);return this.__wbg_ptr=e>>>0,Ho.register(this,this.__wbg_ptr,this),this}set(t,e){let n=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),r=M;a.ephemeralstorewasm_set(this.__wbg_ptr,n,r,w(e))}keys(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.ephemeralstorewasm_keys(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),n}finally{a.__wbindgen_add_to_stack_pointer(16)}}apply(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16),i=Nn(t,a.__wbindgen_malloc),o=M;a.ephemeralstorewasm_apply(r,this.__wbg_ptr,i,o);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}delete(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M;a.ephemeralstorewasm_delete(this.__wbg_ptr,e,n)}encode(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.ephemeralstorewasm_encode(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=Te(e,n).slice();return a.__wbindgen_free(e,n*1,1),r}finally{a.__wbindgen_add_to_stack_pointer(16)}}isEmpty(){return a.ephemeralstorewasm_isEmpty(this.__wbg_ptr)!==0}encodeAll(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.ephemeralstorewasm_encodeAll(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=Te(t,e).slice();return a.__wbindgen_free(t,e*1,1),n}finally{a.__wbindgen_add_to_stack_pointer(16)}}subscribe(t){let e=a.ephemeralstorewasm_subscribe(this.__wbg_ptr,w(t));return _(e)}}var ii=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_lorocounter_free(t>>>0,1));class Re{static __wrap(t){t=t>>>0;let e=Object.create(Re.prototype);return e.__wbg_ptr=t,ii.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,ii.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_lorocounter_free(t,0)}toContainerTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_toContainerTree(i,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isAttached(){return a.lorocounter_isAttached(this.__wbg_ptr)!==0}getAttached(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_getAttached(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getShallowValue(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_getShallowValue(r,this.__wbg_ptr);var t=u().getFloat64(r+0,!0),e=u().getInt32(r+8,!0),n=u().getInt32(r+12,!0);if(n)throw _(e);return t}finally{a.__wbindgen_add_to_stack_pointer(16)}}get id(){let t=a.lorocounter_id(this.__wbg_ptr);return _(t)}constructor(){let t=a.lorocounter_new();return this.__wbg_ptr=t>>>0,ii.register(this,this.__wbg_ptr,this),this}kind(){let t=a.lorocounter_kind(this.__wbg_ptr);return _(t)}parent(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_parent(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_getShallowValue(r,this.__wbg_ptr);var t=u().getFloat64(r+0,!0),e=u().getInt32(r+8,!0),n=u().getInt32(r+12,!0);if(n)throw _(e);return t}finally{a.__wbindgen_add_to_stack_pointer(16)}}decrement(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_decrement(r,this.__wbg_ptr,t);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get value(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_getShallowValue(r,this.__wbg_ptr);var t=u().getFloat64(r+0,!0),e=u().getInt32(r+8,!0),n=u().getInt32(r+12,!0);if(n)throw _(e);return t}finally{a.__wbindgen_add_to_stack_pointer(16)}}increment(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_increment(r,this.__wbg_ptr,t);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}subscribe(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_subscribe(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var oi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_lorodoc_free(t>>>0,1));class Pt{static __wrap(t){t=t>>>0;let e=Object.create(Pt.prototype);return e.__wbg_ptr=t,oi.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,oi.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_lorodoc_free(t,0)}applyDiff(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_applyDiff(i,this.__wbg_ptr,w(t),K(e)?0:w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isShallow(){return a.lorodoc_isShallow(this.__wbg_ptr)!==0}changeCount(){return a.lorodoc_changeCount(this.__wbg_ptr)>>>0}getByPath(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.lorodoc_getByPath(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getCounter(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getCounter(i,this.__wbg_ptr,Nt(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Re.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}isDetached(){return a.lorodoc_isDetached(this.__wbg_ptr)!==0}get peerIdStr(){let t=a.lorodoc_peerIdStr(this.__wbg_ptr);return _(t)}setPeerId(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_setPeerId(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getCursorPos(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);en(t,Tt),a.lorodoc_getCursorPos(i,this.__wbg_ptr,t.__wbg_ptr);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}hasContainer(t){return a.lorodoc_hasContainer(this.__wbg_ptr,w(t))!==0}importBatch(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_importBatch(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}cmpFrontiers(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16),s=Wt(t,a.__wbindgen_malloc),l=M,c=Wt(e,a.__wbindgen_malloc),d=M;a.lorodoc_cmpFrontiers(o,this.__wbg_ptr,s,l,c,d);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}debugHistory(){a.lorodoc_debugHistory(this.__wbg_ptr)}static fromSnapshot(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Nn(t,a.__wbindgen_malloc),s=M;a.lorodoc_fromSnapshot(i,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Pt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getChangeAt(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getChangeAt(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}oplogVersion(){let t=a.lorodoc_oplogVersion(this.__wbg_ptr);return Dt.__wrap(t)}getMovableList(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getMovableList(i,this.__wbg_ptr,Nt(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Le.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}frontiersToVV(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Wt(t,a.__wbindgen_malloc),s=M;a.lorodoc_frontiersToVV(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Dt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getAllChanges(){let t=a.lorodoc_getAllChanges(this.__wbg_ptr);return _(t)}oplogFrontiers(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_oplogFrontiers(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}vvToFrontiers(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);en(t,Dt),a.lorodoc_vvToFrontiers(i,this.__wbg_ptr,t.__wbg_ptr);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}shallowSinceVV(){let t=a.lorodoc_shallowSinceVV(this.__wbg_ptr);return Dt.__wrap(t)}configTextStyle(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_configTextStyle(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getOpsInChange(t){try{let s=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getOpsInChange(s,this.__wbg_ptr,w(t));var e=u().getInt32(s+0,!0),n=u().getInt32(s+4,!0),r=u().getInt32(s+8,!0),i=u().getInt32(s+12,!0);if(i)throw _(r);var o=te(e,n).slice();return a.__wbindgen_free(e,n*4,4),o}finally{a.__wbindgen_add_to_stack_pointer(16)}}getShallowValue(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getShallowValue(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}checkoutToLatest(){try{let n=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_checkoutToLatest(n,this.__wbg_ptr);var t=u().getInt32(n+0,!0),e=u().getInt32(n+4,!0);if(e)throw _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}cmpWithFrontiers(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Wt(t,a.__wbindgen_malloc),s=M;a.lorodoc_cmpWithFrontiers(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return e}finally{a.__wbindgen_add_to_stack_pointer(16)}}exportJsonInIdSpan(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_exportJsonInIdSpan(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}subscribeJsonpath(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16),s=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),l=M;a.lorodoc_subscribeJsonpath(o,this.__wbg_ptr,s,l,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}deleteRootContainer(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_deleteRootContainer(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}exportJsonUpdates(t,e,n){try{let s=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_exportJsonUpdates(s,this.__wbg_ptr,w(t),w(e),K(n)?16777215:n?1:0);var r=u().getInt32(s+0,!0),i=u().getInt32(s+4,!0),o=u().getInt32(s+8,!0);if(o)throw _(i);return _(r)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getContainerById(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getContainerById(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getPendingTxnLength(){return a.lorodoc_getPendingTxnLength(this.__wbg_ptr)>>>0}importJsonUpdates(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_importJsonUpdates(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}importUpdateBatch(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_importBatch(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}setDetachedEditing(t){a.lorodoc_setDetachedEditing(this.__wbg_ptr,t)}setRecordTimestamp(t){a.lorodoc_setRecordTimestamp(this.__wbg_ptr,t)}subscribePreCommit(t){let e=a.lorodoc_subscribePreCommit(this.__wbg_ptr,w(t));return _(e)}findIdSpansBetween(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16),s=Wt(t,a.__wbindgen_malloc),l=M,c=Wt(e,a.__wbindgen_malloc),d=M;a.lorodoc_findIdSpansBetween(o,this.__wbg_ptr,s,l,c,d);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getChangeAtLamport(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16),s=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),l=M;a.lorodoc_getChangeAtLamport(o,this.__wbg_ptr,s,l,e);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getPathToContainer(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getPathToContainer(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}exportPendingUpdates(){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_exportPendingUpdates(i,this.__wbg_ptr);var t=u().getInt32(i+0,!0),e=u().getInt32(i+4,!0),n=u().getInt32(i+8,!0),r=u().getInt32(i+12,!0);if(r)throw _(n);let o;if(t!==0)o=Te(t,e).slice(),a.__wbindgen_free(t,e*1,1);return o}finally{a.__wbindgen_add_to_stack_pointer(16)}}getChangedContainersIn(t,e){try{let l=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getChangedContainersIn(l,this.__wbg_ptr,w(t),e);var n=u().getInt32(l+0,!0),r=u().getInt32(l+4,!0),i=u().getInt32(l+8,!0),o=u().getInt32(l+12,!0);if(o)throw _(i);var s=te(n,r).slice();return a.__wbindgen_free(n,r*4,4),s}finally{a.__wbindgen_add_to_stack_pointer(16)}}getDeepValueWithID(){let t=a.lorodoc_getDeepValueWithID(this.__wbg_ptr);return _(t)}setNextCommitOrigin(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M;a.lorodoc_setNextCommitOrigin(this.__wbg_ptr,e,n)}getUncommittedOpsAsJson(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getUncommittedOpsAsJson(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}setNextCommitMessage(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M;a.lorodoc_setNextCommitMessage(this.__wbg_ptr,e,n)}setNextCommitOptions(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_setNextCommitOptions(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}shallowSinceFrontiers(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_shallowSinceFrontiers(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}subscribeLocalUpdates(t){let e=a.lorodoc_subscribeLocalUpdates(this.__wbg_ptr,w(t));return _(e)}travelChangeAncestors(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Wt(t,a.__wbindgen_malloc),s=M;a.lorodoc_travelChangeAncestors(i,this.__wbg_ptr,o,s,w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}clearNextCommitOptions(){a.lorodoc_clearNextCommitOptions(this.__wbg_ptr)}configDefaultTextStyle(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_configDefaultTextStyle(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getDecodedValueCacheLimit(){return a.lorodoc_getDecodedValueCacheLimit(this.__wbg_ptr)>>>0}setChangeMergeInterval(t){a.lorodoc_setChangeMergeInterval(this.__wbg_ptr,t)}setNextCommitTimestamp(t){a.lorodoc_setNextCommitTimestamp(this.__wbg_ptr,t)}setHideEmptyRootContainers(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_setHideEmptyRootContainers(r,this.__wbg_ptr,t);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isDetachedEditingEnabled(){return a.lorodoc_isDetachedEditingEnabled(this.__wbg_ptr)!==0}setDecodedValueCacheLimit(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_setDecodedValueCacheLimit(r,this.__wbg_ptr,t);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}subscribeFirstCommitFromPeer(t){let e=a.lorodoc_subscribeFirstCommitFromPeer(this.__wbg_ptr,w(t));return _(e)}constructor(){let t=a.lorodoc_new();return this.__wbg_ptr=t>>>0,oi.register(this,this.__wbg_ptr,this),this}diff(t,e,n){try{let s=a.__wbindgen_add_to_stack_pointer(-16),l=Wt(t,a.__wbindgen_malloc),c=M,d=Wt(e,a.__wbindgen_malloc),f=M;a.lorodoc_diff(s,this.__wbg_ptr,l,c,d,f,K(n)?16777215:n?1:0);var r=u().getInt32(s+0,!0),i=u().getInt32(s+4,!0),o=u().getInt32(s+8,!0);if(o)throw _(i);return _(r)}finally{a.__wbindgen_add_to_stack_pointer(16)}}fork(){let t=a.lorodoc_fork(this.__wbg_ptr);return Pt.__wrap(t)}attach(){a.lorodoc_attach(this.__wbg_ptr)}commit(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_commit(r,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}detach(){a.lorodoc_detach(this.__wbg_ptr)}export(t){try{let s=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_export(s,this.__wbg_ptr,w(t));var e=u().getInt32(s+0,!0),n=u().getInt32(s+4,!0),r=u().getInt32(s+8,!0),i=u().getInt32(s+12,!0);if(i)throw _(r);var o=Te(e,n).slice();return a.__wbindgen_free(e,n*1,1),o}finally{a.__wbindgen_add_to_stack_pointer(16)}}import(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Nn(t,a.__wbindgen_malloc),s=M;a.lorodoc_import(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}forkAt(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Wt(t,a.__wbindgen_malloc),s=M;a.lorodoc_forkAt(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Pt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getMap(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getMap(i,this.__wbg_ptr,Nt(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return St.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}opCount(){return a.lorodoc_opCount(this.__wbg_ptr)>>>0}get peerId(){let t=a.lorodoc_peerId(this.__wbg_ptr);return BigInt.asUintN(64,t)}toJSON(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_toJSON(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}version(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_version(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return Dt.__wrap(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}checkout(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16),i=Wt(t,a.__wbindgen_malloc),o=M;a.lorodoc_checkout(r,this.__wbg_ptr,i,o);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getList(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getList(i,this.__wbg_ptr,Nt(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return ee.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}getText(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getText(i,this.__wbg_ptr,Nt(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Rt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}getTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getTree(i,this.__wbg_ptr,Nt(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return me.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}frontiers(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_frontiers(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}JSONPath(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.lorodoc_JSONPath(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}revertTo(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16),i=Wt(t,a.__wbindgen_malloc),o=M;a.lorodoc_revertTo(r,this.__wbg_ptr,i,o);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}subscribe(t){let e=a.lorodoc_subscribe(this.__wbg_ptr,w(t));return _(e)}toContainerTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_toContainerTree(i,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toContainerTreeJson(t){let e,n;try{let d=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_toContainerTreeJson(d,this.__wbg_ptr,K(t)?0:w(t));var r=u().getInt32(d+0,!0),i=u().getInt32(d+4,!0),o=u().getInt32(d+8,!0),s=u().getInt32(d+12,!0),l=r,c=i;if(s)throw l=0,c=0,_(o);return e=l,n=c,it(l,c)}finally{a.__wbindgen_add_to_stack_pointer(16),a.__wbindgen_free(e,n,1)}}}var si=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_lorolist_free(t>>>0,1));class ee{static __wrap(t){t=t>>>0;let e=Object.create(ee.prototype);return e.__wbg_ptr=t,si.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,si.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_lorolist_free(t,0)}isAttached(){return a.lorolist_isAttached(this.__wbg_ptr)!==0}getAttached(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_getAttached(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}pushContainer(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_pushContainer(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getRangeValue(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_getRangeValue(o,this.__wbg_ptr,t,e);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}insertContainer(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_insertContainer(o,this.__wbg_ptr,t,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getShallowValue(){let t=a.lorolist_getShallowValue(this.__wbg_ptr);return _(t)}getDeepValueWithID(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_getDeepValueWithID(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getRangeDeepValueWithID(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_getRangeDeepValueWithID(o,this.__wbg_ptr,t,e);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get id(){let t=a.lorolist_id(this.__wbg_ptr);return _(t)}get(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_get(i,this.__wbg_ptr,t);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}constructor(){let t=a.lorolist_new();return this.__wbg_ptr=t>>>0,si.register(this,this.__wbg_ptr,this),this}pop(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_pop(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}kind(){let t=a.lorolist_kind(this.__wbg_ptr);return _(t)}push(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_push(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}clear(){try{let n=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_clear(n,this.__wbg_ptr);var t=u().getInt32(n+0,!0),e=u().getInt32(n+4,!0);if(e)throw _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}delete(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_delete(i,this.__wbg_ptr,t,e);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}insert(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_insert(i,this.__wbg_ptr,t,w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get length(){return a.lorolist_length(this.__wbg_ptr)>>>0}parent(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_parent(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getIdAt(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_getIdAt(i,this.__wbg_ptr,t);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){let t=a.lorolist_toJSON(this.__wbg_ptr);return _(t)}toArray(){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_toArray(o,this.__wbg_ptr);var t=u().getInt32(o+0,!0),e=u().getInt32(o+4,!0),n=u().getInt32(o+8,!0),r=u().getInt32(o+12,!0);if(r)throw _(n);var i=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),i}finally{a.__wbindgen_add_to_stack_pointer(16)}}getCursor(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_getCursor(o,this.__wbg_ptr,t,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return n===0?void 0:Tt.__wrap(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isDeleted(){return a.lorolist_isDeleted(this.__wbg_ptr)!==0}subscribe(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_subscribe(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toContainerTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_toContainerTree(i,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toContainerTreeSlice(t,e,n){try{let s=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_toContainerTreeSlice(s,this.__wbg_ptr,t,e,K(n)?0:w(n));var r=u().getInt32(s+0,!0),i=u().getInt32(s+4,!0),o=u().getInt32(s+8,!0);if(o)throw _(i);return _(r)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var li=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_loromap_free(t>>>0,1));class St{static __wrap(t){t=t>>>0;let e=Object.create(St.prototype);return e.__wbg_ptr=t,li.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,li.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_loromap_free(t,0)}isAttached(){return a.loromap_isAttached(this.__wbg_ptr)!==0}getAttached(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_getAttached(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getLastEditor(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M,r=a.loromap_getLastEditor(this.__wbg_ptr,e,n);return _(r)}setContainer(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16),s=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),l=M;a.loromap_setContainer(o,this.__wbg_ptr,s,l,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getShallowValue(){let t=a.loromap_getShallowValue(this.__wbg_ptr);return _(t)}ensureMergeableMap(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_ensureMergeableMap(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return St.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}ensureMergeableList(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_ensureMergeableList(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return ee.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}ensureMergeableText(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_ensureMergeableText(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Rt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}ensureMergeableTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_ensureMergeableTree(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return me.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getDeepValueWithID(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_getDeepValueWithID(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getOrCreateContainer(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16),s=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),l=M;a.loromap_getOrCreateContainer(o,this.__wbg_ptr,s,l,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}ensureMergeableCounter(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_ensureMergeableCounter(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Re.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}ensureMergeableMovableList(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_ensureMergeableMovableList(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Le.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get id(){let t=a.loromap_id(this.__wbg_ptr);return _(t)}get(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_get(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}constructor(){let t=a.loromap_new();return this.__wbg_ptr=t>>>0,li.register(this,this.__wbg_ptr,this),this}keys(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_keys(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),n}finally{a.__wbindgen_add_to_stack_pointer(16)}}kind(){let t=a.loromap_kind(this.__wbg_ptr);return _(t)}get size(){return a.loromap_size(this.__wbg_ptr)>>>0}clear(){try{let n=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_clear(n,this.__wbg_ptr);var t=u().getInt32(n+0,!0),e=u().getInt32(n+4,!0);if(e)throw _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}delete(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16),i=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),o=M;a.loromap_delete(r,this.__wbg_ptr,i,o);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}set(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_set(i,this.__wbg_ptr,o,s,w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}parent(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_parent(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}values(){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_values(o,this.__wbg_ptr);var t=u().getInt32(o+0,!0),e=u().getInt32(o+4,!0),n=u().getInt32(o+8,!0),r=u().getInt32(o+12,!0);if(r)throw _(n);var i=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),i}finally{a.__wbindgen_add_to_stack_pointer(16)}}entries(){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_entries(o,this.__wbg_ptr);var t=u().getInt32(o+0,!0),e=u().getInt32(o+4,!0),n=u().getInt32(o+8,!0),r=u().getInt32(o+12,!0);if(r)throw _(n);var i=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),i}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){let t=a.loromap_toJSON(this.__wbg_ptr);return _(t)}isDeleted(){return a.loromap_isDeleted(this.__wbg_ptr)!==0}subscribe(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_subscribe(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toContainerTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_toContainerTree(i,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var ai=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_loromovablelist_free(t>>>0,1));class Le{static __wrap(t){t=t>>>0;let e=Object.create(Le.prototype);return e.__wbg_ptr=t,ai.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,ai.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_loromovablelist_free(t,0)}isAttached(){return a.loromovablelist_isAttached(this.__wbg_ptr)!==0}getCreatorAt(t){let e=a.loromovablelist_getCreatorAt(this.__wbg_ptr,t);return _(e)}getAttached(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_getAttached(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}setContainer(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_setContainer(o,this.__wbg_ptr,t,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getLastMoverAt(t){let e=a.loromovablelist_getLastMoverAt(this.__wbg_ptr,t);return _(e)}pushContainer(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_pushContainer(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getLastEditorAt(t){let e=a.loromovablelist_getLastEditorAt(this.__wbg_ptr,t);return _(e)}getRangeValue(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_getRangeValue(o,this.__wbg_ptr,t,e);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}insertContainer(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_insertContainer(o,this.__wbg_ptr,t,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getShallowValue(){let t=a.loromovablelist_getShallowValue(this.__wbg_ptr);return _(t)}getDeepValueWithID(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_getDeepValueWithID(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getRangeDeepValueWithID(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_getRangeDeepValueWithID(o,this.__wbg_ptr,t,e);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get id(){let t=a.loromovablelist_id(this.__wbg_ptr);return _(t)}get(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_get(i,this.__wbg_ptr,t);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}move(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_move(i,this.__wbg_ptr,t,e);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}constructor(){let t=a.loromovablelist_new();return this.__wbg_ptr=t>>>0,ai.register(this,this.__wbg_ptr,this),this}pop(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_pop(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}set(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_set(i,this.__wbg_ptr,t,w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}kind(){let t=a.loromovablelist_kind(this.__wbg_ptr);return _(t)}push(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_push(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}clear(){try{let n=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_clear(n,this.__wbg_ptr);var t=u().getInt32(n+0,!0),e=u().getInt32(n+4,!0);if(e)throw _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}delete(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_delete(i,this.__wbg_ptr,t,e);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}insert(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_insert(i,this.__wbg_ptr,t,w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get length(){return a.loromovablelist_length(this.__wbg_ptr)>>>0}parent(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_parent(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){let t=a.loromovablelist_toJSON(this.__wbg_ptr);return _(t)}toArray(){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_toArray(o,this.__wbg_ptr);var t=u().getInt32(o+0,!0),e=u().getInt32(o+4,!0),n=u().getInt32(o+8,!0),r=u().getInt32(o+12,!0);if(r)throw _(n);var i=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),i}finally{a.__wbindgen_add_to_stack_pointer(16)}}getCursor(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_getCursor(o,this.__wbg_ptr,t,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return n===0?void 0:Tt.__wrap(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isDeleted(){return a.loromovablelist_isDeleted(this.__wbg_ptr)!==0}subscribe(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_subscribe(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toContainerTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_toContainerTree(i,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toContainerTreeSlice(t,e,n){try{let s=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_toContainerTreeSlice(s,this.__wbg_ptr,t,e,K(n)?0:w(n));var r=u().getInt32(s+0,!0),i=u().getInt32(s+4,!0),o=u().getInt32(s+8,!0);if(o)throw _(i);return _(r)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var ci=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_lorotext_free(t>>>0,1));class Rt{static __wrap(t){t=t>>>0;let e=Object.create(Rt.prototype);return e.__wbg_ptr=t,ci.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,ci.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_lorotext_free(t,0)}applyDelta(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_applyDelta(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}convertPos(t,e,n){let r=q(e,a.__wbindgen_malloc,a.__wbindgen_realloc),i=M,o=q(n,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M,l=a.lorotext_convertPos(this.__wbg_ptr,t,r,i,o,s);return _(l)}deleteUtf8(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_deleteUtf8(i,this.__wbg_ptr,t,e);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getEditorOf(t){let e=a.lorotext_getEditorOf(this.__wbg_ptr,t);return _(e)}insertUtf8(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(e,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.lorotext_insertUtf8(i,this.__wbg_ptr,t,o,s);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isAttached(){return a.lorotext_isAttached(this.__wbg_ptr)!==0}sliceDelta(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_sliceDelta(o,this.__wbg_ptr,t,e);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getAttached(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_getAttached(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}updateByLine(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.lorotext_updateByLine(i,this.__wbg_ptr,o,s,w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}sliceDeltaUtf8(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_sliceDeltaUtf8(o,this.__wbg_ptr,t,e);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getShallowValue(){let t,e;try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_getShallowValue(i,this.__wbg_ptr);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);return t=n,e=r,it(n,r)}finally{a.__wbindgen_add_to_stack_pointer(16),a.__wbindgen_free(t,e,1)}}getDeepValueWithID(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_getDeepValueWithID(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get id(){let t=a.lorotext_id(this.__wbg_ptr);return _(t)}constructor(){let t=a.lorotext_new();return this.__wbg_ptr=t>>>0,ci.register(this,this.__wbg_ptr,this),this}iter(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_iter(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}kind(){let t=a.lorotext_kind(this.__wbg_ptr);return _(t)}mark(t,e,n){try{let o=a.__wbindgen_add_to_stack_pointer(-16),s=q(e,a.__wbindgen_malloc,a.__wbindgen_realloc),l=M;a.lorotext_mark(o,this.__wbg_ptr,w(t),s,l,w(n));var r=u().getInt32(o+0,!0),i=u().getInt32(o+4,!0);if(i)throw _(r)}finally{a.__wbindgen_add_to_stack_pointer(16)}}push(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16),i=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),o=M;a.lorotext_push(r,this.__wbg_ptr,i,o);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}slice(t,e){let n,r;try{let f=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_slice(f,this.__wbg_ptr,t,e);var i=u().getInt32(f+0,!0),o=u().getInt32(f+4,!0),s=u().getInt32(f+8,!0),l=u().getInt32(f+12,!0),c=i,d=o;if(l)throw c=0,d=0,_(s);return n=c,r=d,it(c,d)}finally{a.__wbindgen_add_to_stack_pointer(16),a.__wbindgen_free(n,r,1)}}delete(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_delete(i,this.__wbg_ptr,t,e);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}insert(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(e,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.lorotext_insert(i,this.__wbg_ptr,t,o,s);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get length(){return a.lorotext_length(this.__wbg_ptr)>>>0}parent(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_parent(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}splice(t,e,n){let r,i;try{let h=a.__wbindgen_add_to_stack_pointer(-16),p=q(n,a.__wbindgen_malloc,a.__wbindgen_realloc),m=M;a.lorotext_splice(h,this.__wbg_ptr,t,e,p,m);var o=u().getInt32(h+0,!0),s=u().getInt32(h+4,!0),l=u().getInt32(h+8,!0),c=u().getInt32(h+12,!0),d=o,f=s;if(c)throw d=0,f=0,_(l);return r=d,i=f,it(d,f)}finally{a.__wbindgen_add_to_stack_pointer(16),a.__wbindgen_free(r,i,1)}}unmark(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(e,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.lorotext_unmark(i,this.__wbg_ptr,w(t),o,s);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}update(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.lorotext_update(i,this.__wbg_ptr,o,s,w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}charAt(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_charAt(i,this.__wbg_ptr,t);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return String.fromCodePoint(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){let t=a.lorotext_toJSON(this.__wbg_ptr);return _(t)}toDelta(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_toDelta(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getCursor(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_getCursor(o,this.__wbg_ptr,t,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return n===0?void 0:Tt.__wrap(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isDeleted(){return a.lorotext_isDeleted(this.__wbg_ptr)!==0}subscribe(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_subscribe(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toString(){let t,e;try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_toString(i,this.__wbg_ptr);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);return t=n,e=r,it(n,r)}finally{a.__wbindgen_add_to_stack_pointer(16),a.__wbindgen_free(t,e,1)}}toContainerTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_toContainerTree(i,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var di=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_lorotree_free(t>>>0,1));class me{static __wrap(t){t=t>>>0;let e=Object.create(me.prototype);return e.__wbg_ptr=t,di.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,di.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_lorotree_free(t,0)}createNode(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_createNode(o,this.__wbg_ptr,Nt(t),K(e)?4294967297:e>>>0);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return Zt.__wrap(n)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}isAttached(){return a.lorotree_isAttached(this.__wbg_ptr)!==0}getAttached(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_getAttached(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getNodeByID(t){try{let e=a.lorotree_getNodeByID(this.__wbg_ptr,Nt(t));return e===0?void 0:Zt.__wrap(e)}finally{tt[mt++]=void 0}}isNodeDeleted(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_isNodeDeleted(i,this.__wbg_ptr,Nt(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return e!==0}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}getShallowValue(){let t=a.lorotree_getShallowValue(this.__wbg_ptr);return _(t)}getDeepValueWithID(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_getDeepValueWithID(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}enableFractionalIndex(t){a.lorotree_enableFractionalIndex(this.__wbg_ptr,t)}disableFractionalIndex(){a.lorotree_disableFractionalIndex(this.__wbg_ptr)}isFractionalIndexEnabled(){return a.lorotree_isFractionalIndexEnabled(this.__wbg_ptr)!==0}get id(){let t=a.lorotree_id(this.__wbg_ptr);return _(t)}move(t,e,n){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_move(o,this.__wbg_ptr,Nt(t),Nt(e),K(n)?4294967297:n>>>0);var r=u().getInt32(o+0,!0),i=u().getInt32(o+4,!0);if(i)throw _(r)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0,tt[mt++]=void 0}}constructor(){let t=a.lorotree_new();return this.__wbg_ptr=t>>>0,di.register(this,this.__wbg_ptr,this),this}kind(){let t=a.lorotree_kind(this.__wbg_ptr);return _(t)}nodes(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_nodes(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),n}finally{a.__wbindgen_add_to_stack_pointer(16)}}roots(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_roots(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),n}finally{a.__wbindgen_add_to_stack_pointer(16)}}delete(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_delete(r,this.__wbg_ptr,Nt(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}parent(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_parent(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){let t=a.lorotree_toJSON(this.__wbg_ptr);return _(t)}has(t){try{return a.lorotree_has(this.__wbg_ptr,Nt(t))!==0}finally{tt[mt++]=void 0}}toArray(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_toArray(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getNodes(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_getNodes(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isDeleted(){return a.lorotree_isDeleted(this.__wbg_ptr)!==0}subscribe(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_subscribe(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toContainerTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_toContainerTree(i,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var Ko=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_lorotreenode_free(t>>>0,1));class Zt{static __wrap(t){t=t>>>0;let e=Object.create(Zt.prototype);return e.__wbg_ptr=t,Ko.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Ko.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_lorotreenode_free(t,0)}__getClassname(){let t,e;try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode___getClassname(i,this.__wbg_ptr);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);return t=n,e=r,it(n,r)}finally{a.__wbindgen_add_to_stack_pointer(16),a.__wbindgen_free(t,e,1)}}creationId(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_creationId(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isDeleted(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_isDeleted(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return t!==0}finally{a.__wbindgen_add_to_stack_pointer(16)}}moveBefore(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);en(t,Zt),a.lorotreenode_moveBefore(r,this.__wbg_ptr,t.__wbg_ptr);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}createNode(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_createNode(i,this.__wbg_ptr,K(t)?4294967297:t>>>0);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Zt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getLastMoveId(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_getLastMoveId(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_toJSON(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}fractionalIndex(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_fractionalIndex(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get id(){let t=a.lorotreenode_id(this.__wbg_ptr);return _(t)}move(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_move(i,this.__wbg_ptr,Nt(t),K(e)?4294967297:e>>>0);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}get data(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_data(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return St.__wrap(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}index(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_index(r,this.__wbg_ptr);var t=u().getFloat64(r+0,!0),e=u().getInt32(r+8,!0),n=u().getInt32(r+12,!0);if(n)throw _(e);return t===4294967297?void 0:t}finally{a.__wbindgen_add_to_stack_pointer(16)}}parent(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_parent(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return t===0?void 0:Zt.__wrap(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}creator(){let t=a.lorotreenode_creator(this.__wbg_ptr);return _(t)}children(){let t=a.lorotreenode_children(this.__wbg_ptr);return _(t)}moveAfter(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);en(t,Zt),a.lorotreenode_moveAfter(r,this.__wbg_ptr,t.__wbg_ptr);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var Yo=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_undomanager_free(t>>>0,1));class nn{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Yo.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_undomanager_free(t,0)}groupStart(){try{let n=a.__wbindgen_add_to_stack_pointer(-16);a.undomanager_groupStart(n,this.__wbg_ptr);var t=u().getInt32(n+0,!0),e=u().getInt32(n+4,!0);if(e)throw _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}topRedoValue(){let t=a.undomanager_topRedoValue(this.__wbg_ptr);return _(t)}topUndoValue(){let t=a.undomanager_topUndoValue(this.__wbg_ptr);return _(t)}setMaxUndoSteps(t){a.undomanager_setMaxUndoSteps(this.__wbg_ptr,t)}setMergeInterval(t){a.undomanager_setMergeInterval(this.__wbg_ptr,t)}addExcludeOriginPrefix(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M;a.undomanager_addExcludeOriginPrefix(this.__wbg_ptr,e,n)}constructor(t,e){en(t,Pt);let n=a.undomanager_new(t.__wbg_ptr,w(e));return this.__wbg_ptr=n>>>0,Yo.register(this,this.__wbg_ptr,this),this}peer(){let t=a.undomanager_peer(this.__wbg_ptr);return _(t)}redo(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.undomanager_redo(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return t!==0}finally{a.__wbindgen_add_to_stack_pointer(16)}}undo(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.undomanager_undo(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return t!==0}finally{a.__wbindgen_add_to_stack_pointer(16)}}clear(){a.undomanager_clear(this.__wbg_ptr)}pause(){a.undomanager_pause(this.__wbg_ptr)}resume(){a.undomanager_resume(this.__wbg_ptr)}canRedo(){return a.undomanager_canRedo(this.__wbg_ptr)!==0}canUndo(){return a.undomanager_canUndo(this.__wbg_ptr)!==0}groupEnd(){a.undomanager_groupEnd(this.__wbg_ptr)}isPaused(){return a.undomanager_isPaused(this.__wbg_ptr)!==0}setOnPop(t){a.undomanager_setOnPop(this.__wbg_ptr,w(t))}clearRedo(){a.undomanager_clearRedo(this.__wbg_ptr)}clearUndo(){a.undomanager_clearUndo(this.__wbg_ptr)}setOnPush(t){a.undomanager_setOnPush(this.__wbg_ptr,w(t))}}var ui=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_versionvector_free(t>>>0,1));class Dt{static __wrap(t){t=t>>>0;let e=Object.create(Dt.prototype);return e.__wbg_ptr=t,ui.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,ui.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_versionvector_free(t,0)}get(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.versionvector_get(i,this.__wbg_ptr,w(t));var e=u().getFloat64(i+0,!0),n=u().getInt32(i+8,!0),r=u().getInt32(i+12,!0);if(r)throw _(n);return e===4294967297?void 0:e}finally{a.__wbindgen_add_to_stack_pointer(16)}}constructor(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.versionvector_new(i,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return this.__wbg_ptr=e>>>0,ui.register(this,this.__wbg_ptr,this),this}finally{a.__wbindgen_add_to_stack_pointer(16)}}static decode(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Nn(t,a.__wbindgen_malloc),s=M;a.versionvector_decode(i,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Dt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}encode(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.versionvector_encode(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=Te(t,e).slice();return a.__wbindgen_free(t,e*1,1),n}finally{a.__wbindgen_add_to_stack_pointer(16)}}length(){return a.versionvector_length(this.__wbg_ptr)>>>0}remove(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.versionvector_remove(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}setEnd(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.versionvector_setEnd(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}compare(t){en(t,Dt);let e=a.versionvector_compare(this.__wbg_ptr,t.__wbg_ptr);return e===4294967297?void 0:e}setLast(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.versionvector_setLast(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){let t=a.versionvector_toJSON(this.__wbg_ptr);return _(t)}static parseJSON(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.versionvector_parseJSON(i,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Dt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}async function Sc(t,e){if(typeof Response==="function"&&t instanceof Response){if(typeof WebAssembly.instantiateStreaming==="function")try{return await WebAssembly.instantiateStreaming(t,e)}catch(r){if(t.headers.get("Content-Type")!="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",r);else throw r}let n=await t.arrayBuffer();return await WebAssembly.instantiate(n,e)}else{let n=await WebAssembly.instantiate(t,e);if(n instanceof WebAssembly.Instance)return{instance:n,module:t};else return n}}function Cc(){let t={};return t.wbg={},t.wbg.__wbg_String_8f0eb39a4a4c2f66=function(e,n){let r=String(x(n)),i=q(r,a.__wbindgen_malloc,a.__wbindgen_realloc),o=M;u().setInt32(e+4,o,!0),u().setInt32(e+0,i,!0)},t.wbg.__wbg_apply_36be6a55257c99bf=function(){return gt(function(e,n,r){let i=x(e).apply(x(n),x(r));return w(i)},arguments)},t.wbg.__wbg_apply_eb9e9b97497f91e4=function(){return gt(function(e,n,r){let i=Reflect.apply(x(e),x(n),x(r));return w(i)},arguments)},t.wbg.__wbg_buffer_609cc3eee51ed158=function(e){let n=x(e).buffer;return w(n)},t.wbg.__wbg_call_672a4d21634d4a24=function(){return gt(function(e,n){let r=x(e).call(x(n));return w(r)},arguments)},t.wbg.__wbg_call_7cccdd69e0791ae2=function(){return gt(function(e,n,r){let i=x(e).call(x(n),x(r));return w(i)},arguments)},t.wbg.__wbg_call_833bed5770ea2041=function(){return gt(function(e,n,r,i){let o=x(e).call(x(n),x(r),x(i));return w(o)},arguments)},t.wbg.__wbg_call_b8adc8b1d0a0d8eb=function(){return gt(function(e,n,r,i,o){let s=x(e).call(x(n),x(r),x(i),x(o));return w(s)},arguments)},t.wbg.__wbg_changemodifier_new=function(e){let n=tn.__wrap(e);return w(n)},t.wbg.__wbg_crypto_574e78ad8b13b65f=function(e){let n=x(e).crypto;return w(n)},t.wbg.__wbg_cursor_new=function(e){let n=Tt.__wrap(e);return w(n)},t.wbg.__wbg_done_769e5ede4b31c67b=function(e){return x(e).done},t.wbg.__wbg_entries_3265d4158b33e5dc=function(e){let n=Object.entries(x(e));return w(n)},t.wbg.__wbg_entries_c8a90a7ed73e84ce=function(e){let n=x(e).entries();return w(n)},t.wbg.__wbg_error_428bae4e36b351e3=function(e,n){console.error(it(e,n))},t.wbg.__wbg_from_2a5d3e218e67aa85=function(e){let n=Array.from(x(e));return w(n)},t.wbg.__wbg_getOwnPropertySymbols_97eebed6fe6e08be=function(e){let n=Object.getOwnPropertySymbols(x(e));return w(n)},t.wbg.__wbg_getRandomValues_b8f5dbd5f3995a9e=function(){return gt(function(e,n){x(e).getRandomValues(x(n))},arguments)},t.wbg.__wbg_get_67b2ba62fc30de12=function(){return gt(function(e,n){let r=Reflect.get(x(e),x(n));return w(r)},arguments)},t.wbg.__wbg_get_b9b93047fe3cf45b=function(e,n){let r=x(e)[n>>>0];return w(r)},t.wbg.__wbg_getindex_5b00c274b05714aa=function(e,n){return x(e)[n>>>0]},t.wbg.__wbg_getwithrefkey_1dc361bd10053bfe=function(e,n){let r=x(e)[x(n)];return w(r)},t.wbg.__wbg_instanceof_ArrayBuffer_e14585432e3737fc=function(e){let n;try{n=x(e)instanceof ArrayBuffer}catch(i){n=!1}return n},t.wbg.__wbg_instanceof_Map_f3469ce2244d2430=function(e){let n;try{n=x(e)instanceof Map}catch(i){n=!1}return n},t.wbg.__wbg_instanceof_Object_7f2dcef8f78644a4=function(e){let n;try{n=x(e)instanceof Object}catch(i){n=!1}return n},t.wbg.__wbg_instanceof_Uint8Array_17156bcf118086a9=function(e){let n;try{n=x(e)instanceof Uint8Array}catch(i){n=!1}return n},t.wbg.__wbg_isArray_a1eab7e0d067391b=function(e){return Array.isArray(x(e))},t.wbg.__wbg_isSafeInteger_343e2beeeece1bb0=function(e){return Number.isSafeInteger(x(e))},t.wbg.__wbg_iterator_9a24c88df860dc65=function(){return w(Symbol.iterator)},t.wbg.__wbg_length_a446193dc22c12f8=function(e){return x(e).length},t.wbg.__wbg_length_e2d2a49132c1b256=function(e){return x(e).length},t.wbg.__wbg_log_0cc1b7768397bcfe=function(e,n,r,i,o,s,l,c){let d,f;try{d=e,f=n,console.log(it(e,n),it(r,i),it(o,s),it(l,c))}finally{a.__wbindgen_free(d,f,1)}},t.wbg.__wbg_log_882f657276590a29=function(e,n){console.log(it(e,n))},t.wbg.__wbg_log_cb9e190acc5753fb=function(e,n){let r,i;try{r=e,i=n,console.log(it(e,n))}finally{a.__wbindgen_free(r,i,1)}},t.wbg.__wbg_lorocounter_new=function(e){let n=Re.__wrap(e);return w(n)},t.wbg.__wbg_lorolist_new=function(e){let n=ee.__wrap(e);return w(n)},t.wbg.__wbg_loromap_new=function(e){let n=St.__wrap(e);return w(n)},t.wbg.__wbg_loromovablelist_new=function(e){let n=Le.__wrap(e);return w(n)},t.wbg.__wbg_lorotext_new=function(e){let n=Rt.__wrap(e);return w(n)},t.wbg.__wbg_lorotree_new=function(e){let n=me.__wrap(e);return w(n)},t.wbg.__wbg_lorotreenode_new=function(e){let n=Zt.__wrap(e);return w(n)},t.wbg.__wbg_mark_7438147ce31e9d4b=function(e,n){performance.mark(it(e,n))},t.wbg.__wbg_measure_fb7825c11612c823=function(){return gt(function(e,n,r,i){let o,s,l,c;try{o=e,s=n,l=r,c=i,performance.measure(it(e,n),it(r,i))}finally{a.__wbindgen_free(o,s,1),a.__wbindgen_free(l,c,1)}},arguments)},t.wbg.__wbg_msCrypto_a61aeb35a24c1329=function(e){let n=x(e).msCrypto;return w(n)},t.wbg.__wbg_new_405e22f390576ce2=function(){return w({})},t.wbg.__wbg_new_5e0be73521bc8c17=function(){return w(new Map)},t.wbg.__wbg_new_78feb108b6472713=function(){return w([])},t.wbg.__wbg_new_a12002a7f91c75be=function(e){let n=new Uint8Array(x(e));return w(n)},t.wbg.__wbg_new_c68d7209be747379=function(e,n){let r=Error(it(e,n));return w(r)},t.wbg.__wbg_newnoargs_105ed471475aaf50=function(e,n){let r=Function(it(e,n));return w(r)},t.wbg.__wbg_newwithbyteoffsetandlength_d97e637ebe145a9a=function(e,n,r){let i=new Uint8Array(x(e),n>>>0,r>>>0);return w(i)},t.wbg.__wbg_newwithlength_a381634e90c276d4=function(e){let n=new Uint8Array(e>>>0);return w(n)},t.wbg.__wbg_newwithlength_c4c419ef0bc8a1f8=function(e){let n=Array(e>>>0);return w(n)},t.wbg.__wbg_next_25feadfc0913fea9=function(e){let n=x(e).next;return w(n)},t.wbg.__wbg_next_6574e1a8a62d1055=function(){return gt(function(e){let n=x(e).next();return w(n)},arguments)},t.wbg.__wbg_node_905d3e251edff8a2=function(e){let n=x(e).node;return w(n)},t.wbg.__wbg_now_2b509d5c9d429404=function(){return Date.now()},t.wbg.__wbg_ownKeys_3930041068756f1f=function(){return gt(function(e){let n=Reflect.ownKeys(x(e));return w(n)},arguments)},t.wbg.__wbg_process_dc0fbacc7c1c06f7=function(e){let n=x(e).process;return w(n)},t.wbg.__wbg_push_737cfc8c1432c2c6=function(e,n){return x(e).push(x(n))},t.wbg.__wbg_randomFillSync_ac0988aba3254290=function(){return gt(function(e,n){x(e).randomFillSync(_(n))},arguments)},t.wbg.__wbg_require_60cc747a6bc5215a=function(){return gt(function(){let e=Nc.require;return w(e)},arguments)},t.wbg.__wbg_resolve_4851785c9c5f573d=function(e){let n=Promise.resolve(x(e));return w(n)},t.wbg.__wbg_set_37837023f3d740e8=function(e,n,r){x(e)[n>>>0]=_(r)},t.wbg.__wbg_set_3f1d0b984ed272ed=function(e,n,r){x(e)[_(n)]=_(r)},t.wbg.__wbg_set_65595bdd868b3009=function(e,n,r){x(e).set(x(n),r>>>0)},t.wbg.__wbg_set_8fc6bf8a5b1071d1=function(e,n,r){let i=x(e).set(x(n),x(r));return w(i)},t.wbg.__wbg_set_bb8cecf6a62b9f46=function(){return gt(function(e,n,r){return Reflect.set(x(e),x(n),x(r))},arguments)},t.wbg.__wbg_stateBinary_bcc49261f5205b9f=function(e,n){let r=Vo(Te(e,n));return w(r)},t.wbg.__wbg_stateCid_ddf7fe40691e2c8f=function(e,n,r){let i=Bo(x(e),n,r);return w(i)},t.wbg.__wbg_stateContainer_8b73508686ecac7f=function(e,n,r){let i=Po(e,x(n),_(r));return w(i)},t.wbg.__wbg_stateIndex_985e23155ddc5679=function(){return gt(function(e,n,r){Wo(x(e),n>>>0,x(r))},arguments)},t.wbg.__wbg_stateOptions_234376ac96321e68=function(){return gt(function(e,n){let r=Ro(_(e),n!==0);return w(r)},arguments)},t.wbg.__wbg_stateRootCid_92a320b321ddff0a=function(e,n,r){let i=zo(it(e,n),r);return w(i)},t.wbg.__wbg_stateSet_9c75457bd566f749=function(){return gt(function(e,n,r){qo(x(e),x(n),x(r))},arguments)},t.wbg.__wbg_stateSlice_4573448d6dfd609f=function(e,n,r){let i=Lo(_(e),n>>>0,r>>>0);return w(i)},t.wbg.__wbg_stateValue_32a9721f28b53795=function(e){let n=Fo(_(e));return w(n)},t.wbg.__wbg_static_accessor_GLOBAL_88a902d13a557d07=function(){let e=typeof global>"u"?null:global;return K(e)?0:w(e)},t.wbg.__wbg_static_accessor_GLOBAL_THIS_56578be7e9f832b0=function(){let e=typeof globalThis>"u"?null:globalThis;return K(e)?0:w(e)},t.wbg.__wbg_static_accessor_SELF_37c5d418e4bf5819=function(){let e=typeof self>"u"?null:self;return K(e)?0:w(e)},t.wbg.__wbg_static_accessor_WINDOW_5de37043a91a9c40=function(){let e=typeof window>"u"?null:window;return K(e)?0:w(e)},t.wbg.__wbg_subarray_aa9065fa9dc5df96=function(e,n,r){let i=x(e).subarray(n>>>0,r>>>0);return w(i)},t.wbg.__wbg_then_44b73946d2fb3e7d=function(e,n){let r=x(e).then(x(n));return w(r)},t.wbg.__wbg_value_cd1ffa7b1ab794f1=function(e){let n=x(e).value;return w(n)},t.wbg.__wbg_versions_c01dfd4722a88165=function(e){let n=x(e).versions;return w(n)},t.wbg.__wbg_versionvector_new=function(e){let n=Dt.__wrap(e);return w(n)},t.wbg.__wbg_warn_5d1fd3858772ca54=function(e,n){console.warn(it(e,n))},t.wbg.__wbindgen_as_number=function(e){return+x(e)},t.wbg.__wbindgen_bigint_from_i64=function(e){return w(e)},t.wbg.__wbindgen_bigint_from_u64=function(e){let n=BigInt.asUintN(64,e);return w(n)},t.wbg.__wbindgen_bigint_get_as_i64=function(e,n){let r=x(n),i=typeof r==="bigint"?r:void 0;u().setBigInt64(e+8,K(i)?BigInt(0):i,!0),u().setInt32(e+0,!K(i),!0)},t.wbg.__wbindgen_boolean_get=function(e){let n=x(e);return typeof n==="boolean"?n?1:0:2},t.wbg.__wbindgen_cb_drop=function(e){let n=_(e).original;if(n.cnt--==1)return n.a=0,!0;return!1},t.wbg.__wbindgen_closure_wrapper295=function(e,n,r){let i=$o(e,n,16,Ic);return w(i)},t.wbg.__wbindgen_closure_wrapper551=function(e,n,r){let i=$o(e,n,16,vc);return w(i)},t.wbg.__wbindgen_debug_string=function(e,n){let r=hi(x(n)),i=q(r,a.__wbindgen_malloc,a.__wbindgen_realloc),o=M;u().setInt32(e+4,o,!0),u().setInt32(e+0,i,!0)},t.wbg.__wbindgen_error_new=function(e,n){let r=Error(it(e,n));return w(r)},t.wbg.__wbindgen_in=function(e,n){return x(e)in x(n)},t.wbg.__wbindgen_is_array=function(e){return Array.isArray(x(e))},t.wbg.__wbindgen_is_bigint=function(e){return typeof x(e)==="bigint"},t.wbg.__wbindgen_is_function=function(e){return typeof x(e)==="function"},t.wbg.__wbindgen_is_null=function(e){return x(e)===null},t.wbg.__wbindgen_is_object=function(e){let n=x(e);return typeof n==="object"&&n!==null},t.wbg.__wbindgen_is_string=function(e){return typeof x(e)==="string"},t.wbg.__wbindgen_is_undefined=function(e){return x(e)===void 0},t.wbg.__wbindgen_jsval_eq=function(e,n){return x(e)===x(n)},t.wbg.__wbindgen_jsval_loose_eq=function(e,n){return x(e)==x(n)},t.wbg.__wbindgen_memory=function(){let e=a.memory;return w(e)},t.wbg.__wbindgen_number_get=function(e,n){let r=x(n),i=typeof r==="number"?r:void 0;u().setFloat64(e+8,K(i)?0:i,!0),u().setInt32(e+0,!K(i),!0)},t.wbg.__wbindgen_number_new=function(e){return w(e)},t.wbg.__wbindgen_object_clone_ref=function(e){let n=x(e);return w(n)},t.wbg.__wbindgen_object_drop_ref=function(e){_(e)},t.wbg.__wbindgen_rethrow=function(e){throw _(e)},t.wbg.__wbindgen_string_get=function(e,n){let r=x(n),i=typeof r==="string"?r:void 0;var o=K(i)?0:q(i,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;u().setInt32(e+4,s,!0),u().setInt32(e+0,o,!0)},t.wbg.__wbindgen_string_new=function(e,n){let r=it(e,n);return w(r)},t.wbg.__wbindgen_throw=function(e,n){throw Error(it(e,n))},t.wbg.__wbindgen_typeof=function(e){let n=typeof x(e);return w(n)},t}function Oc(t,e){}function Mc(t,e){return a=t.exports,Go.__wbindgen_wasm_module=e,De=null,An=null,a.__wbindgen_start(),a}async function Go(t){if(a!==void 0)return a;if(typeof t<"u")if(Object.getPrototypeOf(t)===Object.prototype)({module_or_path:t}=t);else console.warn("using deprecated parameters for the initialization function; pass a single object instead");if(typeof t>"u")t=new URL("loro_wasm_bg.wasm",import.meta.url);let e=Cc();if(typeof t==="string"||typeof Request==="function"&&t instanceof Request||typeof URL==="function"&&t instanceof URL)t=fetch(t);Oc(e);let{instance:n,module:r}=await Sc(await t,e);return Mc(n,r)}var _i=Go,fi=Symbol("loroContainerId");function Ac(t){let e=t.prototype,n=Object.getOwnPropertyDescriptor(e,"id"),r=n&&n.get,i=Object.getOwnPropertyDescriptor(e,"__destroy_into_raw"),o=i&&i.value;if(!r||!i||!o)throw Error("Unexpected wasm-bindgen container wrapper shape");Object.defineProperty(e,"id",{...n,get(){if(this.__wbg_ptr===0)return r.call(this);let s=this[fi];if(s!==void 0)return s;let l=r.call(this);try{Object.defineProperty(this,fi,{configurable:!0,value:l})}catch{}return l}}),Object.defineProperty(e,"__destroy_into_raw",{...i,value(){try{delete this[fi]}catch{}return o.call(this)}})}function Ec(t){let e=t.prototype,n=Object.getOwnPropertyDescriptor(e,"kind"),r=n&&n.value;if(typeof r!=="function")throw Error("Unexpected wasm-bindgen container wrapper shape");let i;Object.defineProperty(e,"kind",{...n,value(){if(this.__wbg_ptr===0)return r.call(this);if(i===void 0)i=r.call(this);return i}})}for(let t of[St,Rt,ee,me,Le,Re])Ac(t),Ec(t);var Tc=["Map","Text","List","Tree","MovableList","Counter"];function Rc(t){return pi(t)}function ie(t){if(typeof t!=="object"||t==null)return!1;let e=Object.getPrototypeOf(t);if(e==null||typeof e!=="object"||typeof e.kind!=="function")return!1;return Tc.includes(t.kind())}class gi{constructor(t=30000){this.inner=new Dn(t),this.timeout=t}apply(t){this.inner.apply(t),this.startTimerIfNotEmpty()}set(t,e){this.inner.set(t,e),this.startTimerIfNotEmpty()}delete(t){this.inner.delete(t)}get(t){return this.inner.get(t)}getAllStates(){return this.inner.getAllStates()}encode(t){return this.inner.encode(t)}encodeAll(){return this.inner.encodeAll()}keys(){return this.inner.keys()}destroy(){clearInterval(this.timer)}subscribe(t){return this.inner.subscribe(t)}subscribeLocalUpdates(t){return this.inner.subscribeLocalUpdates(t)}startTimerIfNotEmpty(){if(this.inner.isEmpty()||this.timer!=null)return;this.timer=setInterval(()=>{if(this.inner.removeOutdated(),this.inner.isEmpty())clearInterval(this.timer),this.timer=void 0},this.timeout/2)}}Pt.prototype.toJsonWithReplacer=function(t){let e=new Set,n=this,r=(s,l)=>{if(typeof l==="string"){if(Rc(l)&&!e.has(l)){e.add(l);let d=n.getContainerById(l);if(d==null)throw Error(`ContainerID not found: ${l}`);let f=t(s,d);if(f===d){let h=d.getShallowValue();if(typeof h==="object")return i(h);return h}if(ie(f))throw Error("Using new container is not allowed in toJsonWithReplacer");if(typeof f==="object"&&f!=null)return i(f);return f}}if(typeof l==="object"&&l!=null)return i(l);let c=t(s,l);if(ie(c))throw Error("Using new container is not allowed in toJsonWithReplacer");return c},i=(s)=>{if(Array.isArray(s))return s.map((c,d)=>r(d,c)).filter((c)=>c!==void 0);let l={};for(let[c,d]of Object.entries(s)){let f=r(c,d);if(f!==void 0)l[c]=f}return l},o=n.getShallowValue();return i(o)};var Qo=Symbol("loro.callPendingEventsWrapped");function Lc(t,e){let n=Object.getOwnPropertyDescriptor(t,e);if(!n||typeof n.value!=="function")return;let r=n.value;if(r[Qo])return;let i=function(...o){let s;try{return s=r.apply(this,o),s}finally{if(s&&typeof s.then==="function")s.finally(()=>{fr()});else fr()}};i[Qo]=!0,Object.defineProperty(t,e,{...n,value:i})}function mi(t,e){for(let n of e)Lc(t,n)}mi(Pt.prototype,["setDetachedEditing","attach","detach","fork","forkAt","checkoutToLatest","checkout","commit","getCursorPos","revertTo","export","exportJsonUpdates","exportJsonInIdSpan","importJsonUpdates","import","importUpdateBatch","importBatch","travelChangeAncestors","getChangedContainersIn","diff","applyDiff","setPeerId"]);mi(Dn.prototype,["set","delete","apply","removeOutdated"]);mi(nn.prototype,["undo","redo"]);function kt(t){this.content=t}kt.prototype={constructor:kt,find:function(t){for(var e=0;e>1}};kt.from=function(t){if(t instanceof kt)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new kt(e)};var bi=kt;function ds(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let i=t.child(r),o=e.child(r);if(i==o){n+=i.nodeSize;continue}if(!i.sameMarkup(o))return n;if(i.isText&&i.text!=o.text){let s=i.text,l=o.text,c=0;for(;s[c]==l[c];c++)n++;if(c&&c0&&p>0&&d[h-1]==f[p-1])h--,p--,n--,r--;if(h&&p&&h=56320&&t<57344}function hs(t){return t>=55296&&t<56320}class k{constructor(t,e){if(this.content=t,this.size=e||0,e==null)for(let n=0;nt&&n(l,r+s,i||null,o)!==!1&&l.content.size){let d=s+1;l.nodesBetween(Math.max(0,t-d),Math.min(l.content.size,e-d),n,r+d)}s=c}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,e,n,r){let i="",o=!0;return this.nodesBetween(t,e,(s,l)=>{let c=s.isText?s.text.slice(Math.max(t,l)-l,e-l):!s.isLeaf?"":r?typeof r==="function"?r(s):r:s.type.spec.leafText?s.type.spec.leafText(s):"";if(s.isBlock&&(s.isLeaf&&c||s.isTextblock)&&n)if(o)o=!1;else i+=n;i+=c},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let e=this.lastChild,n=t.firstChild,r=this.content.slice(),i=0;if(e.isText&&e.sameMarkup(n))r[r.length-1]=e.withText(e.text+n.text),i=1;for(;it)for(let i=0,o=0;ot){if(oe)if(s.isText)s=s.cut(Math.max(0,t-o),Math.min(s.text.length,e-o));else s=s.cut(Math.max(0,t-o-1),Math.min(s.content.size,e-o-1));n.push(s),r+=s.nodeSize}o=l}return new k(n,r)}cutByIndex(t,e){if(t==e)return k.empty;if(t==0&&e==this.content.length)return this;return new k(this.content.slice(t,e))}replaceChild(t,e){let n=this.content[t];if(n==e)return this;let r=this.content.slice(),i=this.size+e.nodeSize-n.nodeSize;return r[t]=e,new k(r,i)}addToStart(t){return new k([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new k(this.content.concat(t),this.size+t.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let e=0;ethis.size||t<0)throw RangeError(`Position ${t} outside of fragment (${this})`);for(let e=0,n=0;;e++){let r=this.child(e),i=n+r.nodeSize;if(i>=t){if(i==t)return hr(e+1,i);return hr(e,n)}n=i}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map((t)=>t.toJSON()):null}static fromJSON(t,e){if(!e)return k.empty;if(!Array.isArray(e))throw RangeError("Invalid input for Fragment.fromJSON");return k.fromArray(e.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return k.empty;let e,n=0;for(let r=0;rthis.type.rank){if(!e)e=t.slice(0,r);e.push(this),n=!0}if(e)e.push(i)}}if(!e)e=t.slice();if(!n)e.push(this);return e}removeFromSet(t){for(let e=0;en.type.rank-r.type.rank),e}}J.none=[];class ze extends Error{}class I{constructor(t,e,n){this.content=t,this.openStart=e,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,e){let n=_s(this.content,t+this.openStart,e,this.openStart+1,this.openEnd+1);return n&&new I(n,this.openStart,this.openEnd)}removeBetween(t,e){return new I(ps(this.content,t+this.openStart,e+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};if(this.openStart>0)t.openStart=this.openStart;if(this.openEnd>0)t.openEnd=this.openEnd;return t}static fromJSON(t,e){if(!e)return I.empty;let n=e.openStart||0,r=e.openEnd||0;if(typeof n!="number"||typeof r!="number")throw RangeError("Invalid input for Slice.fromJSON");return new I(k.fromJSON(t,e.content),n,r)}static maxOpen(t,e=!0){let n=0,r=0;for(let i=t.firstChild;i&&!i.isLeaf&&(e||!i.type.spec.isolating);i=i.firstChild)n++;for(let i=t.lastChild;i&&!i.isLeaf&&(e||!i.type.spec.isolating);i=i.lastChild)r++;return new I(t,n,r)}}I.empty=new I(k.empty,0,0);function ps(t,e,n){let{index:r,offset:i}=t.findIndex(e),o=t.maybeChild(r),{index:s,offset:l}=t.findIndex(n);if(i==e||o.isText){if(l!=n&&!t.child(s).isText)throw RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=s)throw RangeError("Removing non-flat range");return t.replaceChild(r,o.copy(ps(o.content,e-i-1,n-i-1)))}function _s(t,e,n,r,i,o){let{index:s,offset:l}=t.findIndex(e),c=t.maybeChild(s);if(l==e||c.isText){if(o&&r<=0&&i<=0&&!o.canReplace(s,s,n))return null;return t.cut(0,e).append(n).append(t.cut(e))}let d=_s(c.content,e-l-1,n,s==0?r-1:0,s==t.childCount-1?i-1:0,c);return d&&t.replaceChild(s,c.copy(d))}function Pc(t,e,n){if(n.openStart>t.depth)throw new ze("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new ze("Inconsistent open depths");return gs(t,e,n,0)}function gs(t,e,n,r){let i=t.index(r),o=t.node(r);if(i==e.index(r)&&r=0&&t.isText&&t.sameMarkup(e[n]))e[n]=t.withText(e[n].text+t.text);else e.push(t)}function Rn(t,e,n,r){let i=(e||t).node(n),o=0,s=e?e.index(n):i.childCount;if(t){if(o=t.index(n),t.depth>n)o++;else if(t.textOffset)Pe(t.nodeAfter,r),o++}for(let l=o;li&&yi(t,e,i+1),s=r.depth>i&&yi(n,r,i+1),l=[];if(Rn(null,t,i,l),o&&s&&e.index(i)==n.index(i))ms(o,s),Pe(Be(o,bs(t,e,n,r,i+1)),l);else{if(o)Pe(Be(o,mr(t,e,i+1)),l);if(Rn(e,n,i,l),s)Pe(Be(s,mr(n,r,i+1)),l)}return Rn(r,null,i,l),new k(l)}function mr(t,e,n){let r=[];if(Rn(null,t,n,r),t.depth>n){let i=yi(t,e,n+1);Pe(Be(i,mr(t,e,n+1)),r)}return Rn(e,null,n,r),new k(r)}function Bc(t,e){let n=e.depth-t.openStart,i=e.node(n).copy(t.content);for(let o=n-1;o>=0;o--)i=e.node(o).copy(k.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class Pn{constructor(t,e,n){this.pos=t,this.path=e,this.parentOffset=n,this.depth=e.length/3-1}resolveDepth(t){if(t==null)return this.depth;if(t<0)return this.depth+t;return t}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(t){return this.path[this.resolveDepth(t)*3]}index(t){return this.path[this.resolveDepth(t)*3+1]}indexAfter(t){return t=this.resolveDepth(t),this.index(t)+(t==this.depth&&!this.textOffset?0:1)}start(t){return t=this.resolveDepth(t),t==0?0:this.path[t*3-1]+1}end(t){return t=this.resolveDepth(t),this.start(t)+this.node(t).content.size}before(t){if(t=this.resolveDepth(t),!t)throw RangeError("There is no position before the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]}after(t){if(t=this.resolveDepth(t),!t)throw RangeError("There is no position after the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]+this.path[t*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let t=this.parent,e=this.index(this.depth);if(e==t.childCount)return null;let n=this.pos-this.path[this.path.length-1],r=t.child(e);return n?t.child(e).cut(n):r}get nodeBefore(){let t=this.index(this.depth),e=this.pos-this.path[this.path.length-1];if(e)return this.parent.child(t).cut(0,e);return t==0?null:this.parent.child(t-1)}posAtIndex(t,e){e=this.resolveDepth(e);let n=this.path[e*3],r=e==0?0:this.path[e*3-1]+1;for(let i=0;i0;e--)if(this.start(e)<=t&&this.end(e)>=t)return e;return 0}blockRange(t=this,e){if(t.pos=0;n--)if(t.pos<=this.end(n)&&(!e||e(this.node(n))))return new on(this,t,n);return null}sameParent(t){return this.pos-this.parentOffset==t.pos-t.parentOffset}max(t){return t.pos>this.pos?t:this}min(t){return t.pos=0&&e<=t.content.size))throw RangeError("Position "+e+" out of range");let n=[],r=0,i=e;for(let o=t;;){let{index:s,offset:l}=o.content.findIndex(i),c=i-l;if(n.push(o,s,r+l),!c)break;if(o=o.child(s),o.isText)break;i=c-1,r+=l+1}return new Pn(e,n,i)}static resolveCached(t,e){let n=Zo.get(t);if(n)for(let i=0;it)this.nodesBetween(t,e,(i)=>{if(n.isInSet(i.marks))r=!0;return!r});return r}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let t=this.type.name;if(this.content.size)t+="("+this.content.toStringInner()+")";return ys(this.marks,t)}contentMatchAt(t){let e=this.type.contentMatch.matchFragment(this.content,0,t);if(!e)throw Error("Called contentMatchAt on a node with invalid content");return e}canReplace(t,e,n=k.empty,r=0,i=n.childCount){let o=this.contentMatchAt(t).matchFragment(n,r,i),s=o&&o.matchFragment(this.content,e);if(!s||!s.validEnd)return!1;for(let l=r;le.type.name)}`);this.content.forEach((e)=>e.check())}toJSON(){let t={type:this.type.name};for(let e in this.attrs){t.attrs=this.attrs;break}if(this.content.size)t.content=this.content.toJSON();if(this.marks.length)t.marks=this.marks.map((e)=>e.toJSON());return t}static fromJSON(t,e){if(!e)throw RangeError("Invalid input for Node.fromJSON");let n=void 0;if(e.marks){if(!Array.isArray(e.marks))throw RangeError("Invalid mark data for Node.fromJSON");n=e.marks.map(t.markFromJSON)}if(e.type=="text"){if(typeof e.text!="string")throw RangeError("Invalid text node in JSON");return t.text(e.text,n)}let r=k.fromJSON(t,e.content);return t.nodeType(e.type).create(e.attrs,r,n)}}qt.prototype.text=void 0;class br extends qt{constructor(t,e,n,r){super(t,e,null,r);if(!n)throw RangeError("Empty text nodes are not allowed");this.text=n}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);return ys(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(t,e){return this.text.slice(t,e)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new br(this.type,this.attrs,this.text,t)}withText(t){if(t==this.text)return this;return new br(this.type,this.attrs,t,this.marks)}cut(t=0,e=this.text.length){if(t==0&&e==this.text.length)return this;return this.withText(this.text.slice(t,e))}eq(t){return this.sameMarkup(t)&&this.text==t.text}toJSON(){let t=super.toJSON();return t.text=this.text,t}}function ys(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}function ts(t,e,n,r){for(let i in e)if(!(i in t))throw RangeError(`Unsupported attribute ${i} for ${n} of type ${r}`);for(let i in t)if(t[i].validate)t[i].validate(e[i])}class Fe{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,e){let n=new ks(t,e);if(n.next==null)return Fe.empty;let r=xs(n);if(n.next)n.err("Unexpected trailing text");let i=jc(Jc(r));return Hc(i,n),i}matchType(t){for(let e=0;ec.createAndFill()));for(let c=0;c=this.next.length)throw RangeError(`There's no ${t}th edge in this content match`);return this.next[t]}toString(){let t=[];function e(n){t.push(n);for(let r=0;r{let i=r+(n.validEnd?"*":" ")+" ";for(let o=0;o"+t.indexOf(n.next[o].next);return i}).join(` +`)}}Fe.empty=new Fe(!0);class ks{constructor(t,e){if(this.string=t,this.nodeTypes=e,this.inline=null,this.pos=0,this.tokens=t.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]=="")this.tokens.pop();if(this.tokens[0]=="")this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(t){return this.next==t&&(this.pos++||!0)}err(t){throw SyntaxError(t+" (in content expression '"+this.string+"')")}}function xs(t){let e=[];do e.push(Vc(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function Vc(t){let e=[];do e.push(Wc(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function Wc(t){let e=$c(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else if(t.eat("{"))e=qc(t,e);else break;return e}function es(t){if(/\D/.test(t.next))t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function qc(t,e){let n=es(t),r=n;if(t.eat(","))if(t.next!="}")r=es(t);else r=-1;if(!t.eat("}"))t.err("Unclosed braced range");return{type:"range",min:n,max:r,expr:e}}function Uc(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let i=[];for(let o in n){let s=n[o];if(s.isInGroup(e))i.push(s)}if(i.length==0)t.err("No node type or group '"+e+"' found");return i}function $c(t){if(t.eat("(")){let e=xs(t);if(!t.eat(")"))t.err("Missing closing paren");return e}else if(!/\W/.test(t.next)){let e=Uc(t,t.next).map((n)=>{if(t.inline==null)t.inline=n.isInline;else if(t.inline!=n.isInline)t.err("Mixing inline and block content");return{type:"name",value:n}});return t.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}else t.err("Unexpected token '"+t.next+"'")}function Jc(t){let e=[[]];return i(o(t,0),n()),e;function n(){return e.push([])-1}function r(s,l,c){let d={term:c,to:l};return e[s].push(d),d}function i(s,l){s.forEach((c)=>c.to=l)}function o(s,l){if(s.type=="choice")return s.exprs.reduce((c,d)=>c.concat(o(d,l)),[]);else if(s.type=="seq")for(let c=0;;c++){let d=o(s.exprs[c],l);if(c==s.exprs.length-1)return d;i(d,l=n())}else if(s.type=="star"){let c=n();return r(l,c),i(o(s.expr,c),c),[r(c)]}else if(s.type=="plus"){let c=n();return i(o(s.expr,l),c),i(o(s.expr,c),c),[r(c)]}else if(s.type=="opt")return[r(l)].concat(o(s.expr,l));else if(s.type=="range"){let c=l;for(let d=0;d{t[s].forEach(({term:l,to:c})=>{if(!l)return;let d;for(let f=0;f{if(!d)i.push([l,d=[]]);if(d.indexOf(f)==-1)d.push(f)})})});let o=e[r.join(",")]=new Fe(r.indexOf(t.length-1)>-1);for(let s=0;s-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let t in this.attrs)if(this.attrs[t].isRequired)return!0;return!1}compatibleContent(t){return this==t||this.contentMatch.compatible(t.contentMatch)}computeAttrs(t){if(!t&&this.defaultAttrs)return this.defaultAttrs;else return Ss(this.attrs,t)}create(t=null,e,n){if(this.isText)throw Error("NodeType.create can't construct text nodes");return new qt(this,this.computeAttrs(t),k.from(e),J.setFrom(n))}createChecked(t=null,e,n){return e=k.from(e),this.checkContent(e),new qt(this,this.computeAttrs(t),e,J.setFrom(n))}createAndFill(t=null,e,n){if(t=this.computeAttrs(t),e=k.from(e),e.size){let o=this.contentMatch.fillBefore(e);if(!o)return null;e=o.append(e)}let r=this.contentMatch.matchFragment(e),i=r&&r.fillBefore(k.empty,!0);if(!i)return null;return new qt(this,t,e.append(i),J.setFrom(n))}validContent(t){let e=this.contentMatch.matchFragment(t);if(!e||!e.validEnd)return!1;for(let n=0;n-1}allowsMarks(t){if(this.markSet==null)return!0;for(let e=0;en[i]=new wr(i,e,o));let r=e.spec.topNode||"doc";if(!n[r])throw RangeError("Schema is missing its top node type ('"+r+"')");if(!n.text)throw RangeError("Every schema needs a 'text' type");for(let i in n.text.attrs)throw RangeError("The text node type should not have attributes");return n}}function Kc(t,e,n){let r=n.split("|");return(i)=>{let o=i===null?"null":typeof i;if(r.indexOf(o)<0)throw RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${o}`)}}class Os{constructor(t,e,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,"default"),this.default=n.default,this.validate=typeof n.validate=="string"?Kc(t,e,n.validate):n.validate}get isRequired(){return!this.hasDefault}}class zn{constructor(t,e,n,r){this.name=t,this.rank=e,this.schema=n,this.spec=r,this.attrs=Cs(t,r.attrs),this.excluded=null;let i=vs(this.attrs);this.instance=i?new J(this,i):null}create(t=null){if(!t&&this.instance)return this.instance;return new J(this,Ss(this.attrs,t))}static compile(t,e){let n=Object.create(null),r=0;return t.forEach((i,o)=>n[i]=new zn(i,r++,e,o)),n}removeFromSet(t){for(var e=0;e-1}}class sn{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let e=this.spec={};for(let r in t)e[r]=t[r];e.nodes=bi.from(t.nodes),e.marks=bi.from(t.marks||{}),this.nodes=wr.compile(this.spec.nodes,this),this.marks=zn.compile(this.spec.marks,this);let n=Object.create(null);for(let r in this.nodes){if(r in this.marks)throw RangeError(r+" can not be both a node and a mark");let i=this.nodes[r],o=i.spec.content||"",s=i.spec.marks;if(i.contentMatch=n[o]||(n[o]=Fe.parse(o,this.nodes)),i.inlineContent=i.contentMatch.inlineContent,i.spec.linebreakReplacement){if(this.linebreakReplacement)throw RangeError("Multiple linebreak nodes defined");if(!i.isInline||!i.isLeaf)throw RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=i}i.markSet=s=="_"?null:s?rs(this,s.split(" ")):s==""||!i.inlineContent?[]:null}for(let r in this.marks){let i=this.marks[r],o=i.spec.excludes;i.excluded=o==null?[i]:o==""?[]:rs(this,o.split(" "))}this.nodeFromJSON=(r)=>qt.fromJSON(this,r),this.markFromJSON=(r)=>J.fromJSON(this,r),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(t,e=null,n,r){if(typeof t=="string")t=this.nodeType(t);else if(!(t instanceof wr))throw RangeError("Invalid node type: "+t);else if(t.schema!=this)throw RangeError("Node type from different schema used ("+t.name+")");return t.createChecked(e,n,r)}text(t,e){let n=this.nodes.text;return new br(n,n.defaultAttrs,t,J.setFrom(e))}mark(t,e){if(typeof t=="string")t=this.marks[t];return t.create(e)}nodeType(t){let e=this.nodes[t];if(!e)throw RangeError("Unknown node type: "+t);return e}}function rs(t,e){let n=[];for(let r=0;r-1)n.push(s=c)}if(!s)throw SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}function Yc(t){return t.tag!=null}function Xc(t){return t.style!=null}class rn{constructor(t,e){this.schema=t,this.rules=e,this.tags=[],this.styles=[];let n=this.matchedStyles=[];e.forEach((r)=>{if(Yc(r))this.tags.push(r);else if(Xc(r)){let i=/[^=]*/.exec(r.style)[0];if(n.indexOf(i)<0)n.push(i);this.styles.push(r)}}),this.normalizeLists=!this.tags.some((r)=>{if(!/^(ul|ol)\b/.test(r.tag)||!r.node)return!1;let i=t.nodes[r.node];return i.contentMatch.matchType(i)})}parse(t,e={}){let n=new xi(this,e,!1);return n.addAll(t,J.none,e.from,e.to),n.finish()}parseSlice(t,e={}){let n=new xi(this,e,!0);return n.addAll(t,J.none,e.from,e.to),I.maxOpen(n.finish())}matchTag(t,e,n){for(let r=n?this.tags.indexOf(n)+1:0;rt.length&&(s.charCodeAt(t.length)!=61||s.slice(t.length+1)!=e))continue;if(o.getAttrs){let l=o.getAttrs(e);if(l===!1)continue;o.attrs=l||void 0}return o}}static schemaRules(t){let e=[];function n(r){let i=r.priority==null?50:r.priority,o=0;for(;o{if(n(o=ss(o)),!(o.mark||o.ignore||o.clearMark))o.mark=r})}for(let r in t.nodes){let i=t.nodes[r].spec.parseDOM;if(i)i.forEach((o)=>{if(n(o=ss(o)),!(o.node||o.ignore||o.mark))o.node=r})}return e}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new rn(t,rn.schemaRules(t)))}}var Ms={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Gc={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},As={ol:!0,ul:!0},Bn=1,ki=2,Ln=4;function is(t,e,n){if(e!=null)return(e?Bn:0)|(e==="full"?ki:0);return t&&t.whitespace=="pre"?Bn|ki:n&~Ln}class Tn{constructor(t,e,n,r,i,o){this.type=t,this.attrs=e,this.marks=n,this.solid=r,this.options=o,this.content=[],this.activeMarks=J.none,this.match=i||(o&Ln?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let e=this.type.contentMatch.fillBefore(k.from(t));if(e)this.match=this.type.contentMatch.matchFragment(e);else{let n=this.type.contentMatch,r;if(r=n.findWrapping(t.type))return this.match=n,r;else return null}}return this.match.findWrapping(t.type)}finish(t){if(!(this.options&Bn)){let n=this.content[this.content.length-1],r;if(n&&n.isText&&(r=/[ \t\r\n\u000c]+$/.exec(n.text))){let i=n;if(n.text.length==r[0].length)this.content.pop();else this.content[this.content.length-1]=i.withText(i.text.slice(0,i.text.length-r[0].length))}}let e=k.from(this.content);if(!t&&this.match)e=e.append(this.match.fillBefore(k.empty,!0));return this.type?this.type.create(this.attrs,e,this.marks):e}inlineContext(t){if(this.type)return this.type.inlineContent;if(this.content.length)return this.content[0].isInline;return t.parentNode&&!Ms.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class xi{constructor(t,e,n){this.parser=t,this.options=e,this.isOpen=n,this.open=0,this.localPreserveWS=!1;let r=e.topNode,i,o=is(null,e.preserveWhitespace,0)|(n?Ln:0);if(r)i=new Tn(r.type,r.attrs,J.none,!0,e.topMatch||r.type.contentMatch,o);else if(n)i=new Tn(null,null,J.none,!0,null,o);else i=new Tn(t.schema.topNodeType,null,J.none,!0,null,o);this.nodes=[i],this.find=e.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(t,e){if(t.nodeType==3)this.addTextNode(t,e);else if(t.nodeType==1)this.addElement(t,e)}addTextNode(t,e){let n=t.nodeValue,r=this.top,i=r.options&ki?"full":this.localPreserveWS||(r.options&Bn)>0,{schema:o}=this.parser;if(i==="full"||r.inlineContext(t)||/[^ \t\r\n\u000c]/.test(n)){if(!i){if(n=n.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(n)&&this.open==this.nodes.length-1){let s=r.content[r.content.length-1],l=t.previousSibling;if(!s||l&&l.nodeName=="BR"||s.isText&&/[ \t\r\n\u000c]$/.test(s.text))n=n.slice(1)}}else if(i==="full")n=n.replace(/\r\n?/g,` +`);else if(o.linebreakReplacement&&/[\r\n]/.test(n)&&this.top.findWrapping(o.linebreakReplacement.create())){let s=n.split(/\r?\n|\r/);for(let l=0;l!l.clearMark(c));else e=e.concat(this.parser.schema.marks[l.mark].create(l.attrs));if(l.consuming===!1)s=l;else break}}return e}addElementByRule(t,e,n,r){let i,o;if(e.node){if(o=this.parser.schema.nodes[e.node],!o.isLeaf){let l=this.enter(o,e.attrs||null,n,e.preserveWhitespace);if(l)i=!0,n=l}else if(!this.insertNode(o.create(e.attrs),n,t.nodeName=="BR"))this.leafFallback(t,n)}else{let l=this.parser.schema.marks[e.mark];n=n.concat(l.create(e.attrs))}let s=this.top;if(o&&o.isLeaf)this.findInside(t);else if(r)this.addElement(t,n,r);else if(e.getContent)this.findInside(t),e.getContent(t,this.parser.schema).forEach((l)=>this.insertNode(l,n,!1));else{let l=t;if(typeof e.contentElement=="string")l=t.querySelector(e.contentElement);else if(typeof e.contentElement=="function")l=e.contentElement(t);else if(e.contentElement)l=e.contentElement;this.findAround(t,l,!0),this.addAll(l,n),this.findAround(t,l,!1)}if(i&&this.sync(s))this.open--}addAll(t,e,n,r){let i=n||0;for(let o=n?t.childNodes[n]:t.firstChild,s=r==null?null:t.childNodes[r];o!=s;o=o.nextSibling,++i)this.findAtPoint(t,i),this.addDOM(o,e);this.findAtPoint(t,i)}findPlace(t,e,n){let r,i;for(let o=this.open,s=0;o>=0;o--){let l=this.nodes[o],c=l.findWrapping(t);if(c&&(!r||r.length>c.length+s)){if(r=c,i=l,!c.length)break}if(l.solid){if(n)break;s+=2}}if(!r)return null;this.sync(i);for(let o=0;o{if(o.type?o.type.allowsMarkType(c.type):ls(c.type,t))return l=c.addToSet(l),!1;return!0}),this.nodes.push(new Tn(t,e,l,r,null,s)),this.open++,n}closeExtra(t=!1){let e=this.nodes.length-1;if(e>this.open){for(;e>this.open;e--)this.nodes[e-1].content.push(this.nodes[e].finish(t));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(t){for(let e=this.open;e>=0;e--)if(this.nodes[e]==t)return this.open=e,!0;else if(this.localPreserveWS)this.nodes[e].options|=Bn;return!1}get currentPos(){this.closeExtra();let t=0;for(let e=this.open;e>=0;e--){let n=this.nodes[e].content;for(let r=n.length-1;r>=0;r--)t+=n[r].nodeSize;if(e)t++}return t}findAtPoint(t,e){if(this.find){for(let n=0;n-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let e=t.split("/"),n=this.options.context,r=!this.isOpen&&(!n||n.parent.type==this.nodes[0].type),i=-(n?n.depth+1:0)+(r?0:1),o=(s,l)=>{for(;s>=0;s--){let c=e[s];if(c==""){if(s==e.length-1||s==0)continue;for(;l>=i;l--)if(o(s-1,l))return!0;return!1}else{let d=l>0||l==0&&r?this.nodes[l].type:n&&l>=i?n.node(l-i).type:null;if(!d||d.name!=c&&!d.isInGroup(c))return!1;l--}}return!0};return o(e.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let e=t.depth;e>=0;e--){let n=t.node(e).contentMatchAt(t.indexAfter(e)).defaultType;if(n&&n.isTextblock&&n.defaultAttrs)return n}for(let e in this.parser.schema.nodes){let n=this.parser.schema.nodes[e];if(n.isTextblock&&n.defaultAttrs)return n}}}function Qc(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;if(r&&As.hasOwnProperty(r)&&n)n.appendChild(e),e=n;else if(r=="li")n=e;else if(r)n=null}}function Zc(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function ss(t){let e={};for(let n in t)e[n]=t[n];return e}function ls(t,e){let n=e.schema.nodes;for(let r in n){let i=n[r];if(!i.allowsMarkType(t))continue;let o=[],s=(l)=>{o.push(l);for(let c=0;c{if(i.length||o.marks.length){let s=0,l=0;while(s=0;r--){let i=this.serializeMark(t.marks[r],t.isInline,e);if(i)(i.contentDOM||i.dom).appendChild(n),n=i.dom}return n}serializeMark(t,e,n={}){let r=this.marks[t.type.name];return r&&_r(pr(n),r(t,e),null,t.attrs)}static renderSpec(t,e,n=null,r){if(typeof e=="string")return{dom:t.createTextNode(e)};return _r(t,e,n,r)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new Ve(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let e=as(t.nodes);if(!e.text)e.text=(n)=>n.text;return e}static marksFromSchema(t){return as(t.marks)}}function as(t){let e={};for(let n in t){let r=t[n].spec.toDOM;if(r)e[n]=r}return e}function pr(t){return t.document||window.document}var cs=new WeakMap;function td(t){let e=cs.get(t);if(e===void 0)cs.set(t,e=ed(t));return e}function ed(t){let e=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string"){if(!e)e=[];e.push(r)}else for(let i=0;i-1)throw RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let s=i.indexOf(" ");if(s>0)n=i.slice(0,s),i=i.slice(s+1);let l,c=n?t.createElementNS(n,i):t.createElement(i),d=e[1],f=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){f=2;for(let h in d)if(d[h]!=null){let p=h.indexOf(" ");if(p>0)c.setAttributeNS(h.slice(0,p),h.slice(p+1),d[h]);else if(h=="style"&&c.style)c.style.cssText=d[h];else c.setAttribute(h,d[h])}}for(let h=f;hf)throw RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else if(typeof p=="string")c.appendChild(t.createTextNode(p));else{let{dom:m,contentDOM:g}=_r(t,p,n,r);if(c.appendChild(m),g){if(l)throw RangeError("Multiple content holes");l=g}}}return{dom:c,contentDOM:l}}var Rs=65535,Ls=Math.pow(2,16);function nd(t,e){return t+e*Ls}function Es(t){return t&Rs}function rd(t){return(t-(t&Rs))/Ls}var Ps=1,Bs=2,yr=4,zs=8;class kr{constructor(t,e,n){this.pos=t,this.delInfo=e,this.recover=n}get deleted(){return(this.delInfo&zs)>0}get deletedBefore(){return(this.delInfo&(Ps|yr))>0}get deletedAfter(){return(this.delInfo&(Bs|yr))>0}get deletedAcross(){return(this.delInfo&yr)>0}}class Bt{constructor(t,e=!1){if(this.ranges=t,this.inverted=e,!t.length&&Bt.empty)return Bt.empty}recover(t){let e=0,n=Es(t);if(!this.inverted)for(let r=0;rt)break;let c=this.ranges[s+i],d=this.ranges[s+o],f=l+c;if(t<=f){let h=!c?e:t==l?-1:t==f?1:e,p=l+r+(h<0?0:d);if(n)return p;let m=t==(e<0?l:f)?null:nd(s/3,t-l),g=0;if(c){if(g|=t==l?Bs:t==f?Ps:yr,e<0?t!=l:t!=f)g|=zs}return new kr(p,g,m)}r+=d-c}return n?t+r:new kr(t+r,0,null)}touches(t,e){let n=0,r=Es(e),i=this.inverted?2:1,o=this.inverted?1:2;for(let s=0;st)break;let c=this.ranges[s+i],d=l+c;if(t<=d&&s==r*3)return!0;n+=this.ranges[s+o]-c}return!1}forEach(t){let e=this.inverted?2:1,n=this.inverted?1:2;for(let r=0,i=0;r=0;e--){let r=t.getMirror(e);this.appendMap(t._maps[e].invert(),r!=null&&r>e?n-r-1:void 0)}}invert(){let t=new xr;return t.appendMappingInverted(this),t}map(t,e=1){if(this.mirror)return this._map(t,e,!0);for(let n=this.from;ni&&l{if(!o.isAtom||!s.type.allowsMarkType(this.mark.type))return o;return o.mark(this.mark.addToSet(o.marks))},r),e.openStart,e.openEnd);return ct.fromReplace(t,this.from,this.to,i)}invert(t){let e=[];return t.nodesBetween(this.from,this.to,(n,r)=>{if(n.isInline&&n.isAtom){let i=this.mark.addToSet(n.marks);if(!J.sameSet(i,n.marks)){let o=Math.max(this.from,r),s=Math.min(this.to,r+n.nodeSize);Ir(se,o,s,this.mark,e);for(let l of n.marks)if(!l.isInSet(i))Ir(oe,o,s,l,e)}}}),e.length==1?e[0]:new We(e)}map(t){let e=t.map(this.from,1),n=t.map(this.to,-1);if(e>=n)return null;return new oe(e,n,this.mark)}merge(t){if(t instanceof oe&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from)return new oe(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark);return null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,e){if(typeof e.from!="number"||typeof e.to!="number")throw RangeError("Invalid input for AddMarkStep.fromJSON");return new oe(e.from,e.to,t.markFromJSON(e.mark))}}ht.jsonID("addMark",oe);class se extends ht{constructor(t,e,n){super();this.from=t,this.to=e,this.mark=n}apply(t){let e=t.slice(this.from,this.to),n=new I(Ci(e.content,(r)=>r.mark(this.mark.removeFromSet(r.marks)),t),e.openStart,e.openEnd);return ct.fromReplace(t,this.from,this.to,n)}invert(t){let e=[];return t.nodesBetween(this.from,this.to,(n,r)=>{if(n.isInline&&n.isAtom&&this.mark.isInSet(n.marks))Ir(oe,Math.max(this.from,r),Math.min(this.to,r+n.nodeSize),this.mark,e)}),e.length==1?e[0]:new We(e)}map(t){let e=t.map(this.from,1),n=t.map(this.to,-1);if(e>=n)return null;return new se(e,n,this.mark)}merge(t){if(t instanceof se&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from)return new se(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark);return null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,e){if(typeof e.from!="number"||typeof e.to!="number")throw RangeError("Invalid input for RemoveMarkStep.fromJSON");return new se(e.from,e.to,t.markFromJSON(e.mark))}}ht.jsonID("removeMark",se);function Ir(t,e,n,r,i){let o=i.length?i[i.length-1]:null;if(o&&o instanceof t&&o.to==e&&o.mark.eq(r))i[i.length-1]=new t(o.from,n,r);else i.push(new t(e,n,r))}class We extends ht{constructor(t){super();this.steps=t}apply(t){for(let e of this.steps){let n=e.apply(t);if(!n.doc)return n;t=n.doc}return new ct(t,null)}invert(t){return new We(this.steps.map((e)=>e.invert(t)))}map(t){let e=[];for(let n of this.steps){let r=n.map(t);if(r)e.push(r)}return e.length?new We(e):null}toJSON(){return{stepType:"markSet",steps:this.steps.map((t)=>t.toJSON())}}static fromJSON(t,e){if(!Array.isArray(e.steps)||!e.steps.every((n)=>n.stepType=="addMark"||n.stepType=="removeMark"))throw RangeError("Invalid JSON for MarkSetStep");return new We(e.steps.map((n)=>ht.fromJSON(t,n)))}}ht.jsonID("markSet",We);class be extends ht{constructor(t,e){super();this.pos=t,this.mark=e}apply(t){let e=t.nodeAt(this.pos);if(!e)return ct.fail("No node at mark step's position");let n=e.type.create(e.attrs,null,this.mark.addToSet(e.marks));return ct.fromReplace(t,this.pos,this.pos+1,new I(k.from(n),0,e.isLeaf?0:1))}invert(t){let e=t.nodeAt(this.pos);if(e){let n=this.mark.addToSet(e.marks);if(n.length==e.marks.length){for(let r=0;rn.pos)return null;return new ft(e.pos,n.pos,r,i,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};if(this.slice.size)t.slice=this.slice.toJSON();if(this.structure)t.structure=!0;return t}static fromJSON(t,e){if(typeof e.from!="number"||typeof e.to!="number"||typeof e.gapFrom!="number"||typeof e.gapTo!="number"||typeof e.insert!="number")throw RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new ft(e.from,e.to,e.gapFrom,e.gapTo,I.fromJSON(t,e.slice),e.insert,!!e.structure)}}ht.jsonID("replaceAround",ft);function Si(t,e,n){let r=t.resolve(e),i=n-e,o=r.depth;while(i>0&&o>0&&r.indexAfter(o)==r.node(o).childCount)o--,i--;if(i>0){let s=r.node(o).maybeChild(r.indexAfter(o));while(i>0){if(!s||s.isLeaf)return!0;s=s.firstChild,i--}}return!1}function id(t,e,n,r){let i=[];t.doc.nodesBetween(e,n,(o,s,l)=>{if(!o.isInline)return;let c=o.marks;if(!r.isInSet(c)&&l.type.allowsMarkType(r.type)){let d=Math.max(s,e),f=Math.min(s+o.nodeSize,n);Ir(oe,d,f,r,i)}}),i.forEach((o)=>t.step(o))}function od(t,e,n,r){let i=[],o=0;t.doc.nodesBetween(e,n,(s,l)=>{if(!s.isInline||!s.isAtom)return;o++;let c=null;if(r instanceof zn){let d=s.marks,f;while(f=r.isInSet(d))(c||(c=[])).push(f),d=f.removeFromSet(d)}else if(r){if(r.isInSet(s.marks))c=[r]}else c=s.marks;if(c&&c.length){let d=Math.min(l+s.nodeSize,n);for(let f=0;ft.step(new se(s.from,s.to,s.style)))}function Oi(t,e,n,r=n.contentMatch,i=!0){let o=t.doc.nodeAt(e),s=[],l=e+1;for(let c=0;c=0;c--)t.step(s[c])}function sd(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function Ue(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,i=0,o=0;;--r){let s=t.$from.node(r),l=t.$from.index(r)+i,c=t.$to.indexAfter(r)-o;if(rn;g--)if(b||r.index(g)>0)b=!0,f=k.from(r.node(g).copy(f)),h++;else c--;let p=k.empty,m=0;for(let g=o,b=!1;g>n;g--)if(b||i.after(g+1)=0;s--){if(r.size){let l=n[s].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=k.from(n[s].type.create(n[s].attrs,r))}let{start:i,end:o}=e;t.step(new ft(i,o,i,o,new I(r,0,0),n.length,!0))}function ud(t,e,n,r,i){if(!r.isTextblock)throw RangeError("Type given to setBlockType should be a textblock");let o=t.steps.length;t.doc.nodesBetween(e,n,(s,l)=>{let c=typeof i=="function"?i(s):i;if(s.isTextblock&&!s.hasMarkup(r,c)&&fd(t.doc,t.mapping.slice(o).map(l),r)){let d=null;if(r.schema.linebreakReplacement){let m=r.whitespace=="pre",g=!!r.contentMatch.matchType(r.schema.linebreakReplacement);if(m&&!g)d=!1;else if(!m&&g)d=!0}if(d===!1)Vs(t,s,l,o);Oi(t,t.mapping.slice(o).map(l,1),r,void 0,d===null);let f=t.mapping.slice(o),h=f.map(l,1),p=f.map(l+s.nodeSize,1);if(t.step(new ft(h,p,h+1,p-1,new I(k.from(r.create(c,null,s.marks)),0,0),1,!0)),d===!0)Fs(t,s,l,o);return!1}})}function Fs(t,e,n,r){e.forEach((i,o)=>{if(i.isText){let s,l=/\r?\n|\r/g;while(s=l.exec(i.text)){let c=t.mapping.slice(r).map(n+1+o+s.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function Vs(t,e,n,r){e.forEach((i,o)=>{if(i.type==i.type.schema.linebreakReplacement){let s=t.mapping.slice(r).map(n+1+o);t.replaceWith(s,s+1,e.type.schema.text(` +`))}})}function fd(t,e,n){let r=t.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,n)}function hd(t,e,n,r,i){let o=t.doc.nodeAt(e);if(!o)throw RangeError("No node at given position");if(!n)n=o.type;let s=n.create(r,null,i||o.marks);if(o.isLeaf)return t.replaceWith(e,e+o.nodeSize,s);if(!n.validContent(o.content))throw RangeError("Invalid content for node type "+n.name);t.step(new ft(e,e+o.nodeSize,e+1,e+o.nodeSize-1,new I(k.from(s),0,0),1,!0))}function we(t,e,n=1,r){let i=t.resolve(e),o=i.depth-n,s=r&&r[r.length-1]||i.parent;if(o<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!s.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let d=i.depth-1,f=n-2;d>o;d--,f--){let h=i.node(d),p=i.index(d);if(h.type.spec.isolating)return!1;let m=h.content.cutByIndex(p,h.childCount),g=r&&r[f+1];if(g)m=m.replaceChild(0,g.type.create(g.attrs));let b=r&&r[f]||h;if(!h.canReplace(p+1,h.childCount)||!b.type.validContent(m))return!1}let l=i.indexAfter(o),c=r&&r[0];return i.node(o).canReplaceWith(l,l,c?c.type:i.node(o+1).type)}function pd(t,e,n=1,r){let i=t.doc.resolve(e),o=k.empty,s=k.empty;for(let l=i.depth,c=i.depth-n,d=n-1;l>c;l--,d--){o=k.from(i.node(l).copy(o));let f=r&&r[d];s=k.from(f?f.type.create(f.attrs,s):i.node(l).copy(s))}t.step(new ut(e,e,new I(o.append(s),n,n),!0))}function $e(t,e){let n=t.resolve(e),r=n.index();return gd(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function _d(t,e){if(!e.content.size)t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:r}=t.type.schema;for(let i=0;i=0;i--){let o=r.index(i);if(r.node(i).canReplaceWith(o,o,n))return r.before(i+1);if(o>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let o=r.indexAfter(i);if(r.node(i).canReplaceWith(o,o,n))return r.after(i+1);if(o=0;s--){let l=s==r.depth?0:r.pos<=(r.start(s+1)+r.end(s+1))/2?-1:1,c=r.index(s)+(l>0?1:0),d=r.node(s),f=!1;if(o==1)f=d.canReplace(c,c,i);else{let h=d.contentMatchAt(c).findWrapping(i.firstChild.type);f=h&&d.canReplaceWith(c,c,h[0])}if(f)return l==0?r.pos:l<0?r.before(s+1):r.after(s+1)}return null}function Sr(t,e,n=e,r=I.empty){if(e==n&&!r.size)return null;let i=t.resolve(e),o=t.resolve(n);if(Ws(i,o,r))return new ut(e,n,r);return new qs(i,o,r).fit()}function Ws(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class qs{constructor(t,e,n){this.$from=t,this.$to=e,this.unplaced=n,this.frontier=[],this.placed=k.empty;for(let r=0;r<=t.depth;r++){let i=t.node(r);this.frontier.push({type:i.type,match:i.contentMatchAt(t.indexAfter(r))})}for(let r=t.depth;r>0;r--)this.placed=k.from(t.node(r).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){while(this.unplaced.size){let c=this.findFittable();if(c)this.placeNodes(c);else this.openMore()||this.dropNode()}let t=this.mustMoveInline(),e=this.placed.size-this.depth-this.$from.depth,n=this.$from,r=this.close(t<0?this.$to:n.doc.resolve(t));if(!r)return null;let i=this.placed,o=n.depth,s=r.depth;while(o&&s&&i.childCount==1)i=i.firstChild.content,o--,s--;let l=new I(i,o,s);if(t>-1)return new ft(n.pos,t,this.$to.pos,this.$to.end(),l,e);if(l.size||n.pos!=this.$to.pos)return new ut(n.pos,r.pos,l);return null}findFittable(){let t=this.unplaced.openStart;for(let e=this.unplaced.content,n=0,r=this.unplaced.openEnd;n1)r=0;if(i.type.spec.isolating&&r<=n){t=n;break}e=i.content}for(let e=1;e<=2;e++)for(let n=e==1?t:this.unplaced.openStart;n>=0;n--){let r,i=null;if(n)i=Ds(this.unplaced.content,n-1).firstChild,r=i.content;else r=this.unplaced.content;let o=r.firstChild;for(let s=this.depth;s>=0;s--){let{type:l,match:c}=this.frontier[s],d,f=null;if(e==1&&(o?c.matchType(o.type)||(f=c.fillBefore(k.from(o),!1)):i&&l.compatibleContent(i.type)))return{sliceDepth:n,frontierDepth:s,parent:i,inject:f};else if(e==2&&o&&(d=c.findWrapping(o.type)))return{sliceDepth:n,frontierDepth:s,parent:i,wrap:d};if(i&&c.matchType(i.type))break}}}openMore(){let{content:t,openStart:e,openEnd:n}=this.unplaced;if(Ts(t,-1)<=e)return!1;if(this.unplaced.size>1&&Ts(t,1)>n)n++;return this.unplaced=new I(t,e+1,n),!0}dropNode(){let{content:t,openStart:e,openEnd:n}=this.unplaced,r=Ds(t,e);if(r.childCount<=1&&e>0){let i=t.size-e<=e+r.size;this.unplaced=new I(Fn(t,e-1,1),e-1,i?e-1:n)}else this.unplaced=new I(Fn(t,e,1),e,n)}placeNodes({sliceDepth:t,frontierDepth:e,parent:n,inject:r,wrap:i}){while(this.depth>e)this.closeFrontierNode();if(i)for(let g=0;g1||l==0||g.content.size)f=b,d.push(Us(g.mark(h.allowedMarks(g.marks)),c==1?l:0,c==s.childCount?p:-1))}let m=c==s.childCount;if(!m)p=-1;if(this.placed=Vn(this.placed,e,k.from(d)),this.frontier[e].match=f,m&&p<0&&n&&n.type==this.frontier[this.depth].type&&this.frontier.length>1)this.closeFrontierNode();for(let g=0,b=s;g1&&r==this.$to.end(--n))++r;return r}findCloseLevel(t){t:for(let e=Math.min(this.depth,t.depth);e>=0;e--){let{match:n,type:r}=this.frontier[e],i=e=0;s--){let{match:l,type:c}=this.frontier[s],d=vi(t,s,c,l,!0);if(!d||d.childCount)continue t}return{depth:e,fit:o,move:i?t.doc.resolve(t.after(e+1)):t}}}close(t){let e=this.findCloseLevel(t);if(!e)return null;while(this.depth>e.depth)this.closeFrontierNode();if(e.fit.childCount)this.placed=Vn(this.placed,e.depth,e.fit);t=e.move;for(let n=e.depth+1;n<=t.depth;n++){let r=t.node(n),i=r.type.contentMatch.fillBefore(r.content,!0,t.index(n));this.openFrontierNode(r.type,r.attrs,i)}return t}openFrontierNode(t,e=null,n){let r=this.frontier[this.depth];r.match=r.match.matchType(t),this.placed=Vn(this.placed,this.depth,k.from(t.create(e,n))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let e=this.frontier.pop().match.fillBefore(k.empty,!0);if(e.childCount)this.placed=Vn(this.placed,this.frontier.length,e)}}function Fn(t,e,n){if(e==0)return t.cutByIndex(n,t.childCount);return t.replaceChild(0,t.firstChild.copy(Fn(t.firstChild.content,e-1,n)))}function Vn(t,e,n){if(e==0)return t.append(n);return t.replaceChild(t.childCount-1,t.lastChild.copy(Vn(t.lastChild.content,e-1,n)))}function Ds(t,e){for(let n=0;n1)r=r.replaceChild(0,Us(r.firstChild,e-1,r.childCount==1?n-1:0));if(e>0){if(r=t.type.contentMatch.fillBefore(r).append(r),n<=0)r=r.append(t.type.contentMatch.matchFragment(r).fillBefore(k.empty,!0))}return t.copy(r)}function vi(t,e,n,r,i){let o=t.node(e),s=i?t.indexAfter(e):t.index(e);if(s==o.childCount&&!n.compatibleContent(o.type))return null;let l=r.fillBefore(o.content,!0,s);return l&&!wd(n,o.content,s)?l:null}function wd(t,e,n){for(let r=n;r0;p--,m--){let g=i.node(p).type.spec;if(g.defining||g.definingAsContext||g.isolating)break;if(s.indexOf(p)>-1)l=p;else if(i.before(p)==m)s.splice(1,0,-p)}let c=s.indexOf(l),d=[],f=r.openStart;for(let p=r.content,m=0;;m++){let g=p.firstChild;if(d.push(g),m==r.openStart)break;p=g.content}for(let p=f-1;p>=0;p--){let m=d[p],g=yd(m.type);if(g&&!m.sameMarkup(i.node(Math.abs(l)-1)))f=p;else if(g||!m.type.isTextblock)break}for(let p=r.openStart;p>=0;p--){let m=(p+f+1)%(r.openStart+1),g=d[m];if(!g)continue;for(let b=0;b=0;p--){if(t.replace(e,n,r),t.steps.length>h)break;let m=s[p];if(m<0)continue;e=i.before(m),n=o.after(m)}}function $s(t,e,n,r,i){if(er){let o=i.contentMatchAt(0),s=o.fillBefore(t).append(t);t=s.append(o.matchFragment(s).fillBefore(k.empty,!0))}return t}function xd(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let i=bd(t.doc,e,r.type);if(i!=null)e=n=i}t.replaceRange(e,n,new I(k.from(r),0,0))}function Id(t,e,n){let r=t.doc.resolve(e),i=t.doc.resolve(n);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let s=r.sharedDepth(n),l=!1;for(let c=r.depth;c>s;c--)if(r.node(c).type.spec.isolating)l=!0;for(let c=i.depth;c>s;c--)if(i.node(c).type.spec.isolating)l=!0;if(!l){for(let c=r.depth;c>0&&e==r.start(c);c--)e=r.before(c);for(let c=i.depth;c>0&&n==i.start(c);c--)n=i.before(c);r=t.doc.resolve(e),i=t.doc.resolve(n)}}let o=Js(r,i);for(let s=0;s0&&(c||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return t.delete(r.before(l),i.after(l))}for(let s=1;s<=r.depth&&s<=i.depth;s++)if(e-r.start(s)==r.depth-s&&n>r.end(s)&&i.end(s)-n!=i.depth-s&&r.start(s-1)==i.start(s-1)&&r.node(s-1).canReplace(r.index(s-1),i.index(s-1)))return t.delete(r.before(s),n);t.delete(e,n)}function Js(t,e){let n=[],r=Math.min(t.depth,e.depth);for(let i=r;i>=0;i--){let o=t.start(i);if(oe.pos+(e.depth-i)||t.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;if(o==e.start(i)||i==t.depth&&i==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==o-1)n.push(i)}return n}class ln extends ht{constructor(t,e,n){super();this.pos=t,this.attr=e,this.value=n}apply(t){let e=t.nodeAt(this.pos);if(!e)return ct.fail("No node at attribute step's position");let n=Object.create(null);for(let i in e.attrs)n[i]=e.attrs[i];n[this.attr]=this.value;let r=e.type.create(n,null,e.marks);return ct.fromReplace(t,this.pos,this.pos+1,new I(k.from(r),0,e.isLeaf?0:1))}getMap(){return Bt.empty}invert(t){return new ln(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let e=t.mapResult(this.pos,1);return e.deletedAfter?null:new ln(e.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,e){if(typeof e.pos!="number"||typeof e.attr!="string")throw RangeError("Invalid input for AttrStep.fromJSON");return new ln(e.pos,e.attr,e.value)}}ht.jsonID("attr",ln);class Wn extends ht{constructor(t,e){super();this.attr=t,this.value=e}apply(t){let e=Object.create(null);for(let r in t.attrs)e[r]=t.attrs[r];e[this.attr]=this.value;let n=t.type.create(e,t.content,t.marks);return ct.ok(n)}getMap(){return Bt.empty}invert(t){return new Wn(this.attr,t.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(t,e){if(typeof e.attr!="string")throw RangeError("Invalid input for DocAttrStep.fromJSON");return new Wn(e.attr,e.value)}}ht.jsonID("docAttr",Wn);var an=class extends Error{};an=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n};an.prototype=Object.create(Error.prototype);an.prototype.constructor=an;an.prototype.name="TransformError";class Mi{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new xr}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let e=this.maybeStep(t);if(e.failed)throw new an(e.failed);return this}maybeStep(t){let e=t.apply(this.doc);if(!e.failed)this.addStep(t,e.doc);return e}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,e=-1e9;for(let n=0;n{t=Math.min(t,s),e=Math.max(e,l)})}return t==1e9?null:{from:t,to:e}}addStep(t,e){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=e}replace(t,e=t,n=I.empty){let r=Sr(this.doc,t,e,n);if(r)this.step(r);return this}replaceWith(t,e,n){return this.replace(t,e,new I(k.from(n),0,0))}delete(t,e){return this.replace(t,e,I.empty)}insert(t,e){return this.replaceWith(t,t,e)}replaceRange(t,e,n){return kd(this,t,e,n),this}replaceRangeWith(t,e,n){return xd(this,t,e,n),this}deleteRange(t,e){return Id(this,t,e),this}lift(t,e){return ld(this,t,e),this}join(t,e=1){return md(this,t,e),this}wrap(t,e){return dd(this,t,e),this}setBlockType(t,e=t,n,r=null){return ud(this,t,e,n,r),this}setNodeMarkup(t,e,n=null,r){return hd(this,t,e,n,r),this}setNodeAttribute(t,e,n){return this.step(new ln(t,e,n)),this}setDocAttribute(t,e){return this.step(new Wn(t,e)),this}addNodeMark(t,e){return this.step(new be(t,e)),this}removeNodeMark(t,e){let n=this.doc.nodeAt(t);if(!n)throw RangeError("No node at position "+t);if(e instanceof J){if(e.isInSet(n.marks))this.step(new qe(t,e))}else{let r=n.marks,i,o=[];while(i=e.isInSet(r))o.push(new qe(t,i)),r=i.removeFromSet(r);for(let s=o.length-1;s>=0;s--)this.step(o[s])}return this}split(t,e=1,n){return pd(this,t,e,n),this}addMark(t,e,n){return id(this,t,e,n),this}removeMark(t,e,n){return od(this,t,e,n),this}clearIncompatible(t,e,n){return Oi(this,t,e,n),this}}var Ai=Object.create(null);class F{constructor(t,e,n){this.$anchor=t,this.$head=e,this.ranges=n||[new qn(t.min(e),t.max(e))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let t=this.ranges;for(let e=0;e=0;i--){let o=e<0?dn(t.node(0),t.node(i),t.before(i+1),t.index(i),e,n):dn(t.node(0),t.node(i),t.after(i+1),t.index(i)+1,e,n);if(o)return o}return null}static near(t,e=1){return this.findFrom(t,e)||this.findFrom(t,-e)||new Ct(t.node(0))}static atStart(t){return dn(t,t,0,0,1)||new Ct(t)}static atEnd(t){return dn(t,t,t.content.size,t.childCount,-1)||new Ct(t)}static fromJSON(t,e){if(!e||!e.type)throw RangeError("Invalid input for Selection.fromJSON");let n=Ai[e.type];if(!n)throw RangeError(`No selection type ${e.type} defined`);return n.fromJSON(t,e)}static jsonID(t,e){if(t in Ai)throw RangeError("Duplicate use of selection JSON ID "+t);return Ai[t]=e,e.prototype.jsonID=t,e}getBookmark(){return R.between(this.$anchor,this.$head).getBookmark()}}F.prototype.visible=!0;class qn{constructor(t,e){this.$from=t,this.$to=e}}var js=!1;function Hs(t){if(!js&&!t.parent.inlineContent)js=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")")}class R extends F{constructor(t,e=t){Hs(t),Hs(e);super(t,e)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,e){let n=t.resolve(e.map(this.head));if(!n.parent.inlineContent)return F.near(n);let r=t.resolve(e.map(this.anchor));return new R(r.parent.inlineContent?r:n,n)}replace(t,e=I.empty){if(super.replace(t,e),e==I.empty){let n=this.$from.marksAcross(this.$to);if(n)t.ensureMarks(n)}}eq(t){return t instanceof R&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new Mr(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,e){if(typeof e.anchor!="number"||typeof e.head!="number")throw RangeError("Invalid input for TextSelection.fromJSON");return new R(t.resolve(e.anchor),t.resolve(e.head))}static create(t,e,n=e){let r=t.resolve(e);return new this(r,n==e?r:t.resolve(n))}static between(t,e,n){let r=t.pos-e.pos;if(!n||r)n=r>=0?1:-1;if(!e.parent.inlineContent){let i=F.findFrom(e,n,!0)||F.findFrom(e,-n,!0);if(i)e=i.$head;else return F.near(e,n)}if(!t.parent.inlineContent){if(r==0)t=e;else if(t=(F.findFrom(t,-n,!0)||F.findFrom(t,n,!0)).$anchor,t.pos0?0:1);i>0?s=0;s+=i){let l=e.child(s);if(!l.isAtom){let c=dn(t,l,n+i,i<0?l.childCount:0,i,o);if(c)return c}else if(!o&&T.isSelectable(l))return T.create(t,n-(i<0?l.nodeSize:0));n+=l.nodeSize*i}return null}function Ks(t,e,n){let r=t.steps.length-1;if(r{if(s==null)s=f}),t.setSelection(F.near(t.doc.resolve(s),n))}var Ys=1,Cr=2,Xs=4;class Qs extends Mi{constructor(t){super(t.doc);this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=t.selection,this.storedMarks=t.storedMarks}get selection(){if(this.curSelectionFor0}setStoredMarks(t){return this.storedMarks=t,this.updated|=Cr,this}ensureMarks(t){if(!J.sameSet(this.storedMarks||this.selection.$from.marks(),t))this.setStoredMarks(t);return this}addStoredMark(t){return this.ensureMarks(t.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(t){return this.ensureMarks(t.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Cr)>0}addStep(t,e){super.addStep(t,e),this.updated=this.updated&~Cr,this.storedMarks=null}setTime(t){return this.time=t,this}replaceSelection(t){return this.selection.replace(this,t),this}replaceSelectionWith(t,e=!0){let n=this.selection;if(e)t=t.mark(this.storedMarks||(n.empty?n.$from.marks():n.$from.marksAcross(n.$to)||J.none));return n.replaceWith(this,t),this}deleteSelection(){return this.selection.replace(this),this}insertText(t,e,n){let r=this.doc.type.schema;if(e==null){if(!t)return this.deleteSelection();return this.replaceSelectionWith(r.text(t),!0)}else{if(n==null)n=e;if(!t)return this.deleteRange(e,n);let i=this.storedMarks;if(!i){let o=this.doc.resolve(e);i=n==e?o.marks():o.marksAcross(this.doc.resolve(n))}if(this.replaceRangeWith(e,n,r.text(t,i)),!this.selection.empty&&this.selection.to==e+t.length)this.setSelection(F.near(this.selection.$to));return this}}setMeta(t,e){return this.meta[typeof t=="string"?t:t.key]=e,this}getMeta(t){return this.meta[typeof t=="string"?t:t.key]}get isGeneric(){for(let t in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Xs,this}get scrolledIntoView(){return(this.updated&Xs)>0}}function Gs(t,e){return!e||!t?t:t.bind(e)}class un{constructor(t,e,n){this.name=t,this.init=Gs(e.init,n),this.apply=Gs(e.apply,n)}}var Sd=[new un("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new un("selection",{init(t,e){return t.selection||F.atStart(e.doc)},apply(t){return t.selection}}),new un("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new un("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class Or{constructor(t,e){if(this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=Sd.slice(),e)e.forEach((n)=>{if(this.pluginsByKey[n.key])throw RangeError("Adding different instances of a keyed plugin ("+n.key+")");if(this.plugins.push(n),this.pluginsByKey[n.key]=n,n.spec.state)this.fields.push(new un(n.key,n.spec.state,n))})}}class ye{constructor(t){this.config=t}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(t){return this.applyTransaction(t).state}filterTransaction(t,e=-1){for(let n=0;nn.toJSON());if(t&&typeof t=="object")for(let n in t){if(n=="doc"||n=="selection")throw RangeError("The JSON fields `doc` and `selection` are reserved");let r=t[n],i=r.spec.state;if(i&&i.toJSON)e[n]=i.toJSON.call(r,this[r.key])}return e}static fromJSON(t,e,n){if(!e)throw RangeError("Invalid input for EditorState.fromJSON");if(!t.schema)throw RangeError("Required config field 'schema' missing");let r=new Or(t.schema,t.plugins),i=new ye(r);return r.fields.forEach((o)=>{if(o.name=="doc")i.doc=qt.fromJSON(t.schema,e.doc);else if(o.name=="selection")i.selection=F.fromJSON(i.doc,e.selection);else if(o.name=="storedMarks"){if(e.storedMarks)i.storedMarks=e.storedMarks.map(t.schema.markFromJSON)}else{if(n)for(let s in n){let l=n[s],c=l.spec.state;if(l.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(e,s)){i[o.name]=c.fromJSON.call(l,t,e[s],i);return}}i[o.name]=o.init(t,i)}}),i}}function Zs(t,e,n){for(let r in t){let i=t[r];if(i instanceof Function)i=i.bind(e);else if(r=="handleDOMEvents")i=Zs(i,e,{});n[r]=i}return n}class st{constructor(t){if(this.spec=t,this.props={},t.props)Zs(t.props,this,this.props);this.key=t.key?t.key.key:tl("plugin")}getState(t){return t[this.key]}}var Ei=Object.create(null);function tl(t){if(t in Ei)return t+"$"+ ++Ei[t];return Ei[t]=0,t+"$"}class fn{constructor(t="key"){this.key=tl(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}var bt=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},gn=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e},Pi=null,ae=function(t,e,n){let r=Pi||(Pi=document.createRange());return r.setEnd(t,n==null?t.nodeValue.length:n),r.setStart(t,e||0),r},Cd=function(){Pi=null},Xe=function(t,e,n,r){return n&&(el(t,e,n,r,-1)||el(t,e,n,r,1))},Od=/^(img|br|input|textarea|hr)$/i;function el(t,e,n,r,i){var o;for(;;){if(t==n&&e==r)return!0;if(e==(i<0?0:It(t))){let s=t.parentNode;if(!s||!E(s)||Xn(t)||Od.test(t.nodeName)||t.contentEditable=="false")return!1;e=bt(t)+(i<0?0:1),t=s}else if(E(t)){let s=t.childNodes[e+(i<0?-1:0)];if(E(s)&&s.contentEditable=="false")if((o=s.pmViewDesc)===null||o===void 0?void 0:o.ignoreForSelection)e+=i;else return!1;else t=s,e=i<0?It(t):0}else return!1}}function It(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function E(t){return t.nodeType==1}function pt(t){return t.nodeType==3}function Ge(t,e){return e?t.contains(E(e)?e:e.parentNode):!1}function Md(t,e){for(;;){if(pt(t)&&e)return t;if(E(t)&&e>0){if(t.contentEditable=="false")return null;t=t.childNodes[e-1],e=It(t)}else if(t.parentNode&&!Xn(t))e=bt(t),t=t.parentNode;else return null}}function Ad(t,e){for(;;){if(pt(t)&&e2),Ut=mn||(ne?/Mac/.test(ne.platform):!1),Tl=ne?/Win/.test(ne.platform):!1,ce=/Android \d/.test(Me),Lr=!!nl&&"webkitFontSmoothing"in nl.documentElement.style,Td=Lr?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function Rd(t){let e=t.defaultView&&t.defaultView.visualViewport;if(e)return{left:0,right:e.width,top:0,bottom:e.height};return{left:0,right:t.documentElement.clientWidth,top:0,bottom:t.documentElement.clientHeight}}function le(t,e){return typeof t=="number"?t:t[e]}function Ld(t){let e=t.getBoundingClientRect(),n=e.width/t.offsetWidth||1,r=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*n,top:e.top,bottom:e.top+t.clientHeight*r}}function rl(t,e,n){if(!Vi(e)&&e.left==0)return;let r=t.someProp("scrollThreshold")||0,i=t.someProp("scrollMargin")||5,o=t.dom.ownerDocument;for(let s=n||t.dom;;){if(!s)break;if(!E(s)){s=gn(s);continue}let l=s==o.body,c=l?Rd(o):Ld(s),d=0,f=0;if(e.topc.bottom-le(r,"bottom"))f=e.bottom-e.top>c.bottom-c.top?e.top+le(i,"top")-c.top:e.bottom-c.bottom+le(i,"bottom");if(e.leftc.right-le(r,"right"))d=e.right-c.right+le(i,"right");if(d||f)if(l)o.defaultView.scrollBy(d,f);else{let p=s.scrollLeft,m=s.scrollTop;if(f)s.scrollTop+=f;if(d)s.scrollLeft+=d;let g=s.scrollLeft-p,b=s.scrollTop-m;e={left:e.left-g,top:e.top-b,right:e.right-g,bottom:e.bottom-b}}let h=l?"fixed":getComputedStyle(s).position;if(/^(fixed|sticky)$/.test(h))break;s=h=="absolute"?s.offsetParent:gn(s)}}function Pd(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),r,i;for(let o=(e.left+e.right)/2,s=n+1;s=n-20){r=l,i=c.top;break}}return{refDOM:r,refTop:i,stack:Rl(t.dom)}}function Rl(t){let e=[],n=t.ownerDocument;for(let r=t;r;r=gn(r))if(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t==n)break;return e}function Bd({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;Ll(n,r==0?0:r-e)}function Ll(t,e){for(let n=0;n=l){s=Math.max(g.bottom,s),l=Math.min(g.top,l);let b=g.left>e.left?g.left-e.left:g.right=(g.left+g.right)/2?1:0);continue}}else if(g.top>e.top&&!c&&g.left<=e.left&&g.right>=e.left)c=f,d={left:Math.max(g.left,Math.min(g.right,e.left)),top:g.top};if(!n&&(e.left>=g.right&&e.top>=g.top||e.left>=g.left&&e.top>=g.bottom))o=h+1}}if(!n&&c)n=c,i=d,r=0;if(n&&pt(n))return Fd(n,i);if(!n||r)return{node:t,offset:o};return Pl(n,i)}function Fd(t,e){let n=t.nodeValue.length,r=document.createRange(),i;for(let o=0;o=(s.left+s.right)/2?1:0)};break}}return r.detach(),i||{node:t,offset:0}}function Hi(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function Vd(t,e){let n=t.parentNode;if(n&&/^li$/i.test(n.nodeName)&&e.left(s.left+s.right)/2?1:-1}return t.docView.posFromDOM(r,i,o)}function qd(t,e,n,r){let i=-1;for(let o=e,s=!1;;){if(o==t.dom)break;let l=t.docView.nearestDesc(o,!0),c;if(!l)return null;if(E(l.dom)&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((c=l.dom.getBoundingClientRect()).width||c.height)){if(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)){if(!s&&c.left>r.left||c.top>r.top)i=l.posBefore;else if(!s&&c.right-1?i:t.docView.posFromDOM(e,n,-1)}function Bl(t,e,n){let r=t.childNodes.length;if(r&&n.tope.top)i++}}let d;if(Lr&&i&&E(r)&&E(d=r.childNodes[i-1])&&d.contentEditable=="false"&&d.getBoundingClientRect().top>=e.top)i--;if(r==t.dom&&i==r.childNodes.length-1&&E(r.lastChild)&&e.top>r.lastChild.getBoundingClientRect().bottom)l=t.state.doc.content.size;else if(i==0||!E(r)||r.childNodes[i-1].nodeName!="BR")l=qd(t,r,i,e)}if(l==null)l=Wd(t,s,e);let c=t.docView.nearestDesc(s,!0);return{pos:l,inside:c?c.posAtStart-c.border:-1}}function Vi(t){return t.top=0&&i==r.nodeValue.length)c--,f=1;else if(n<0)c--;else d++;return Un(ke(ae(r,c,d),f),f<0)}if(!t.state.doc.resolve(e-(o||0)).parent.inlineContent){if(o==null&&i&&(n<0||i==It(r))){let c=r.childNodes[i-1];if(E(c))return Di(c.getBoundingClientRect(),!1)}if(o==null&&i=0)}if(o==null&&i&&(n<0||i==It(r))){let c=r.childNodes[i-1],d=pt(c)?ae(c,It(c)-(s?0:1)):E(c)&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return Un(ke(d,1),!1)}if(o==null&&i=0)}function Un(t,e){if(t.width==0)return t;let n=e?t.left:t.right;return{top:t.top,bottom:t.bottom,left:n,right:n}}function Di(t,e){if(t.height==0)return t;let n=e?t.top:t.bottom;return{top:n,bottom:n,left:t.left,right:t.right}}function Fl(t,e,n){let r=t.state,i=t.root.activeElement;if(r!=e)t.updateState(e);if(i!=t.dom)t.focus();try{return n()}finally{if(r!=e)t.updateState(r);if(i!=t.dom&&i)i.focus()}}function Jd(t,e,n){let r=e.selection,i=n=="up"?r.$from:r.$to;return Fl(t,e,()=>{let{node:o}=t.docView.domFromPos(i.pos,n=="up"?-1:1);for(;;){let l=t.docView.nearestDesc(o,!0);if(!l)break;if(l.node.isBlock){o=l.contentDOM||l.dom;break}o=l.dom.parentNode}let s=zl(t,i.pos,1);for(let l=o.firstChild;l;l=l.nextSibling){let c;if(E(l))c=l.getClientRects();else if(pt(l))c=ae(l,0,l.nodeValue.length).getClientRects();else continue;for(let d=0;df.top+1&&(n=="up"?s.top-f.top>(f.bottom-s.top)*2:f.bottom-s.bottom>(s.bottom-f.top)*2))return!1}}return!0})}var jd=/[\u0590-\u08ac]/;function Hd(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,o=!i,s=i==r.parent.content.size,l=t.domSelection();if(!l)return r.pos==r.start()||r.pos==r.end();if(!jd.test(r.parent.textContent)||!l.modify)return n=="left"||n=="backward"?o:s;return Fl(t,e,()=>{let{focusNode:c,focusOffset:d,anchorNode:f,anchorOffset:h}=t.domSelectionRange(),p=l.caretBidiLevel;l.modify("move",n,"character");let m=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:g,focusOffset:b}=t.domSelectionRange(),y=g&&!Ge(m,g)||c==g&&d==b;try{if(l.collapse(f,h),c&&(c!=f||d!=h)&&l.extend)l.extend(c,d)}catch(S){}if(p!=null)l.caretBidiLevel=p;return y})}var il=null,ol=null,sl=!1;function Kd(t,e,n){if(il==e&&ol==n)return sl;return il=e,ol=n,sl=n=="up"||n=="down"?Jd(t,e,n):Hd(t,e,n)}var $t=0,ll=1,je=2,Yt=3;class bn{constructor(t,e,n,r){this.parent=t,this.children=e,this.dom=n,this.contentDOM=r,this.dirty=$t,n.pmViewDesc=this}matchesWidget(t){return!1}matchesMark(t){return!1}matchesNode(t,e,n){return!1}matchesHack(t){return!1}parseRule(t){return null}stopEvent(t){return!1}get size(){let t=0;for(let e=0;ebt(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM)){let i=t.compareDocumentPosition(this.contentDOM);if(i&16)r=e>Array.from(t.childNodes).findIndex((o)=>o.contains(this.contentDOM));else r=!(i&4)}else if(this.dom.firstChild){if(e==0)for(let i=t;;i=i.parentNode){if(i==this.dom){r=!1;break}if(i.previousSibling)break}if(r==null&&e==t.childNodes.length)for(let i=t;;i=i.parentNode){if(i==this.dom){r=!0;break}if(i.nextSibling)break}}return(r==null?n>0:r)?this.posAtEnd:this.posAtStart}nearestDesc(t,e=!1){for(let n=!0,r=t;r;r=r.parentNode){let i=this.getDesc(r),o;if(i&&(!e||i.node))if(n&&(o=i.nodeDOM)&&!(E(o)?Ge(o,t):o==t))n=!1;else return i}}getDesc(t){let e=t.pmViewDesc;for(let n=e;n;n=n.parent)if(n==this)return e}posFromDOM(t,e,n){for(let r=t;r;r=r.parentNode){let i=this.getDesc(r);if(i)return i.localPosFromDOM(t,e,n)}return-1}descAt(t){for(let e=0,n=0;et){r=t-i;break}i=s}if(r)return this.children[n].domFromPos(r-this.children[n].border,e);for(;n>0;n--){let i=this.children[n-1];if(i.size||!(i instanceof Yi||i instanceof Ki&&i.side>=0))break}if(e<=0){let i,o=!0;for(;;n--,o=!1)if(i=n?this.children[n-1]:null,!i||i.dom.parentNode==this.contentDOM)break;if(i&&e&&o&&!i.border&&!i.domAtom)return i.domFromPos(i.size,e);return{node:this.contentDOM,offset:i?bt(i.dom)+1:0}}else{let i,o=!0;for(;;n++,o=!1)if(i=n=d&&e<=c-l.border&&l.node&&l.contentDOM&&this.contentDOM.contains(l.contentDOM))return l.parseRange(t,e,d);t=o;for(let f=s;f>0;f--){let h=this.children[f-1];if(h.size&&h.dom.parentNode==this.contentDOM&&!h.emptyChildAt(1)){r=bt(h.dom)+1;break}t-=h.size}if(r==-1)r=0}if(r>-1&&(c>e||s==this.children.length-1)){e=c;for(let d=s+1;dm&&oe){let m=s;s=l,l=m}let p=document.createRange();p.setEnd(l.node,l.offset),p.setStart(s.node,s.offset),c.removeAllRanges(),c.addRange(p)}}ignoreMutation(t){return!this.contentDOM&&t.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,e){for(let n=0,r=0;r=n:tn){let s=n+i.border,l=o-i.border;if(t>=s&&e<=l){if(this.dirty=t==n||e==o?je:ll,t==s&&e==l&&(i.contentLost||i.dom.parentNode!=this.contentDOM))i.dirty=Yt;else i.markDirty(t-s,e-s);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?je:Yt}n=o}this.dirty=je}markParentsDirty(){let t=1;for(let e=this.parent;e;e=e.parent,t++){let n=t==1?je:ll;if(e.dirty{if(!i)return r;if(i.parent)return i.parent.posBeforeChild(i)});if(!e.type.spec.raw){let s=E(o)?o:document.createElement("span");if(s!=o)s.appendChild(o),o=s;if(!s.hasAttribute("contenteditable"))s.contentEditable="false";s.classList.add("ProseMirror-widget")}super(t,[],o,null);this.widget=e,this.widget=e,i=this}matchesWidget(t){return this.dirty==$t&&t.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(t){let e=this.widget.spec.stopEvent;return e?e(t):!1}ignoreMutation(t){return t.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class Vl extends bn{constructor(t,e,n,r){super(t,[],e,null);this.textDOM=n,this.text=r}get size(){return this.text.length}localPosFromDOM(t,e){if(t!=this.textDOM)return this.posAtStart+(e?this.size:0);return this.posAtStart+e}domFromPos(t){return{node:this.textDOM,offset:t}}ignoreMutation(t){return t.type==="characterData"&&t.target.nodeValue==t.oldValue}}class Se extends bn{constructor(t,e,n,r,i){super(t,[],n,r);this.mark=e,this.spec=i}static create(t,e,n,r){let i=r.nodeViews[e.type.name],o=i&&i(e,r,n);if(!o||!o.dom)o=Ve.renderSpec(document,e.type.spec.toDOM(e,n),null,e.attrs);return new Se(t,e,o.dom,o.contentDOM||o.dom,o)}parseRule(){if(this.dirty&Yt||this.mark.type.spec.reparseInView)return null;return{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=Yt&&this.mark.eq(t)}markDirty(t,e){if(super.markDirty(t,e),this.dirty!=$t){let n=this.parent;while(!n.node)n=n.parent;if(n.dirty0)i=qi(i,0,t,n);for(let s=0;s{if(!l)return o;if(l.parent)return l.parent.posBeforeChild(l)},n,r),d=c&&c.dom,f=c&&c.contentDOM;if(e.isText){if(!d)d=document.createTextNode(e.text);else if(!pt(d))throw RangeError("Text must be rendered as a DOM text node")}else if(!d)({dom:d,contentDOM:f}=Ve.renderSpec(document,e.type.spec.toDOM(e),null,e.attrs));if(!f&&!e.isText&&d.nodeName!="BR"){if(!d.hasAttribute("contenteditable"))d.contentEditable="false";if(e.type.spec.draggable)d.draggable=!0}let h=d;if(d=$l(d,n,e),c)return l=new Wl(t,e,n,r,d,f||null,h,c);else if(e.isText)return new Pr(t,e,n,r,d,h);else return new Ce(t,e,n,r,d,f||null,h)}parseRule(t){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre")e.preserveWhitespace="full";if(!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}if(!e.contentElement){let n=t&&t.find((r)=>E(r)&&t.indexOf(r.parentNode)<0&&this.dom.contains(r));if(n)e.contentElement=n;else e.getContent=()=>k.empty}}return e}matchesNode(t,e,n){return this.dirty==$t&&t.eq(this.node)&&Ar(e,this.outerDeco)&&n.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(t,e){let n=this.node.inlineContent,r=e,i=t.composing?this.localCompositionInfo(t,e):null,o=i&&i.pos>-1?i:null,s=i&&i.pos<0,l=new Jl(this,o&&o.node,t),c=this.node.inlineContent,d=c&&this.node.isBlock;if(Qd(this.node,this.innerDeco,(f,h,p)=>{if(f.spec.marks)l.syncToMarks(f.spec.marks,n,t,h);else if(f.type.side>=0&&!p)l.syncToMarks(h==this.node.childCount?J.none:this.node.child(h).marks,n,t,h);l.placeWidget(f,t,r)},(f,h,p,m)=>{if(l.syncToMarks(f.marks,n,t,m),d&&f.isAtom&&!f.isText)l.addHackNode("IMG",l.top);let g;if(l.findNodeMatch(f,h,p,m));else if(s&&t.state.selection.from>r&&t.state.selection.to-1&&l.updateNodeAt(f,h,p,g,t));else if(l.updateNextNode(f,h,p,t,m,r));else l.addNode(f,h,p,t,r);if(r+=f.nodeSize,c)d=f.isAtom&&!f.isText}),l.syncToMarks([],n,t,0),this.node.isTextblock)l.addTextblockHacks();if(l.destroyRest(),l.changed||this.dirty==je){if(o)this.protectLocalComposition(t,o);if(ql(this.contentDOM,this.children,t),mn)Zd(this.dom)}}localCompositionInfo(t,e){let{from:n,to:r}=t.state.selection;if(!(t.state.selection instanceof R)||ne+this.node.content.size)return null;let i=t.input.compositionNode;if(!i||!this.dom.contains(i.parentNode))return null;if(this.node.inlineContent){let o=i.nodeValue,s=tu(this.node.content,o,n-e,r-e);return s<0?null:{node:i,pos:s,text:o}}else return{node:i,pos:-1,text:""}}protectLocalComposition(t,{node:e,pos:n,text:r}){if(this.getDesc(e))return;let i=e;for(;;i=i.parentNode){if(i.parentNode==this.contentDOM)break;while(i.previousSibling)i.parentNode.removeChild(i.previousSibling);while(i.nextSibling)i.parentNode.removeChild(i.nextSibling);if(i.pmViewDesc)i.pmViewDesc=void 0}let o=new Vl(this,i,e,r);t.input.compositionNodes.push(o),this.children=qi(this.children,n,n+r.length,t,o)}update(t,e,n,r){if(this.dirty==Yt||!t.sameMarkup(this.node))return!1;return this.updateInner(t,e,n,r),!0}updateInner(t,e,n,r){if(this.updateOuterDeco(e),this.node=t,this.innerDeco=n,this.contentDOM)this.updateChildren(r,this.posAtStart);this.dirty=$t}updateOuterDeco(t){if(Ar(t,this.outerDeco))return;let e=!E(this.nodeDOM),n=this.dom;if(this.dom=Ul(this.dom,this.nodeDOM,Wi(this.outerDeco,this.node,e),Wi(t,this.node,e)),this.dom!=n)n.pmViewDesc=void 0,this.dom.pmViewDesc=this;this.outerDeco=t}selectNode(){if(E(this.nodeDOM)){if(this.nodeDOM.classList.add("ProseMirror-selectednode"),this.contentDOM||!this.node.type.spec.draggable)this.nodeDOM.draggable=!0}}deselectNode(){if(E(this.nodeDOM)){if(this.nodeDOM.classList.remove("ProseMirror-selectednode"),this.contentDOM||!this.node.type.spec.draggable)this.nodeDOM.removeAttribute("draggable")}}get domAtom(){return this.node.isAtom}}function al(t,e,n,r,i){$l(r,e,t);let o=new Ce(void 0,t,e,n,r,r,r);if(o.contentDOM)o.updateChildren(i,0);return o}class Pr extends Ce{constructor(t,e,n,r,i,o){super(t,e,n,r,i,null,o)}parseRule(){let t=this.nodeDOM.parentNode;while(t&&t!=this.dom&&!t.pmIsDeco)t=t.parentNode;return{skip:t||!0}}update(t,e,n,r){if(this.dirty==Yt||this.dirty!=$t&&!this.inParent()||!t.sameMarkup(this.node))return!1;if(this.updateOuterDeco(e),(this.dirty!=$t||t.text!=this.node.text)&&t.text!=this.nodeDOM.nodeValue){if(this.nodeDOM.nodeValue=t.text,r.trackWrites==this.nodeDOM)r.trackWrites=null}return this.node=t,this.dirty=$t,!0}inParent(){let t=this.parent.contentDOM;for(let e=this.nodeDOM;e;e=e.parentNode)if(e==t)return!0;return!1}domFromPos(t){return{node:this.nodeDOM,offset:t}}localPosFromDOM(t,e,n){if(t==this.nodeDOM)return this.posAtStart+Math.min(e,this.node.text.length);return super.localPosFromDOM(t,e,n)}ignoreMutation(t){return t.type!="characterData"&&t.type!="selection"}slice(t,e,n){let r=this.node.cut(t,e),i=document.createTextNode(r.text);return new Pr(this.parent,r,this.outerDeco,this.innerDeco,i,i)}markDirty(t,e){if(super.markDirty(t,e),this.dom!=this.nodeDOM&&(t==0||e==this.nodeDOM.nodeValue.length))this.dirty=Yt}get domAtom(){return!1}isText(t){return this.node.text==t}}class Yi extends bn{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==$t&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Wl extends Ce{constructor(t,e,n,r,i,o,s,l){super(t,e,n,r,i,o,s);this.spec=l}update(t,e,n,r){if(this.dirty==Yt)return!1;if(this.spec.update&&(this.node.type==t.type||this.spec.multiType)){let i=this.spec.update(t,e,n);if(i)this.updateInner(t,e,n,r);return i}else if(!this.contentDOM&&!t.isLeaf)return!1;else return super.update(t,e,n,r)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(t,e,n,r){this.spec.setSelection?this.spec.setSelection(t,e,n.root):super.setSelection(t,e,n,r)}destroy(){if(this.spec.destroy)this.spec.destroy();super.destroy()}stopEvent(t){return this.spec.stopEvent?this.spec.stopEvent(t):!1}ignoreMutation(t){return this.spec.ignoreMutation?this.spec.ignoreMutation(t):super.ignoreMutation(t)}}function ql(t,e,n){let r=t.firstChild,i=!1;for(let o=0;o>1,s=Math.min(o,t.length);while(i-1){if(l>this.index)this.changed=!0,this.destroyBetween(this.index,l);this.top=this.top.children[this.index]}else{let d=Se.create(this.top,t[o],e,n);this.top.children.splice(this.index,0,d),this.top=d,this.changed=!0}this.index=0,o++}}findNodeMatch(t,e,n,r){let i=-1,o;if(r>=this.preMatch.index&&(o=this.preMatch.matches[r-this.preMatch.index]).parent==this.top&&o.matchesNode(t,e,n))i=this.top.children.indexOf(o,this.index);else for(let s=this.index,l=Math.min(this.top.children.length,s+5);s0){let l;for(;;)if(r){let d=n.children[r-1];if(d instanceof Se)n=d,r=d.children.length;else{l=d,r--;break}}else if(n==e)break t;else r=n.parent.children.indexOf(n),n=n.parent;let c=l.node;if(!c)continue;if(c!=t.child(i-1))break;--i,o.set(l,i),s.push(l)}return{index:i,matched:o,matches:s.reverse()}}function Gd(t,e){return t.type.side-e.type.side}function Qd(t,e,n,r){let i=e.locals(t),o=0;if(i.length==0){for(let d=0;do)l.push(i[s++]);let g=o+p.nodeSize;if(p.isText){let y=g;if(s!y.inline):l.slice();r(p,b,e.forChild(o,p),m),o=g}}function Zd(t){if(t.nodeName=="UL"||t.nodeName=="OL"){let e=t.style.cssText;t.style.cssText=e+"; list-style: square !important",window.getComputedStyle(t).listStyle,t.style.cssText=e}}function tu(t,e,n,r){for(let i=0,o=0;i=n){if(o>=r&&c.slice(r-e.length-l,r-l)==e)return r-e.length;let d=l=0&&d+e.length+l>=n)return l+d;if(n==r&&c.length>=r+e.length-l&&c.slice(r-l,r-l+e.length)==e)return r}}return-1}function qi(t,e,n,r,i){let o=[];for(let s=0,l=0;s=n||f<=e)o.push(c);else{if(dn)o.push(c.slice(n-d,c.size,r))}}return o}function Xi(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let i=t.docView.nearestDesc(n.focusNode),o=i&&i.size==0,s=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(s<0)return null;let l=r.resolve(s),c,d;if(Rr(n)){c=s;while(i&&!i.node)i=i.parent;if(i&&i.node.isAtom&&T.isSelectable(i.node)&&i.parent&&!(i.node.isInline&&Ed(n.focusNode,n.focusOffset,i.dom))){let h=i.posBefore;d=new T(s==h?l:r.resolve(h))}else if(zt&&e=="key"&&s>t.state.selection.to&&E(n.focusNode)&&n.focusOffset==n.focusNode.childNodes.length&&i&&i.posAtStart>t.state.selection.to)for(let h=n.focusNode;;h=h.parentNode){if(getComputedStyle(h).overflow!="visible"){d=F.findFrom(r.resolve(i.posAtStart),1);break}if(h==i.dom||h.nextSibling||!h.parentNode||!E(h.parentNode))break}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let h=s,p=s;for(let m=0;m{if(n.anchorNode!=r||n.anchorOffset!=i)e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{if(!jl(t)||t.state.selection.visible)t.dom.classList.remove("ProseMirror-hideselection")},20)})}function nu(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";if(r)e.collapse(n.parentNode,bt(n)+1);else e.collapse(n,0);if(!r&&!t.state.selection.visible&&Lt&&ve<=11)n.disabled=!0,n.disabled=!1}function Hl(t,e){if(e instanceof T){let n=t.docView.descAt(e.from);if(n!=t.lastSelectedViewDesc){if(hl(t),n)n.selectNode();t.lastSelectedViewDesc=n}}else hl(t)}function hl(t){if(t.lastSelectedViewDesc){if(t.lastSelectedViewDesc.parent)t.lastSelectedViewDesc.deselectNode();t.lastSelectedViewDesc=void 0}}function Gi(t,e,n,r){return t.someProp("createSelectionBetween",(i)=>i(t,e,n))||R.between(e,n,r)}function pl(t){if(t.editable&&!t.hasFocus())return!1;return Kl(t)}function Kl(t){let e=t.domSelectionRange();if(!e.anchorNode)return!1;try{return Ge(t.dom,e.anchorNode)&&(t.editable||Ge(t.dom,e.focusNode))}catch(n){return!1}}function ru(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Xe(e.node,e.offset,n.anchorNode,n.anchorOffset)}function Ui(t,e){let{$anchor:n,$head:r}=t.selection,i=e>0?n.max(r):n.min(r),o=!i.parent.inlineContent?i:i.depth?t.doc.resolve(e>0?i.after():i.before()):null;return o&&F.findFrom(o,e)}function xe(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function _l(t,e,n){let r=t.state.selection;if(r instanceof R){if(n.indexOf("s")>-1){let{$head:i}=r,o=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!o||o.isText||!o.isLeaf)return!1;let s=t.state.doc.resolve(i.pos+o.nodeSize*(e<0?-1:1));return xe(t,new R(r.$anchor,s))}else if(!r.empty)return!1;else if(t.endOfTextblock(e>0?"forward":"backward")){let i=Ui(t.state,e);if(i&&i instanceof T)return xe(t,i);return!1}else if(!Ut||n.indexOf("m")<0){let i=r.$head,o=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,s;if(!o||o.isText)return!1;let l=e<0?i.pos-o.nodeSize:i.pos;if(!(o.isAtom||(s=t.docView.descAt(l))&&!s.contentDOM))return!1;if(T.isSelectable(o))return xe(t,new T(e<0?t.state.doc.resolve(i.pos-o.nodeSize):i));else return xe(t,new R(t.state.doc.resolve(e<0?l:l+o.nodeSize)))}}else if(r instanceof T&&r.node.isInline)return xe(t,new R(e>0?r.$to:r.$from));else{let i=Ui(t.state,e);if(i)return xe(t,i);return!1}}function jn(t,e){let n=t.pmViewDesc;return n?n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR"):E(t)&&t.contentEditable=="false"}function pn(t,e){return e<0?iu(t):ou(t)}function iu(t){let e=t.domSelectionRange(),{focusNode:n,focusOffset:r}=e;if(!n)return;let i,o,s=!1;if(zt&&E(n)&&r0){if(!E(n))break;let l=n.childNodes[r-1];if(jn(l,-1))i=n,o=--r;else if(pt(l))n=l,r=n.nodeValue.length;else break}else if(Yl(n))break;else{let l=n.previousSibling;while(l&&jn(l,-1))i=n.parentNode,o=bt(l),l=l.previousSibling;if(!l){if(n=n.parentNode,n==t.dom)break;r=0}else n=l,r=It(n)}if(s)$i(t,n,r);else if(i)$i(t,i,o)}function ou(t){let e=t.domSelectionRange(),{focusNode:n,focusOffset:r}=e;if(!n)return;let i=It(n),o,s;for(;;)if(r{if(t.state==o)ue(t)},50)}function gl(t,e){let n=t.state.doc.resolve(e);if(!(wt||Tl)&&n.parent.inlineContent){let o=t.coordsAtPos(e);if(e>n.start()){let s=t.coordsAtPos(e-1),l=(s.top+s.bottom)/2;if(l>o.top&&l1)return s.lefto.top&&l1)return s.left>o.left?"ltr":"rtl"}}let r=t.dom;for(let o=n.depth;o>0;o--)if(n.node(o).isBlock){r=t.nodeDOM(n.before(o))||r;break}return getComputedStyle(r).direction=="rtl"?"rtl":"ltr"}function ml(t,e,n){let r=t.state.selection;if(r instanceof R&&!r.empty||n.indexOf("s")>-1)return!1;if(Ut&&n.indexOf("m")>-1)return!1;let{$from:i,$to:o}=r;if(!i.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let s=Ui(t.state,e);if(s&&s instanceof T)return xe(t,s)}if(!i.parent.inlineContent){let s=e<0?i:o,l=r instanceof Ct?F.near(s,e):F.findFrom(s,e);return l?xe(t,l):!1}return!1}function bl(t,e){if(!(t.state.selection instanceof R))return!0;let{$head:n,$anchor:r,empty:i}=t.state.selection;if(!n.sameParent(r))return!0;if(!i)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let o=!n.textOffset&&(e<0?n.nodeBefore:n.nodeAfter);if(o&&!o.isText){let s=t.state.tr;if(e<0)s.delete(n.pos-o.nodeSize,n.pos);else s.delete(n.pos,n.pos+o.nodeSize);return t.dispatch(s),!0}return!1}function wl(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function au(t){if(!vt||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(e&&E(e)&&n==0&&e.firstChild&&E(e.firstChild)&&e.firstChild.contentEditable=="false"){let r=e.firstChild;wl(t,r,"true"),setTimeout(()=>wl(t,r,"false"),20)}return!1}function cu(t){let e="";if(t.ctrlKey)e+="c";if(t.metaKey)e+="m";if(t.altKey)e+="a";if(t.shiftKey)e+="s";return e}function du(t,e){let n=e.keyCode,r=cu(e);if(n==8||Ut&&n==72&&r=="c")return bl(t,-1)||pn(t,-1);else if(n==46&&!e.shiftKey||Ut&&n==68&&r=="c")return bl(t,1)||pn(t,1);else if(n==13||n==27)return!0;else if(n==37||Ut&&n==66&&r=="c"){let i=n==37?gl(t,t.state.selection.from)=="ltr"?-1:1:-1;return _l(t,i,r)||pn(t,i)}else if(n==39||Ut&&n==70&&r=="c"){let i=n==39?gl(t,t.state.selection.from)=="ltr"?1:-1:1;return _l(t,i,r)||pn(t,i)}else if(n==38||Ut&&n==80&&r=="c")return ml(t,-1,r)||pn(t,-1);else if(n==40||Ut&&n==78&&r=="c")return au(t)||ml(t,1,r)||pn(t,1);else if(r==(Ut?"m":"c")&&(n==66||n==73||n==89||n==90))return!0;return!1}function Qi(t,e){t.someProp("transformCopied",(m)=>{e=m(e,t)});let n=[],{content:r,openStart:i,openEnd:o}=e;while(i>1&&o>1&&r.childCount==1&&r.firstChild.childCount==1){i--,o--;let m=r.firstChild;n.push(m.type.name,m.attrs!=m.type.defaultAttrs?m.attrs:null),r=m.content}let s=t.someProp("clipboardSerializer")||Ve.fromSchema(t.state.schema),l=ea(),c=l.createElement("div");c.appendChild(s.serializeFragment(r,{document:l}));let d=c.firstChild,f,h=0;while(d&&E(d)&&(f=ta[d.nodeName.toLowerCase()])){for(let m=f.length-1;m>=0;m--){let g=l.createElement(f[m]);while(c.firstChild)g.appendChild(c.firstChild);c.appendChild(g),h++}d=c.firstChild}if(d&&E(d))d.setAttribute("data-pm-slice",`${i} ${o}${h?` -${h}`:""} ${JSON.stringify(n)}`);let p=t.someProp("clipboardTextSerializer",(m)=>m(e,t))||e.content.textBetween(0,e.content.size,` + +`);return{dom:c,text:p,slice:e}}function Xl(t,e,n,r,i){let o=i.parent.type.spec.code,s,l;if(!n&&!e)return null;let c=!!e&&(r||o||!n);if(c){if(t.someProp("transformPastedText",(p)=>{e=p(e,o||r,t)}),o)return l=new I(k.from(t.state.schema.text(e.replace(/\r\n?/g,` +`))),0,0),t.someProp("transformPasted",(p)=>{l=p(l,t,!0)}),l;let h=t.someProp("clipboardTextParser",(p)=>p(e,i,r,t));if(h)l=h;else{let p=i.marks(),{schema:m}=t.state,g=Ve.fromSchema(m);s=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach((b)=>{let y=s.appendChild(document.createElement("p"));if(b)y.appendChild(g.serializeNode(m.text(b,p)))})}}else if(t.someProp("transformPastedHTML",(h)=>{n=h(n,t)}),s=pu(n),Lr)_u(s);let d=s&&s.querySelector("[data-pm-slice]"),f=d&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(d.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let h=+f[3];h>0;h--){let p=s.firstChild;while(p&&!E(p))p=p.nextSibling;if(!p)break;s=p}if(!l)l=(t.someProp("clipboardParser")||t.someProp("domParser")||rn.fromSchema(t.state.schema)).parseSlice(s,{preserveWhitespace:!!(c||f),context:i,ruleFromNode(p){if(p.nodeName=="BR"&&!p.nextSibling&&p.parentNode&&!uu.test(p.parentNode.nodeName))return{ignore:!0};return null}});if(f)l=gu(yl(l,+f[1],+f[2]),f[4]);else if(l=I.maxOpen(fu(l.content,i),!0),l.openStart||l.openEnd){let h=0,p=0;for(let m=l.content.firstChild;h{l=h(l,t,c)}),l}var uu=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function fu(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let i=e.node(n).contentMatchAt(e.index(n)),o,s=[];if(t.forEach((l)=>{if(!s)return;let c=i.findWrapping(l.type),d;if(!c)return s=null;if(d=s.length&&o.length&&Ql(c,o,l,s[s.length-1],0))s[s.length-1]=d;else{if(s.length)s[s.length-1]=Zl(s[s.length-1],o.length);let f=Gl(l,c);s.push(f),i=i.matchType(f.type),o=c}}),s)return k.from(s)}return t}function Gl(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,k.from(t));return t}function Ql(t,e,n,r,i){if(i1)o=0;if(i=n)l=e<0?s.contentMatchAt(0).fillBefore(l,o<=i).append(l):l.append(s.contentMatchAt(s.childCount).fillBefore(k.empty,!0));return t.replaceChild(e<0?0:t.childCount-1,s.copy(l))}function yl(t,e,n){if(en})}return $n.createHTML(t)}function pu(t){let e=/^(\s*]*>)*/.exec(t);if(e)t=t.slice(e[0].length);let n=ea(),r=n.body,i=/<([a-z][^>\s]+)/i.exec(t),o;if(o=i&&ta[i[1].toLowerCase()])t=o.map((s)=>"<"+s+">").join("")+t+o.map((s)=>"").reverse().join("");if(r.innerHTML=hu(t),o)for(let s=0;s=0;l-=2){let c=n.nodes[r[l]];if(!c||c.hasRequiredAttrs())break;try{i=k.from(c.create(r[l+1],i))}catch(d){break}o++,s++}return new I(i,o,s)}var Ot={},Mt={},mu={touchstart:!0,touchmove:!0};class na{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-200000000,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function bu(t){for(let e in Ot){let n=Ot[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=(r)=>{if(yu(t,r)&&!Zi(t,r)&&(t.editable||!(r.type in Mt)))n(t,r)},mu[e]?{passive:!0}:void 0)}if(vt)t.dom.addEventListener("input",()=>null);ji(t)}function de(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function wu(t){if(t.input.mouseDown)t.input.mouseDown.done();t.domObserver.stop();for(let e in t.input.eventHandlers)t.dom.removeEventListener(e,t.input.eventHandlers[e]);clearTimeout(t.input.composingTimeout),clearTimeout(t.input.lastIOSEnterFallbackTimeout)}function ji(t){t.someProp("handleDOMEvents",(e)=>{for(let n in e)if(!t.input.eventHandlers[n])t.dom.addEventListener(n,t.input.eventHandlers[n]=(r)=>Zi(t,r))})}function Zi(t,e){return t.someProp("handleDOMEvents",(n)=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function yu(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let n=e.target;n!=t.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(e))return!1;return!0}function ku(t,e){if(!Zi(t,e)&&Ot[e.type]&&(t.editable||!(e.type in Mt)))Ot[e.type](t,e)}Mt.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,la(t))return;if(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),ce&&wt&&n.keyCode==13)return;if(n.keyCode!=229)t.domObserver.forceFlush();if(mn&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();t.input.lastIOSEnter=r,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{if(t.input.lastIOSEnter==r)t.someProp("handleKeyDown",(i)=>i(t,Je(13,"Enter"))),t.input.lastIOSEnter=0},200)}else if(t.someProp("handleKeyDown",(r)=>r(t,n))||du(t,n))n.preventDefault();else de(t,"key")};Mt.keyup=(t,e)=>{if(e.keyCode==16)t.input.shiftKey=!1};Mt.keypress=(t,e)=>{let n=e;if(la(t)||!n.charCode||n.ctrlKey&&!n.altKey||Ut&&n.metaKey)return;if(t.someProp("handleKeyPress",(i)=>i(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof R)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(n.charCode),o=()=>t.state.tr.insertText(i).scrollIntoView();if(!/[\r\n]/.test(i)&&!t.someProp("handleTextInput",(s)=>s(t,r.$from.pos,r.$to.pos,i,o)))t.dispatch(o());n.preventDefault()}};function Gn(t){return{left:t.clientX,top:t.clientY}}function xu(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function to(t,e,n,r,i){if(r==-1)return!1;let o=t.state.doc.resolve(r);for(let s=o.depth+1;s>0;s--)if(t.someProp(e,(l)=>s>o.depth?l(t,n,o.nodeAfter,o.before(s),i,!0):l(t,n,o.node(s),o.before(s),i,!1)))return!0;return!1}function Qn(t,e,n){if(!t.focused)t.focus();if(t.state.selection.eq(e))return;let r=t.state.tr.setSelection(e);r.setMeta("pointer",!0),t.dispatch(r)}function Iu(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;if(r&&r.isAtom&&T.isSelectable(r))return Qn(t,new T(n)),!0;return!1}function vu(t,e){if(e==-1)return!1;let n=t.state.selection,r,i;if(n instanceof T)r=n.node;let o=t.state.doc.resolve(e);for(let s=o.depth+1;s>0;s--){let l=s>o.depth?o.nodeAfter:o.node(s);if(T.isSelectable(l)){if(r&&n.$from.depth>0&&s>=n.$from.depth&&o.before(n.$from.depth+1)==n.$from.pos)i=o.before(n.$from.depth);else i=o.before(s);break}}if(i!=null)return Qn(t,T.create(t.state.doc,i)),!0;else return!1}function Su(t,e,n,r,i){return to(t,"handleClickOn",e,n,r)||t.someProp("handleClick",(o)=>o(t,e,r))||(i?vu(t,n):Iu(t,n))}function Cu(t,e,n,r){return to(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",(i)=>i(t,e,r))}function Ou(t,e,n,r){return to(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",(i)=>i(t,e,r))||Mu(t,n,r)}function Mu(t,e,n){if(n.button!=0)return!1;let r=ra(t,e,!0),i=t.state.doc;if(!r)return!1;if(Qn(t,r),r instanceof R&&i.eq(t.state.doc))t.input.mouseDown=new sa(t,r);return!0}function ra(t,e,n){let r=t.state.doc;if(e==-1)return r.inlineContent?R.create(r,0,r.content.size):null;let i=r.resolve(e);for(let o=i.depth+1;o>0;o--){let s=o>i.depth?i.nodeAfter:i.node(o),l=i.before(o);if(s.inlineContent)return R.create(r,l+1,l+1+s.content.size);else if(n&&T.isSelectable(s))return T.create(r,l)}return null}function eo(t){return Er(t)}var ia=Ut?"metaKey":"ctrlKey";Ot.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=eo(t),i=Date.now(),o="singleClick";if(i-t.input.lastClick.time<500&&xu(n,t.input.lastClick)&&!n[ia]&&t.input.lastClick.button==n.button){if(t.input.lastClick.type=="singleClick")o="doubleClick";else if(t.input.lastClick.type=="doubleClick")o="tripleClick"}if(t.input.lastClick={time:i,x:n.clientX,y:n.clientY,type:o,button:n.button},t.input.mouseDown)t.input.mouseDown.done();let s=t.posAtCoords(Gn(n));if(!s)return;if(o=="singleClick")t.input.mouseDown=new oa(t,s,n,!!r);else if((o=="doubleClick"?Cu:Ou)(t,s.pos,s.inside,n))n.preventDefault();else de(t,"pointer")};class no{constructor(t){this.view=t,this.mightDrag=null,t.root.addEventListener("mouseup",this.up=this.up.bind(this)),t.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(t){this.done()}move(t){if(t.buttons==0)this.done()}done(){if(this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this)this.view.input.mouseDown=null}delaySelUpdate(){return!1}}class oa extends no{constructor(t,e,n,r){super(t);this.pos=e,this.event=n,this.flushed=r,this.delayedSelectionSync=!1,this.startDoc=t.state.doc,this.selectNode=!!n[ia],this.allowDefault=n.shiftKey;let i,o;if(e.inside>-1)i=t.state.doc.nodeAt(e.inside),o=e.inside;else{let d=t.state.doc.resolve(e.pos);i=d.parent,o=d.depth?d.before():0}let s=r?null:n.target,l=s?t.docView.nearestDesc(s,!0):null;this.target=l&&E(l.nodeDOM)?l.nodeDOM:null;let{selection:c}=t.state;if(n.button==0&&(i.type.spec.draggable&&i.type.spec.selectable!==!1||c instanceof T&&c.from<=o&&c.to>o))this.mightDrag={node:i,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&zt&&!this.target.hasAttribute("contentEditable"))};if(this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)){if(this.view.domObserver.stop(),this.mightDrag.addAttr)this.target.draggable=!0;if(this.mightDrag.setUneditable)setTimeout(()=>{if(this.view.input.mouseDown==this)this.target.setAttribute("contentEditable","false")},20);this.view.domObserver.start()}de(t,"pointer")}done(){if(super.done(),this.mightDrag&&this.target){if(this.view.domObserver.stop(),this.mightDrag.addAttr)this.target.removeAttribute("draggable");if(this.mightDrag.setUneditable)this.target.removeAttribute("contentEditable");this.view.domObserver.start()}if(this.delayedSelectionSync)setTimeout(()=>{if(!this.view.isDestroyed)ue(this.view)})}up(t){if(this.done(),!this.view.dom.contains(t.target))return;let e=this.pos;if(this.view.state.doc!=this.startDoc)e=this.view.posAtCoords(Gn(t));if(this.updateAllowDefault(t),this.allowDefault||!e)de(this.view,"pointer");else if(Su(this.view,e.pos,e.inside,t,this.selectNode))t.preventDefault();else if(t.button==0&&(this.flushed||vt&&this.mightDrag&&!this.mightDrag.node.isAtom||wt&&!this.view.state.selection.visible&&Math.min(Math.abs(e.pos-this.view.state.selection.from),Math.abs(e.pos-this.view.state.selection.to))<=2))Qn(this.view,F.near(this.view.state.doc.resolve(e.pos))),t.preventDefault();else de(this.view,"pointer")}move(t){this.updateAllowDefault(t),de(this.view,"pointer"),super.move(t)}updateAllowDefault(t){if(!this.allowDefault&&(Math.abs(this.event.x-t.clientX)>4||Math.abs(this.event.y-t.clientY)>4))this.allowDefault=!0}delaySelUpdate(){if(!this.allowDefault)return!1;return this.delayedSelectionSync=!0,!0}}class sa extends no{constructor(t,e){super(t);this.startSelection=e,this.startDoc=t.state.doc}move(t){if(t.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}t.preventDefault(),de(this.view,"pointer");let e=this.view.posAtCoords(Gn(t)),n=e&&ra(this.view,e.inside,!1);if(!n)return;let{doc:r}=this.view.state,i=this.startSelection,[o,s]=n.from{t.input.lastTouch=Date.now(),eo(t),de(t,"pointer")};Ot.touchmove=(t)=>{t.input.lastTouch=Date.now(),de(t,"pointer")};Ot.contextmenu=(t)=>eo(t);function la(t,e){if(t.composing)return!0;if(vt&&Math.abs(Date.now()-t.input.compositionEndedAt)<500)return t.input.compositionEndedAt=-200000000,!0;return!1}var Au=ce?5000:-1;Mt.compositionstart=Mt.compositionupdate=(t)=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof R&&e.selection.empty&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some((r)=>r.type.spec.inclusive===!1)||wt&&Tl&&Eu(t)))t.markCursor=t.state.storedMarks||n.marks(),Er(t,!0),t.markCursor=null;else if(Er(t,!e.selection.empty),zt&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=t.domSelectionRange();for(let{focusNode:i,focusOffset:o}=r;i&&E(i)&&o!=0;){let s=o<0?i.lastChild:i.childNodes[o-1];if(!s)break;if(pt(s)){let l=t.domSelection();if(l)l.collapse(s,s.nodeValue.length);break}else i=s,o=-1}}t.input.composing=!0}aa(t,Au)};function Eu(t){let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(!e||!E(e)||n>=e.childNodes.length)return!1;let r=e.childNodes[n];return E(r)&&r.contentEditable=="false"}Mt.compositionend=(t,e)=>{if(t.composing){if(t.input.composing=!1,t.input.compositionEndedAt=Date.now(),t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.badSafariComposition)t.domObserver.forceFlush();else if(t.input.compositionPendingChanges)Promise.resolve().then(()=>t.domObserver.flush());t.input.compositionID++,aa(t,20)}};function aa(t,e){if(clearTimeout(t.input.composingTimeout),e>-1)t.input.composingTimeout=setTimeout(()=>Er(t),e)}function ca(t){if(t.composing)t.input.composing=!1,t.input.compositionEndedAt=Date.now();while(t.input.compositionNodes.length>0)t.input.compositionNodes.pop().markParentsDirty()}function Nu(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=Md(e.focusNode,e.focusOffset),r=Ad(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let i=r.pmViewDesc,o=t.domObserver.lastChangedTextNode;if(n==o||r==o)return o;if(!i||!i.isText(r.nodeValue))return r;else if(t.input.compositionNode==r){let s=n.pmViewDesc;if(!(!s||!s.isText(n.nodeValue)))return r}}return n||r}function Er(t,e=!1){if(ce&&t.domObserver.flushingSoon>=0)return;if(t.domObserver.forceFlush(),ca(t),e||t.docView&&t.docView.dirty){let n=Xi(t),r=t.state.selection;if(n&&!n.eq(r))t.dispatch(t.state.tr.setSelection(n));else if((t.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent)t.dispatch(t.state.tr.deleteSelection());else t.updateState(t.state);return!0}return!1}function Du(t,e){if(!t.dom.parentNode)return;let n=t.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(e),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{if(n.parentNode)n.parentNode.removeChild(n);t.focus()},50)}var Hn=Lt&&ve<15||mn&&Td<604;Ot.copy=Mt.cut=(t,e)=>{let n=e,r=t.state.selection,i=n.type=="cut";if(r.empty)return;let o=Hn?null:n.clipboardData,s=r.content(),{dom:l,text:c}=Qi(t,s);if(o)n.preventDefault(),o.clearData(),o.setData("text/html",l.innerHTML),o.setData("text/plain",c);else Du(t,l);if(i)t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Tu(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function Ru(t,e){if(!t.dom.parentNode)return;let n=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,r=t.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));if(!n)r.contentEditable="true";r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{if(t.focus(),r.parentNode)r.parentNode.removeChild(r);if(n)Kn(t,r.value,null,i,e);else Kn(t,r.textContent,r.innerHTML,i,e)},50)}function Kn(t,e,n,r,i){let o=Xl(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",(c)=>c(t,i,o||I.empty)))return!0;if(!o)return!1;let s=Tu(o),l=s?t.state.tr.replaceSelectionWith(s,r):t.state.tr.replaceSelection(o);return t.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function da(t){let e=t.getData("text/plain")||t.getData("Text");if(e)return e;let n=t.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Mt.paste=(t,e)=>{let n=e;if(t.composing&&!ce)return;let r=Hn?null:n.clipboardData,i=t.input.shiftKey&&t.input.lastKeyCode!=45;if(r&&Kn(t,da(r),r.getData("text/html"),i,n))n.preventDefault();else Ru(t,n)};class ro{constructor(t,e,n){this.slice=t,this.move=e,this.node=n}}var Lu=Ut?"altKey":"ctrlKey";function ua(t,e){let n;return t.someProp("dragCopies",(r)=>{n=n||r(e)}),n!=null?!n:!e[Lu]}Ot.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r)r.done();if(!n.dataTransfer)return;let i=t.state.selection,o=i.empty?null:t.posAtCoords(Gn(n)),s;if(o&&o.pos>=i.from&&o.pos<=(i instanceof T?i.to-1:i.to));else if(r&&r.mightDrag)s=T.create(t.state.doc,r.mightDrag.pos);else if(n.target&&E(n.target)){let h=t.docView.nearestDesc(n.target,!0);if(h&&h.node.type.spec.draggable&&h!=t.docView)s=T.create(t.state.doc,h.posBefore)}let l=(s||t.state.selection).content(),{dom:c,text:d,slice:f}=Qi(t,l);if(!n.dataTransfer.files.length||!wt||Dl>120)n.dataTransfer.clearData();if(n.dataTransfer.setData(Hn?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",!Hn)n.dataTransfer.setData("text/plain",d);t.dragging=new ro(f,ua(t,n),s)};Ot.dragend=(t)=>{let e=t.dragging;window.setTimeout(()=>{if(t.dragging==e)t.dragging=null},50)};Mt.dragover=Mt.dragenter=(t,e)=>e.preventDefault();Mt.drop=(t,e)=>{try{Pu(t,e,t.dragging)}finally{t.dragging=null}};function Pu(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(Gn(e));if(!r)return;let i=t.state.doc.resolve(r.pos),o=n&&n.slice;if(o)t.someProp("transformPasted",(m)=>{o=m(o,t,!1)});else o=Xl(t,da(e.dataTransfer),Hn?null:e.dataTransfer.getData("text/html"),!1,i);let s=!!(n&&ua(t,e));if(t.someProp("handleDrop",(m)=>m(t,e,o||I.empty,s))){e.preventDefault();return}if(!o)return;e.preventDefault();let l=o?vr(t.state.doc,i.pos,o):i.pos;if(l==null)l=i.pos;let c=t.state.tr;if(s){let{node:m}=n;if(m)m.replace(c);else c.deleteSelection()}let d=c.mapping.map(l),f=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,h=c.doc;if(f)c.replaceRangeWith(d,d,o.content.firstChild);else c.replaceRange(d,d,o);if(c.doc.eq(h))return;let p=c.doc.resolve(d);if(f&&T.isSelectable(o.content.firstChild)&&p.nodeAfter&&p.nodeAfter.sameMarkup(o.content.firstChild))c.setSelection(new T(p));else{let m=c.mapping.map(l);c.mapping.maps[c.mapping.maps.length-1].forEach((g,b,y,S)=>m=S),c.setSelection(Gi(t,p,c.doc.resolve(m)))}t.focus(),t.dispatch(c.setMeta("uiEvent","drop"))}Ot.focus=(t)=>{if(t.input.lastFocus=Date.now(),!t.focused)t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout(()=>{if(t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange()))ue(t)},20)};Ot.blur=(t,e)=>{let n=e;if(t.focused){if(t.domObserver.stop(),t.dom.classList.remove("ProseMirror-focused"),t.domObserver.start(),n.relatedTarget&&t.dom.contains(n.relatedTarget))t.domObserver.currentSelection.clear();t.focused=!1}};Ot.beforeinput=(t,e)=>{if(ce&&e.inputType=="deleteContentBackward"){t.domObserver.flushSoon();let{domChangeCount:r}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=r)return;if(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",(o)=>o(t,Je(8,"Backspace"))))return;let{$cursor:i}=t.state.selection;if(i&&i.pos>0)t.dispatch(t.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let t in Mt)Ot[t]=Mt[t];function Yn(t,e){if(t==e)return!0;for(let n in t)if(t[n]!==e[n])return!1;for(let n in e)if(!(n in t))return!1;return!0}class Nr{constructor(t){this.frag=t,this.index=0,this.off=0}nodeAt(t){while(this.off<=t&&this.index=o?null:new _t(i,o,this)}valid(t,e){return e.from=t&&(!i||i(s.spec)))n.push(s.copy(s.from+r,s.to+r))}for(let o=0;ot){let s=this.children[o]+1;this.children[o+2].findInner(t-s,e-s,n,r+s,i)}}map(t,e,n){if(this==xt||t.maps.length==0)return this;return this.mapInner(t,e,0,0,n||Ke)}mapInner(t,e,n,r,i){let o;if(this.local.length){let s=new Nr(e.content);for(let l=0;l{let c=l+n,d;if(!(d=ha(e,s,c)))return;if(!r)r=this.children.slice();while(is&&f.to=t){if(this.children[s]==t)n=this.children[s+2];break}let i=t+1,o=i+e.content.size;for(let s=0;si&&l.type instanceof Oe){let c=Math.max(i,l.from)-i,d=Math.min(o,l.to)-i;if(cr.map(t,e,Ke));return Ie.from(n)}forChild(t,e){if(e.isLeaf)return G.empty;let n=[];for(let r=0;re instanceof G)?t:t.reduce((e,n)=>e.concat(n instanceof G?n:n.members),[]))}}forEachSet(t){for(let e=0;e{let y=b-g-(m-p);for(let S=0;SL+f-h)continue;let U=l[S]+f-h;if(m>=U)l[S+1]=p<=U?-2:-1;else if(p>=f&&y)l[S]+=y,l[S+1]+=y}h+=y}),f=n.maps[d].map(f,-1)}let c=!1;for(let d=0;d=r.content.size){c=!0;continue}let p=n.map(t[d+1]+o,-1),m=p-i,{index:g,offset:b}=r.content.findIndex(h),y=r.maybeChild(g);if(y&&b==h&&b+y.nodeSize==m){let S=l[d+2].mapInner(n,y,f+1,t[d]+o+1,s);if(S!=xt)l[d]=h,l[d+1]=m,l[d+2]=S;else l[d+1]=-2,c=!0}else c=!0}if(c){let d=zu(l,t,e,n,i,o,s),f=Tr(d,r,0,s);e=f.local;for(let h=0;hn&&s.to{let d=ha(t,l,c+n);if(d){o=!0;let f=Tr(d,l,n+c+1,r);if(f!=xt)i.push(c,c+l.nodeSize,f)}});let s=fa(o?pa(t):t,-n).sort(Ye);if(s.length){let l=new Nr(e.content);for(let c=0;c0)e++;t.splice(e,0,n)}function Ri(t){let e=[];if(t.someProp("decorations",(n)=>{let r=n(t.state);if(r&&r!=xt)e.push(r)}),t.cursorWrapper)e.push(G.create(t.state.doc,[t.cursorWrapper.deco]));return Ie.from(e)}var Fu={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Vu=Lt&&ve<=11;class _a{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(t){this.anchorNode=t.anchorNode,this.anchorOffset=t.anchorOffset,this.focusNode=t.focusNode,this.focusOffset=t.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(t){return t.anchorNode==this.anchorNode&&t.anchorOffset==this.anchorOffset&&t.focusNode==this.focusNode&&t.focusOffset==this.focusOffset}}class ga{constructor(t,e){if(this.view=t,this.handleDOMChange=e,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new _a,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver((n)=>{for(let r=0;rr.type=="childList"&&r.removedNodes.length||r.type=="characterData"&&r.oldValue.length>r.target.nodeValue.length))this.flushSoon();else if(vt&&t.composing&&n.some((r)=>r.type=="childList"&&r.target.nodeName=="TR"))t.input.badSafariComposition=!0,this.flushSoon();else this.flush()}),Vu)this.onCharData=(n)=>{this.queue.push({target:n.target,type:"characterData",oldValue:n.prevValue}),this.flushSoon()};this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){if(this.flushingSoon<0)this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20)}forceFlush(){if(this.flushingSoon>-1)window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush()}start(){if(this.observer)this.observer.takeRecords(),this.observer.observe(this.view.dom,Fu);if(this.onCharData)this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData);this.connectSelection()}stop(){if(this.observer){let t=this.observer.takeRecords();if(t.length){for(let e=0;ethis.flush(),20)}this.observer.disconnect()}if(this.onCharData)this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData);this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(!pl(this.view))return;if(this.suppressingSelectionUpdates)return ue(this.view);if(Lt&&ve<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&Xe(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset))return this.flushSoon()}this.flush()}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(t){if(!t.focusNode)return!0;let e=new Set,n;for(let i=t.focusNode;i;i=gn(i))e.add(i);for(let i=t.anchorNode;i;i=gn(i))if(e.has(i)){n=i;break}let r=n&&this.view.docView.nearestDesc(n);if(r&&r.ignoreMutation({type:"selection",target:pt(n)?n.parentNode:n}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let t of this.observer.takeRecords())this.queue.push(t);return this.queue}flush(){let{view:t}=this;if(!t.docView||this.flushingSoon>-1)return;let e=this.pendingRecords();if(e.length)this.queue=[];let n,r=!1;if(!this.suppressingSelectionUpdates&&pl(t))n=t.domSelectionRange(),r=!this.currentSelection.eq(n)&&!this.ignoreSelectionChange(n);let i=-1,o=-1,s=!1,l=[];if(t.editable)for(let d=0;dd.nodeName=="BR")&&(t.input.lastKeyCode==8||t.input.lastKeyCode==46||wt&&(t.composing||t.input.compositionEndedAt>Date.now()-50)&&e.some((d)=>d.type=="childList"&&d.removedNodes.length))){for(let d of l)if(d.nodeName=="BR"&&d.parentNode){let f=d.nextSibling;while(f&&E(f)){if(f.contentEditable=="false"){d.parentNode.removeChild(d);break}f=f.firstChild}}}else if(zt&&l.length){let d=l.filter((f)=>f.nodeName=="BR");if(d.length==2){let[f,h]=d;if(f.parentNode&&f.parentNode.parentNode==h.parentNode)h.remove();else f.remove()}else{let{focusNode:f}=this.currentSelection;for(let h of d){let p=h.parentNode;if(p&&p.nodeName=="LI"&&(!f||Uu(t,f)!=p))h.remove()}}}let c=null;if(i<0&&r&&t.input.lastFocus>Date.now()-200&&Math.max(t.input.lastTouch,t.input.lastClick.time)-1||r){if(i>-1)t.docView.markDirty(i,o),Wu(t);if(t.input.badSafariComposition)t.input.badSafariComposition=!1,$u(t,l);if(this.handleDOMChange(i,o,s,l),t.docView&&t.docView.dirty)t.updateState(t.state);else if(n&&!this.currentSelection.eq(n))ue(t);if(n)this.currentSelection.set(n)}}registerMutation(t,e){if(e.indexOf(t.target)>-1)return null;let n=this.view.docView.nearestDesc(t.target);if(t.type=="attributes"&&(n==this.view.docView||t.attributeName=="contenteditable"||t.attributeName=="style"&&!t.oldValue&&!t.target.getAttribute("style")))return null;if(!n||n.ignoreMutation(t))return null;if(t.type=="childList"){for(let d=0;do;S--){let L=i.childNodes[S-1],U=L.pmViewDesc;if(L.nodeName=="BR"&&!U){s=S;break}if(!U||U.size)break}let p=t.state.doc,m=t.someProp("domParser")||rn.fromSchema(t.state.schema),g=p.resolve(l),b=null,y=m.parse(i,{topNode:g.parent,topMatch:g.parent.contentMatchAt(g.index()),topOpen:!0,from:o,to:s,preserveWhitespace:g.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:ju(r),context:g});if(f&&f[0].pos!=null){let S=f[0].pos,L=f[1]&&f[1].pos;if(L==null)L=S;b={anchor:S+l,head:L+l}}return{doc:y,sel:b,from:l,to:c}}var ju=(t)=>(e)=>{let n=e.pmViewDesc;if(n)return n.parseRule(t);else if(e.nodeName=="BR"&&e.parentNode){if(vt&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||vt&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},Hu=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function Ku(t,e,n,r,i){let o=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let z=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,Y=Xi(t,z);if(Y&&!t.state.selection.eq(Y)){if(wt&&ce&&t.input.lastKeyCode===13&&Date.now()-100P(t,Je(13,"Enter"))))return;let Z=t.state.tr.setSelection(Y);if(z=="pointer")Z.setMeta("pointer",!0);else if(z=="key")Z.scrollIntoView();if(o)Z.setMeta("composition",o);t.dispatch(Z)}return}let s=t.state.doc.resolve(e),l=s.sharedDepth(n);e=s.before(l+1),n=t.state.doc.resolve(n).after(l+1);let c=t.state.selection,d=Ju(t,e,n,i),f=t.state.doc,h=f.slice(d.from,d.to),p,m;if(t.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ce)&&i.some((z)=>E(z)&&!Hu.test(z.nodeName))&&(!g||g.endA>=g.endB)&&t.someProp("handleKeyDown",(z)=>z(t,Je(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!g)if(r&&c instanceof R&&!c.empty&&c.$head.sameParent(c.$anchor)&&!t.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))g={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let z=Sl(t,t.state.doc,d.sel);if(z&&!z.eq(t.state.selection)){let Y=t.state.tr.setSelection(z);if(o)Y.setMeta("composition",o);t.dispatch(Y)}}return}if(t.state.selection.fromt.state.selection.from&&g.start<=t.state.selection.from+2&&t.state.selection.from>=d.from)g.start=t.state.selection.from;else if(g.endA=t.state.selection.to-2&&t.state.selection.to<=d.to)g.endB+=t.state.selection.to-g.endA,g.endA=t.state.selection.to}if(Lt&&ve<=11&&g.endB==g.start+1&&g.endA==g.start&&g.start>d.from&&d.doc.textBetween(g.start-d.from-1,g.start-d.from+1)=="  ")g.start--,g.endA--,g.endB--;let b=d.doc.resolveNoCache(g.start-d.from),y=d.doc.resolveNoCache(g.endB-d.from),S=f.resolve(g.start),L=b.sameParent(y)&&b.parent.inlineContent&&S.end()>=g.endA;if((mn&&t.input.lastIOSEnter>Date.now()-225&&(!L||i.some((z)=>z.nodeName=="DIV"||z.nodeName=="P"))||!L&&Gu(d.doc,b.pos,y.pos))&&t.someProp("handleKeyDown",(z)=>z(t,Je(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>g.start&&(L?g.endA>g.start&&g.endB==g.start:Xu(f,g.start,g.endA,b,y))&&t.someProp("handleKeyDown",(z)=>z(t,Je(8,"Backspace")))){if(ce&&wt)t.domObserver.suppressSelectionUpdates();return}if(wt&&g.endB==g.start)t.input.lastChromeDelete=Date.now();if(ce&&!L&&b.start()!=y.start()&&y.parentOffset==0&&b.depth==y.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==g.endA)g.endB-=2,y=d.doc.resolveNoCache(g.endB-d.from),setTimeout(()=>{t.someProp("handleKeyDown",function(z){return z(t,Je(13,"Enter"))})},20);let U=g.start,et=g.endA,at=(z)=>{let Y=z||t.state.tr.replace(U,et,d.doc.slice(g.start-d.from,g.endB-d.from));if(d.sel){let Z=Sl(t,Y.doc,d.sel);if(Z&&!(wt&&t.composing&&Z.empty&&(g.start!=g.endB||t.input.lastChromeDeleteue(t),20);let z=at(t.state.tr.delete(U,et)),Y=f.resolve(g.start).marksAcross(f.resolve(g.endA));if(Y)z.ensureMarks(Y);t.dispatch(z)}else if(g.endA==g.endB&&(Ft=Yu(b.parent.content.cut(b.parentOffset,y.parentOffset),S.parent.content.cut(S.parentOffset,g.endA-S.start())))){let z=at(t.state.tr);if(Ft.type=="add")z.addMark(U,et,Ft.mark);else z.removeMark(U,et,Ft.mark);t.dispatch(z)}else if(b.parent.child(b.index()).isText&&b.index()==y.index()-(y.textOffset?0:1)){let z=b.parent.textBetween(b.parentOffset,y.parentOffset),Y=()=>at(t.state.tr.insertText(z,U,et));if(!t.someProp("handleTextInput",(Z)=>Z(t,U,et,z,Y)))t.dispatch(Y())}else t.dispatch(at());else t.dispatch(at())}function Sl(t,e,n){if(Math.max(n.anchor,n.head)>e.content.size)return null;return Gi(t,e.resolve(n.anchor),e.resolve(n.head))}function Yu(t,e){let n=t.firstChild.marks,r=e.firstChild.marks,i=n,o=r,s,l,c;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&o.length==1)l=o[0],s="remove",c=(f)=>f.mark(l.removeFromSet(f.marks));else return null;let d=[];for(let f=0;fn||Li(s,!0,!1){if(o.isTextblock&&s>=e&&s0&&(e||t.indexAfter(r)==t.node(r).childCount))r--,i++,e=!1;if(n){let o=t.node(r).maybeChild(t.indexAfter(r));while(o&&!o.isLeaf)o=o.firstChild,i++}return i}function Qu(t,e,n,r,i){let o=t.findDiffStart(e,n),s=n+t.size,l=n+e.size;if(o==null)return null;let{a:c,b:d}=t.findDiffEnd(e,s,l);if(i=="end"){let f=Math.max(0,o-Math.min(c,d));r-=c+f-o}if(c=c?o-r:0;o-=f,d=o+(d-c),c=o}else if(d=d?o-r:0;o-=f,c=o+(c-d),d=o}return{start:o,endA:c,endB:d}}class Zn{constructor(t,e){if(this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new na,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=e,this.state=e.state,this.directPlugins=e.plugins||[],this.directPlugins.forEach(El),this.dispatch=this.dispatch.bind(this),this.dom=t&&t.mount||document.createElement("div"),t){if(t.appendChild)t.appendChild(this.dom);else if(typeof t=="function")t(this.dom);else if(t.mount)this.mounted=!0}this.editable=Ml(this),Ol(this),this.nodeViews=Al(this),this.docView=al(this.state.doc,Cl(this),Ri(this),this.dom,this),this.domObserver=new ga(this,(n,r,i,o)=>Ku(this,n,r,i,o)),this.domObserver.start(),bu(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let t=this._props;this._props={};for(let e in t)this._props[e]=t[e];this._props.state=this.state}return this._props}update(t){if(t.handleDOMEvents!=this._props.handleDOMEvents)ji(this);let e=this._props;if(this._props=t,t.plugins)t.plugins.forEach(El),this.directPlugins=t.plugins;this.updateStateInner(t.state,e)}setProps(t){let e={};for(let n in this._props)e[n]=this._props[n];e.state=this.state;for(let n in t)e[n]=t[n];this.update(e)}updateState(t){this.updateStateInner(t,this._props)}updateStateInner(t,e){var n;let r=this.state,i=!1,o=!1;if(t.storedMarks&&this.composing)ca(this),o=!0;this.state=t;let s=r.plugins!=t.plugins||this._props.plugins!=e.plugins;if(s||this._props.plugins!=e.plugins||this._props.nodeViews!=e.nodeViews){let p=Al(this);if(tf(p,this.nodeViews))this.nodeViews=p,i=!0}if(s||e.handleDOMEvents!=this._props.handleDOMEvents)ji(this);this.editable=Ml(this),Ol(this);let l=Ri(this),c=Cl(this),d=r.plugins!=t.plugins&&!r.doc.eq(t.doc)?"reset":t.scrollToSelection>r.scrollToSelection?"to selection":"preserve",f=i||!this.docView.matchesNode(t.doc,c,l);if(f||!t.selection.eq(r.selection))o=!0;let h=d=="preserve"&&o&&this.dom.style.overflowAnchor==null&&Pd(this);if(o){this.domObserver.stop();let p=f&&(Lt||wt)&&!this.composing&&!r.selection.empty&&!t.selection.empty&&Zu(r.selection,t.selection);if(f){let g=wt?this.trackWrites=this.domSelectionRange().focusNode:null;if(this.composing)this.input.compositionNode=Nu(this);if(i||!this.docView.update(t.doc,c,l,this))this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=al(t.doc,c,l,this.dom,this);if(g&&(!this.trackWrites||!this.dom.contains(this.trackWrites)))p=!0}let m=this.input.mouseDown;if(p||!(m&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&ru(this)&&m.delaySelUpdate()))ue(this,p);else Hl(this,t.selection),this.domObserver.setCurSelection();this.domObserver.start()}if(this.updatePluginViews(r),((n=this.dragging)===null||n===void 0?void 0:n.node)&&!r.doc.eq(t.doc))this.updateDraggedNode(this.dragging,r);if(d=="reset")this.dom.scrollTop=0;else if(d=="to selection")this.scrollToSelection();else if(h)Bd(h)}scrollToSelection(){let t=this.domSelectionRange().focusNode;if(!t||!Ge(this.dom,t));else if(this.someProp("handleScrollToSelection",(e)=>e(this)));else if(this.state.selection instanceof T){let e=this.docView.domAfterPos(this.state.selection.from);if(E(e))rl(this,e.getBoundingClientRect(),t)}else rl(this,this.coordsAtPos(this.state.selection.head,1),t)}destroyPluginViews(){let t;while(t=this.pluginViews.pop())if(t.destroy)t.destroy()}updatePluginViews(t){if(!t||t.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let e=0;e0&&ie.ownerDocument.getSelection();return this._root=e}}return t||document}updateRoot(){this._root=null}posAtCoords(t){return Ud(this,t)}coordsAtPos(t,e=1){return zl(this,t,e)}domAtPos(t,e=0){return this.docView.domFromPos(t,e)}nodeDOM(t){let e=this.docView.descAt(t);return e?e.nodeDOM:null}posAtDOM(t,e,n=-1){let r=this.docView.posFromDOM(t,e,n);if(r==null)throw RangeError("DOM position not inside the editor");return r}endOfTextblock(t,e){return Kd(this,e||this.state,t)}pasteHTML(t,e){return Kn(this,"",t,!1,e||new ClipboardEvent("paste"))}pasteText(t,e){return Kn(this,t,null,!0,e||new ClipboardEvent("paste"))}serializeForClipboard(t){return Qi(this,t)}destroy(){if(!this.docView)return;if(wu(this),this.destroyPluginViews(),this.mounted)this.docView.update(this.state.doc,[],Ri(this),this),this.dom.textContent="";else if(this.dom.parentNode)this.dom.parentNode.removeChild(this.dom);this.docView.destroy(),this.docView=null,Cd()}get isDestroyed(){return this.docView==null}dispatchEvent(t){return ku(this,t)}domSelectionRange(){let t=this.dom.isConnected!==!1&&this.domSelection();if(!t)return{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0};return vt&&this.root.nodeType===11&&Nd(this.dom.ownerDocument)==this.dom&&qu(this,t)||t}domSelection(){return this.root.getSelection()}}Zn.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;if(e)e.call(this,t);else this.updateState(this.state.apply(t))};function Cl(t){let e=Object.create(null);if(e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",(n)=>{if(typeof n=="function")n=n(t.state);if(n){for(let r in n)if(r=="class")e.class+=" "+n[r];else if(r=="style")e.style=(e.style?e.style+";":"")+n[r];else if(!e[r]&&r!="contenteditable"&&r!="nodeName")e[r]=String(n[r])}}),!e.translate)e.translate="no";return[_t.node(0,t.state.doc.content.size,e)]}function Ol(t){if(t.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),t.cursorWrapper={dom:e,deco:_t.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function Ml(t){return!t.someProp("editable",(e)=>e(t.state)===!1)}function Zu(t,e){let n=Math.min(t.$anchor.sharedDepth(t.head),e.$anchor.sharedDepth(e.head));return t.$anchor.start(n)!=e.$anchor.start(n)}function Al(t){let e=Object.create(null);function n(r){for(let i in r)if(!Object.prototype.hasOwnProperty.call(e,i))e[i]=r[i]}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function tf(t,e){let n=0,r=0;for(let i in t){if(t[i]!=e[i])return!0;n++}for(let i in e)r++;return n!=r}function El(t){if(t.spec.state||t.spec.filterTransaction||t.spec.appendTransaction)throw RangeError("Plugins passed directly to the view must not have a state component")}var so=Symbol("Equality");var nf=Object.keys;var lo=(t)=>nf(t).length;var ma=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var wn=(t,e)=>{if(t===e)return!0;if(t==null||e==null||t.constructor!==e.constructor&&(t.constructor||Object)!==(e.constructor||Object))return!1;if(t[so]!=null)return t[so](e);switch(t.constructor){case ArrayBuffer:t=new Uint8Array(t),e=new Uint8Array(e);case Uint8Array:{if(t.byteLength!==e.byteLength)return!1;for(let n=0;n{let n=0,r=0;while(n0&&of.test(t[n-1]))n--;while(r+n0&&sf.test(t[t.length-r]))r--;return{index:n,remove:t.length-n-r,insert:e.slice(n,e.length-r)}},ba=lf;var uo="doc",af="attributes",fo="children";var er=new WeakMap;function cf(t,e,n,r){let i=n.doc,o=r?t.getContainerById(r):t.getMap(uo),s=!1;if(o.get("nodeName")==null)t.commit(),s=!0,o.set("nodeName",i.type.name);if(tr(o,i,e),s)t.commit({origin:"sys:init"});else t.commit({origin:"loroSyncPlugin"})}function ho(t,e,n){let r=n.get(e.id)??null;if(r!=null)return r;if(e instanceof St){let i=qr(e),o=or(e),s=e.get("nodeName");if(s==null||typeof s!=="string")throw Error("Invalid nodeName");let l=o.toArray().flatMap((c)=>ho(t,c,n)).filter((c)=>c!==null);try{r=t.node(s,i.toJSON(),l),er.set(r,e.id)}catch(c){console.error(c)}}else if(e instanceof Rt){r=[];for(let i of e.toDelta()){if(i.insert==null)continue;try{let o=[];for(let[s,l]of Object.entries(i.attributes??{})){let c=Sa(l);o.push(t.mark(s,c??void 0))}r.push(t.text(i.insert,o))}catch(o){console.error(o)}}}else throw Error("Invalid LoroType");if(r!=null){if(!Array.isArray(r))er.set(r,e.id);n.set(e.id,r)}else n.delete(e.id);return r}function ao(t,e,n,r){return Array.isArray(n)?df(t,e,n,r):pf(t,e,n,r)}function df(t,e,n,r){let i=t.insertContainer(e??t.length,new Rt).getAttached(),o=n.map((s)=>({insert:s.text,attributes:va(s.marks)}));return i.applyDelta(o),r.set(i.id,n),i}function uf(t,e,n){n.set(t.id,e);let r=e.map((c)=>({insert:c.text,attributes:va(c.marks)})),{insert:i,remove:o,index:s}=ba(t.toString(),r.map((c)=>c.insert).join(""));if(o>0)t.delete(s,o);if(i.length)t.insert(s,i);let l=ff(t.toDelta(),r);if(l!=null)t.applyDelta(l)}function ff(t,e){let n=[],r=0,i=0,o=0,s=0;while(r0){let f=hf(l.attributes??{},c.attributes);n.push(f!=null?{retain:d,attributes:f}:{retain:d})}if(i+=d,i===l.insert.length)r+=1,i=0;if(s+=d,s===c.insert.length)o+=1,s=0}while(n.length>0&&n[n.length-1].attributes==null)n.pop();return n.length>0?n:null}function hf(t,e){let n=null;for(let[r,i]of Object.entries(e))if(!wn(t[r],i))n=n??{},n[r]=i;for(let r of Object.keys(t))if(!(r in e)&&t[r]!=null)n=n??{},n[r]=null;return n}function va(t){let e={};for(let n of t)e[n.type.name]=n.attrs;return e}function Sa(t){if(t!=null&&typeof t==="object"&&!Array.isArray(t)&&!(t instanceof Uint8Array))return t;return null}function Ca(t,e){let n=t.toDelta();return n.length===e.length&&n.every((r,i)=>r.insert===e[i].text&&Object.keys(r.attributes||{}).length===e[i].marks.length&&e[i].marks.every((o)=>{let s=Sa((r.attributes||{})[o.type.name]);return s!=null&&po(s,o.attrs)}))}function nr(t,e){if(t instanceof St){if(Array.isArray(e)||!Br(t,e))return!1;let n=or(t),r=Wr(e);return n.length===r.length&&po(qr(t).toJSON(),e.attrs)&&r.every((i,o)=>nr(n.get(o),i))}return t instanceof Rt&&Array.isArray(e)&&Ca(t,e)}function po(t,e){let n=Object.keys(t).filter((i)=>t[i]!==null),r=n.length===Object.keys(e).filter((i)=>e[i]!==null).length;for(let i=0;r&&i{if(r.isText){if(n==null)n=[],e.push(n);n.push(r)}else e.push(r),n=null}),e}function wa(t,e,n){let r=or(t),i=r.length,o=Wr(e),s=o.length,l=Math.min(i,s),c=0,d=0,f=!1;for(;cao(s,null,l,r)),er.set(n,i.id),r.set(i.id,n),i}function tr(t,e,n){if(n.set(t.id,e),er.set(e,t.id),!Br(t,e))throw Error("node name mismatch!");_f(t,e,n),gf(t,e,n)}function qr(t){return t.getOrCreateContainer(af,new St)}function _f(t,e,n){let r=qr(t),i=new Set(r.keys()),o=e.attrs;for(let[s,l]of Object.entries(o)){if(l!==null){if(!wn(r.get(s),l))r.set(s,l)}else r.delete(s);i.delete(s)}for(let s of i)r.delete(s)}function or(t){return t.getOrCreateContainer(fo,new ee)}function gf(t,e,n){let r=or(t),i=r.length,o=Wr(e),s=o.length,l=Math.min(s,i),c=0,d=0;for(;c0&&s-c-d>0){let h=r.get(c),p=o[c],m=r.get(i-d-1),g=o[s-d-1];if(h instanceof Rt&&Array.isArray(p)){if(!Ca(h,p))uf(h,p,n);c+=1}else{let b=h instanceof St&&Br(h,p),y=m instanceof St&&Br(m,g);if(b&&y){let S=wa(h,p,n),L=wa(m,g,n);if(S.foundMappedChild&&!L.foundMappedChild)y=!1;else if(L.foundMappedChild&&!S.foundMappedChild)b=!1;else if(S.factor0)r.toArray().slice(c,c+f).filter(ie).forEach((h)=>n.delete(h.id)),r.delete(c,f);if(c+dao(r,c+p,h,n))}function mf(t,e,n){for(let r of e.events){let i=t.getContainerById(r.target);n.delete(i.id);let o=i.parent();while(o)n.delete(o.id),o=o.parent()}}function bf(t,e,n){let r=t.state.doc,i=r.content.size;if(e<0||e>i||n!=null&&(n<0||n>i))return;let o=r.resolve(e),s=n!=null?r.resolve(n):void 0,l=R.between(o,s||o);t.dispatch(t.state.tr.setSelection(l))}var yt=new fn("loro-sync"),wf=(t,e,n)=>{let r=n.getSelection||((l)=>l.selection),i=n.createSelection||((l)=>({class:"loro-selection","data-peer":l,style:"background-color: rgba(228, 208, 102, 0.5)"})),o=n.createCursor||((l)=>{let c=e.getAll()[l],d=document.createElement("span");d.classList.add("ProseMirror-loro-cursor"),d.setAttribute("style",`border-color: ${c?.user?.color??l.slice(0,6)}`);let f=document.createElement("div");f.setAttribute("style",`background-color: ${c?.user?.color??l.slice(0,6)}`),f.insertBefore(document.createTextNode(c?.user?.name??l.slice(0,6)),null);let h=document.createTextNode("⁠"),p=document.createTextNode("⁠");return d.insertBefore(h,null),d.insertBefore(f,null),d.insertBefore(p,null),d}),s=new st({key:t,state:{init(l,c){return ya(c,e,s,i,o)},apply(l,c,d,f){let h=yt.getState(f),p=l.getMeta(t);if(h&&h.changedBy!=="local"||p&&p.presenceUpdated)return ya(f,e,s,i,o);return c.map(l.mapping,l.doc)}},props:{decorations:(l)=>s.getState(l)},view:(l)=>{let c=(h)=>{if(h!=="local")setTimeout(()=>{if(l.isDestroyed)return;let p=l.state.tr;p.setMeta(t,{presenceUpdated:!0}),l.dispatch(p)},0)},d=()=>{let h=yt.getState(l.state),p=e.getLocal();if(h?.doc==null)return;let m=l.state.doc;if(l.hasFocus()){let{anchor:g,focus:b}=Fr(m,r(l.state),h);if(p==null||!co(p.anchor,g)||!co(p.focus,b))e.setLocal({user:n.user,anchor:g,focus:b})}else if(p?.focus!=null)e.setLocal({})},f=e.subscribe(c);return l.dom.addEventListener("focusin",d),l.dom.addEventListener("focusout",d),{update:d,destroy:()=>{l.dom.removeEventListener("focusin",d),l.dom.removeEventListener("focusout",d),f(),e.setLocal({})}}}});return s};function ya(t,e,n,r,i){let o=e.getAll(),s=[],l=yt.getState(t);if(!l)return G.create(t.doc,[]);let c=l.doc,d=c.peerIdStr;for(let[f,h]of Object.entries(o)){if(f===d)continue;if(!h.anchor||!h.focus)continue;let[p,m]=Vr(h.focus,c,l.mapping);if(s.push(_t.widget(p,i(f))),!co(h.anchor,h.focus)){let[g,b]=Vr(h.anchor,c,l.mapping);if(s.push(_t.inline(Math.min(g,p),Math.max(g,p),r(f))),m||b){let y=e.getLocal();e.setLocal({...y?.user&&{user:y.user},anchor:b||h.anchor,focus:m||h.focus})}}else if(m){let g=e.getLocal();e.setLocal({...g?.user&&{user:g.user},focus:m,anchor:m})}}return G.create(t.doc,s)}function Fr(t,e,n){let r=ka(t,e.anchor,n.doc,n.mapping);return{anchor:r,focus:e.head==e.anchor?r:ka(t,e.head,n.doc,n.mapping)}}function yf(t,e){for(let[n,r]of t.entries())if(r===e)return n}function ka(t,e,n,r){let i=t.resolve(e),o=i.node(i.depth),s=i.parentOffset,l=er.get(o)??yf(r,o);if(!l){if(e>1)console.error("Cannot find the loroNode");return}let c=n.getMap(l).get(fo);if(c.length==0)return c.getCursor(0);let d=s,f=0;while(d>=0&&f{i+=p.nodeSize});else if(h!=null)i+=h.nodeSize;else console.error(d,c.toJSON())}o=s.id,s=s.parent()?.parent(),i+=1}else throw Error("Unreachable code")}return[i,l]}function co(t,e){if(!t&&!e)return!0;if(!t||!e)return!1;let n=t.pos(),r=e.pos();return n?.peer===r?.peer&&n?.counter===r?.counter&&t.containerId()===e.containerId()}var xa=new WeakSet;function kf(t){return Object.fromEntries(Object.entries(t.marks).map(([e,n])=>[e,{expand:n.spec.inclusive!==!1?"after":"none"}]))}function Oa(t,e){if(xa.has(t))return;xa.add(t),t.configTextStyle(kf(e))}var rr=new fn("loro-undo"),Ma=(t)=>new st({key:yt,props:{editable:(e)=>yt.getState(e)?.snapshot==null},state:{init:(e,n)=>(Oa(t.doc,n.schema),{doc:t.doc,mapping:t.mapping??new Map,changedBy:"local",containerId:t.containerId}),apply:(e,n,r,i)=>{let o=e.getMeta(yt),s=rr.getState(r);if(o?.type==="non-local-updates")n.changedBy="import";else n.changedBy="local";switch(o?.type){case"doc-changed":if(!s?.isUndoing.current)cf(n.doc,n.mapping,i,t.containerId);break;case"update-state":n={...n,...o.state},n.doc.commit({origin:"sys:init",timestamp:Date.now()});break;default:break}return n}},appendTransaction:(e,n,r)=>{if(e.some((i)=>i.docChanged))return r.tr.setMeta(yt,{type:"doc-changed"});return null},view:(e)=>{let n=setTimeout(()=>xf(e),0);return{update:(r,i)=>{},destroy:()=>{clearTimeout(n)}}}});function xf(t){if(t.isDestroyed)return;let e=yt.getState(t.state),n=e.docSubscription;if(n?.(),e.containerId)n=e.doc.getContainerById(e.containerId).subscribe((o)=>{Ia(t,o)});else n=e.doc.subscribe((o)=>Ia(t,o));let r=e.containerId?e.doc.getContainerById(e.containerId):e.doc.getMap(uo),i=new Map;if(r.size===0){let o=t.state.tr.delete(0,t.state.doc.content.size);o.setMeta(yt,{type:"update-state",state:{mapping:i,docSubscription:n,snapshot:null}}),t.dispatch(o)}else{let o=t.state.schema,s=ho(o,r,i),l=t.state.tr.replace(0,t.state.doc.content.size,new I(k.from(s),0,0));l.setMeta(yt,{type:"update-state",state:{mapping:i,docSubscription:n,snapshot:null}}),t.dispatch(l)}}function Ia(t,e){if(t.isDestroyed)return;let n=yt.getState(t.state);if(n.changedBy=e.by,e.by==="local"&&e.origin!=="undo")return;let r=n.mapping;mf(n.doc,e,r);let i=ho(t.state.schema,n.containerId?n.doc.getContainerById(n.containerId):n.doc.getMap(uo),r),{anchor:o,focus:s}=Fr(t.state.doc,t.state.selection,n),l=t.state.tr.replace(0,t.state.doc.content.size,new I(k.from(i),0,0));if(l.setMeta(yt,{type:"non-local-updates"}),t.dispatch(l),o==null)return;setTimeout(()=>{Aa(t,o,s)})}function Aa(t,e,n){if(t.isDestroyed)return;let r=yt.getState(t.state);if(!r)return;let{doc:i,mapping:o}=r,s=Vr(e,i,o)[0],l=n&&Vr(n,i,o)[0];if(s==null)return;bf(t,s,l)}function ir(t){return ir=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ir(t)}function If(t,e){if(ir(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(ir(r)!="object")return r;throw TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function vf(t){var e=If(t,"string");return ir(e)=="symbol"?e:e+""}function Sf(t,e,n){return(e=vf(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var Ea=class extends gi{constructor(t,e){super(e);Sf(this,"peer",void 0),this.peer=t}setLocal(t){if(!t.anchor&&!t.focus&&!t.user){this.delete(this.peer);return}this.set(this.peer,{anchor:t.anchor?.encode()??null,focus:t.focus?.encode()??null,user:t.user??null})}getLocal(){let t=this.get(this.peer);if(!t)return;return{anchor:t.anchor?Tt.decode(t.anchor):void 0,focus:t.focus?Tt.decode(t.focus):void 0,user:t.user??void 0}}getAll(){let t={};for(let[e,n]of Object.entries(this.getAllStates())){if(!n)continue;t[e]={anchor:n.anchor?Tt.decode(n.anchor):void 0,focus:n.focus?Tt.decode(n.focus):void 0,user:n.user??void 0}}return t}subscribeBy(t){return super.subscribe((e)=>t(e.by))}},Cf=new fn("loro-ephemeral-cursor"),Na=(t,e)=>wf(Cf,Of(t),e),Of=(t)=>({getAll:()=>t.getAll(),getLocal:()=>t.getLocal(),setLocal:(e)=>t.setLocal(e),subscribe:(e)=>t.subscribeBy(e)});var $p=new fn("loro-cursor");var Da=(t)=>{let e=t.undoManager||new nn(t.doc,{}),n={anchor:null,focus:null};return new st({key:rr,state:{init:(r,i)=>(Oa(t.doc,i.schema),e.addExcludeOriginPrefix("sys:init"),{undoManager:e,canUndo:e.canUndo(),canRedo:e.canRedo(),isUndoing:{current:!1}}),apply:(r,i,o,s)=>{let l=rr.getState(o),c=yt.getState(o);if(!l||!c)return i;let d=l.undoManager.canUndo(),f=l.undoManager.canRedo();{let{anchor:h,focus:p}=Fr(o.doc,o.selection,c);n={anchor:h??null,focus:p??null}}return{...i,canUndo:d,canRedo:f}}},view:(r)=>(e.setOnPush((i,o)=>{if(yt.getState(r.state)?.doc==null)return{value:null,cursors:[]};let s=[],l=n;if(!i){let c=yt.getState(r.state);if(c){let{anchor:d,focus:f}=Fr(r.state.doc,r.state.selection,c);l.anchor=d||null,l.focus=f||null}}if(l.anchor)s.push(l.anchor);if(l.focus)s.push(l.focus);return{value:null,cursors:s}}),e.setOnPop((i,o,s)=>{if(yt.getState(r.state)?.doc==null)return;let l=o.cursors[0],c=o.cursors[1];if(l==null)return;setTimeout(()=>{Aa(r,l,c)},0)}),{destroy:()=>{e.setOnPop(),e.setOnPush()}})})};var _o=(t,e)=>{let n=rr.getState(t);if(!n)return!1;if(!e)return n.undoManager.canUndo();return n.isUndoing.current=!0,setTimeout(()=>{n.isUndoing.current=!1},0),n.undoManager.undo()},Ur=(t,e)=>{let n=rr.getState(t);if(!n)return!1;if(!e)return n.undoManager.canRedo();return n.isUndoing.current=!0,setTimeout(()=>{n.isUndoing.current=!1},0),n.undoManager.redo()};var Mf=["p",0],Af=["blockquote",0],Ef=["hr"],Nf=["pre",["code",0]],Df=["br"],Tf={doc:{content:"block+"},paragraph:{content:"inline*",group:"block",parseDOM:[{tag:"p"}],toDOM(){return Mf}},blockquote:{content:"block+",group:"block",defining:!0,parseDOM:[{tag:"blockquote"}],toDOM(){return Af}},horizontal_rule:{group:"block",parseDOM:[{tag:"hr"}],toDOM(){return Ef}},heading:{attrs:{level:{default:1,validate:"number"}},content:"inline*",group:"block",defining:!0,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(t){return["h"+ +t.attrs.level,0]}},code_block:{content:"text*",marks:"",group:"block",code:!0,defining:!0,parseDOM:[{tag:"pre",preserveWhitespace:"full"}],toDOM(){return Nf}},text:{group:"inline"},image:{inline:!0,attrs:{src:{validate:"string"},alt:{default:null,validate:"string|null"},title:{default:null,validate:"string|null"}},group:"inline",draggable:!0,parseDOM:[{tag:"img[src]",getAttrs(t){return{src:t.getAttribute("src"),title:t.getAttribute("title"),alt:t.getAttribute("alt")}}}],toDOM(t){let{src:e,alt:n,title:r}=t.attrs;return["img",{src:e,alt:n,title:r}]}},hard_break:{inline:!0,group:"inline",selectable:!1,parseDOM:[{tag:"br"}],toDOM(){return Df}}},Rf=["em",0],Lf=["strong",0],Pf=["code",0],Bf={link:{attrs:{href:{validate:"string"},title:{default:null,validate:"string|null"}},inclusive:!1,parseDOM:[{tag:"a[href]",getAttrs(t){return{href:t.getAttribute("href"),title:t.getAttribute("title")}}}],toDOM(t){let{href:e,title:n}=t.attrs;return["a",{href:e,title:n},0]}},em:{parseDOM:[{tag:"i"},{tag:"em"},{style:"font-style=italic"},{style:"font-style=normal",clearMark:(t)=>t.type.name=="em"}],toDOM(){return Rf}},strong:{parseDOM:[{tag:"strong"},{tag:"b",getAttrs:(t)=>t.style.fontWeight!="normal"&&null},{style:"font-weight=400",clearMark:(t)=>t.type.name=="strong"},{style:"font-weight",getAttrs:(t)=>/^(bold(er)?|[5-9]\d{2,})$/.test(t)&&null}],toDOM(){return Lf}},code:{code:!0,parseDOM:[{tag:"code"}],toDOM(){return Pf}}},$r=new sn({nodes:Tf,marks:Bf});var zf=["ol",0],Ff=["ul",0],Vf=["li",0],Wf={attrs:{order:{default:1,validate:"number"}},parseDOM:[{tag:"ol",getAttrs(t){return{order:t.hasAttribute("start")?+t.getAttribute("start"):1}}}],toDOM(t){return t.attrs.order==1?zf:["ol",{start:t.attrs.order},0]}},qf={parseDOM:[{tag:"ul"}],toDOM(){return Ff}},Uf={parseDOM:[{tag:"li"}],toDOM(){return Vf},defining:!0};function go(t,e){let n={};for(let r in t)n[r]=t[r];for(let r in e)n[r]=e[r];return n}function Ta(t,e,n){return t.append({ordered_list:go(Wf,{content:"list_item+",group:n}),bullet_list:go(qf,{content:"list_item+",group:n}),list_item:go(Uf,{content:e})})}function Ra(t,e=null){return function(n,r){let{$from:i,$to:o}=n.selection,s=i.blockRange(o);if(!s)return!1;let l=r?n.tr:null;if(!$f(l,s,t,e))return!1;if(r)r(l.scrollIntoView());return!0}}function $f(t,e,n,r=null){let i=!1,o=e,s=e.$from.doc;if(e.depth>=2&&e.$from.node(e.depth-1).type.compatibleContent(n)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let c=s.resolve(e.start-2);if(o=new on(c,c,e.depth),e.endIndex=0;f--)o=k.from(n[f].type.create(n[f].attrs,o));t.step(new ft(e.start-(r?2:0),e.end,e.start,e.end,new I(o,0,0),n.length,!0));let s=0;for(let f=0;f=i.depth-3;S--)h=k.from(i.node(S).copy(h));let m=i.indexAfter(-1){if(y>-1)return!1;if(S.isTextblock&&S.content.size==0)y=L+1}),y>-1)b.setSelection(F.near(b.doc.resolve(y)));r(b.scrollIntoView())}return!0}let c=o.pos==i.end()?l.contentMatchAt(0).defaultType:null,d=n.tr.delete(i.pos,o.pos),f=c?[e?{type:t,attrs:e}:null,{type:c}]:void 0;if(!we(d.doc,i.pos,2,f))return!1;if(r)r(d.split(i.pos,2,f).scrollIntoView());return!0}}function Jr(t){return function(e,n){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,(s)=>s.childCount>0&&s.firstChild.type==t);if(!o)return!1;if(!n)return!0;if(r.node(o.depth-1).type==t)return jf(e,n,t,o);else return Hf(e,n,o)}}function jf(t,e,n,r){let i=t.tr,o=r.end,s=r.$to.end(r.depth);if(ob;g--)m-=i.child(g).nodeSize,r.delete(m-1,m+1);let o=r.doc.resolve(n.start),s=o.nodeAfter;if(r.mapping.map(n.end)!=n.start+o.nodeAfter.nodeSize)return!1;let l=n.startIndex==0,c=n.endIndex==i.childCount,d=o.node(-1),f=o.index(-1);if(!d.canReplace(f+(l?0:1),f+1,s.content.append(c?k.empty:k.from(i))))return!1;let h=o.pos,p=h+s.nodeSize;return r.step(new ft(h-(l?1:0),p+(c?1:0),h+1,p-1,new I((l?k.empty:k.from(i.copy(k.empty))).append(c?k.empty:k.from(i.copy(k.empty))),l?0:1,c?0:1),l?0:1)),e(r.scrollIntoView()),!0}function Pa(t){return function(e,n){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,(d)=>d.childCount>0&&d.firstChild.type==t);if(!o)return!1;let s=o.startIndex;if(s==0)return!1;let l=o.parent,c=l.child(s-1);if(c.type!=t)return!1;if(n){let d=c.lastChild&&c.lastChild.type==l.type,f=k.from(d?t.create():null),h=new I(k.from(t.create(null,k.from(l.type.create(null,f)))),d?3:1,0),{start:p,end:m}=o;n(e.tr.step(new ft(p-(d?3:1),m,p,m,h,1,!0)).scrollIntoView())}return!0}}var fe={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:"'"},jr={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},Kf=typeof navigator<"u"&&/Mac/.test(navigator.platform),Yf=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(ot=0;ot<10;ot++)fe[48+ot]=fe[96+ot]=String(ot);var ot;for(ot=1;ot<=24;ot++)fe[ot+111]="F"+ot;var ot;for(ot=65;ot<=90;ot++)fe[ot]=String.fromCharCode(ot+32),jr[ot]=String.fromCharCode(ot);var ot;for(sr in fe)if(!jr.hasOwnProperty(sr))jr[sr]=fe[sr];var sr;function Ba(t){var e=Kf&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||Yf&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?jr:fe)[t.keyCode]||t.key||"Unidentified";if(n=="Esc")n="Escape";if(n=="Del")n="Delete";if(n=="Left")n="ArrowLeft";if(n=="Up")n="ArrowUp";if(n=="Right")n="ArrowRight";if(n=="Down")n="ArrowDown";return n}var Xf=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),Gf=typeof navigator<"u"&&/Win/.test(navigator.platform);function Qf(t){let e=t.split(/-(?!$)/),n=e[e.length-1];if(n=="Space")n=" ";let r,i,o,s;for(let l=0;l{if(t.selection.empty)return!1;if(e)e(t.tr.deleteSelection().scrollIntoView());return!0};function th(t,e){let{$cursor:n}=t.selection;if(!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0))return null;return n}var eh=(t,e,n)=>{let r=th(t,n);if(!r)return!1;let i=Va(r);if(!i){let s=r.blockRange(),l=s&&Ue(s);if(l==null)return!1;if(e)e(t.tr.lift(s,l).scrollIntoView());return!0}let o=i.nodeBefore;if(Ua(t,i,e,-1))return!0;if(r.parent.content.size==0&&(kn(o,"end")||T.isSelectable(o)))for(let s=r.depth;;s--){let l=Sr(t.doc,r.before(s),r.after(s),I.empty);if(l&&l.slice.size1)break}if(o.isAtom&&i.depth==r.depth-1){if(e)e(t.tr.delete(i.pos-o.nodeSize,i.pos).scrollIntoView());return!0}return!1};function kn(t,e,n=!1){for(let r=t;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}var nh=(t,e,n)=>{let{$head:r,empty:i}=t.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;o=Va(r)}let s=o&&o.nodeBefore;if(!s||!T.isSelectable(s))return!1;if(e)e(t.tr.setSelection(T.create(t.doc,o.pos-s.nodeSize)).scrollIntoView());return!0};function Va(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){if(t.index(e)>0)return t.doc.resolve(t.before(e+1));if(t.node(e).type.spec.isolating)break}return null}function rh(t,e){let{$cursor:n}=t.selection;if(!n||(e?!e.endOfTextblock("forward",t):n.parentOffset{let r=rh(t,n);if(!r)return!1;let i=Wa(r);if(!i)return!1;let o=i.nodeAfter;if(Ua(t,i,e,1))return!0;if(r.parent.content.size==0&&(kn(o,"start")||T.isSelectable(o))){let s=Sr(t.doc,r.before(),r.after(),I.empty);if(s&&s.slice.size{let{$head:r,empty:i}=t.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):r.parentOffset=0;e--){let n=t.node(e);if(t.index(e)+1{let{$from:n,$to:r}=t.selection,i=n.blockRange(r),o=i&&Ue(i);if(o==null)return!1;if(e)e(t.tr.lift(i,o).scrollIntoView());return!0},sh=(t,e)=>{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;if(e)e(t.tr.insertText(` +`).scrollIntoView());return!0};function yo(t){for(let e=0;e{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let i=n.node(-1),o=n.indexAfter(-1),s=yo(i.contentMatchAt(o));if(!s||!i.canReplaceWith(o,o,s))return!1;if(e){let l=n.after(),c=t.tr.replaceWith(l,l,s.createAndFill());c.setSelection(F.near(c.doc.resolve(l),1)),e(c.scrollIntoView())}return!0},ah=(t,e)=>{let n=t.selection,{$from:r,$to:i}=n;if(n instanceof Ct||r.parent.inlineContent||i.parent.inlineContent)return!1;let o=yo(i.parent.contentMatchAt(i.indexAfter()));if(!o||!o.isTextblock)return!1;if(e){let s=(!r.parentOffset&&i.index(){let{$cursor:n}=t.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let o=n.before();if(we(t.doc,o)){if(e)e(t.tr.split(o).scrollIntoView());return!0}}let r=n.blockRange(),i=r&&Ue(r);if(i==null)return!1;if(e)e(t.tr.lift(r,i).scrollIntoView());return!0};function dh(t){return(e,n)=>{if(e.selection instanceof T&&e.selection.node.isBlock){let{$from:m}=e.selection;if(!m.parentOffset||!we(e.doc,m.pos))return!1;if(n)n(e.tr.split(m.pos).scrollIntoView());return!0}if(!e.selection.$from.depth)return!1;let r=e.tr;if(!e.selection.empty&&(e.selection instanceof R||e.selection instanceof Ct))r.deleteSelection();let{$from:i}=r.selection,o=r.steps.length,s=[],l,c,d=!1,f=!1;for(let m=i.depth;;m--)if(i.node(m).isBlock){d=i.end(m)==i.pos+(i.depth-m),f=i.start(m)==i.pos-(i.depth-m),c=yo(i.node(m-1).contentMatchAt(i.indexAfter(m-1)));let b=t&&t(i.parent,d,i);s.unshift(b||(d&&c?{type:c}:null)),l=m;break}else{if(m==1)return!1;s.unshift(null)}let h=i.pos,p=we(r.doc,h,s.length,s);if(!p)s[0]=c?{type:c}:null,p=we(r.doc,h,s.length,s);if(!p)return!1;if(r.split(h,s.length,s),!d&&f&&i.node(l).type!=c){let m=r.mapping.slice(o),g=m.map(i.before(l)),b=r.doc.resolve(g);if(c&&i.node(l-1).canReplaceWith(b.index(),b.index()+1,c))r.setNodeMarkup(m.map(i.before(l)),c)}if(n)n(r.scrollIntoView());return!0}}var uh=dh();var fh=(t,e)=>{if(e)e(t.tr.setSelection(new Ct(t.doc)));return!0};function hh(t,e,n){let{nodeBefore:r,nodeAfter:i}=e,o=e.index();if(!r||!i||!r.type.compatibleContent(i.type))return!1;if(!r.content.size&&e.parent.canReplace(o-1,o)){if(n)n(t.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView());return!0}if(!e.parent.canReplace(o,o+1)||!(i.isTextblock||$e(t.doc,e.pos)))return!1;if(n)n(t.tr.join(e.pos).scrollIntoView());return!0}function Ua(t,e,n,r){let{nodeBefore:i,nodeAfter:o}=e,s,l,c=i.type.spec.isolating||o.type.spec.isolating;if(!c&&hh(t,e,n))return!0;let d=!c&&e.parent.canReplace(e.index(),e.index()+1);if(d&&(s=(l=i.contentMatchAt(i.childCount)).findWrapping(o.type))&&l.matchType(s[0]||o.type).validEnd){if(n){let m=e.pos+o.nodeSize,g=k.empty;for(let S=s.length-1;S>=0;S--)g=k.from(s[S].create(null,g));g=k.from(i.copy(g));let b=t.tr.step(new ft(e.pos-1,m,e.pos,m,new I(g,1,0),s.length,!0)),y=b.doc.resolve(m+2*s.length);if(y.nodeAfter&&y.nodeAfter.type==i.type&&$e(b.doc,y.pos))b.join(y.pos);n(b.scrollIntoView())}return!0}let f=o.type.spec.isolating||r>0&&c?null:F.findFrom(e,1),h=f&&f.$from.blockRange(f.$to),p=h&&Ue(h);if(p!=null&&p>=e.depth){if(n)n(t.tr.lift(h,p).scrollIntoView());return!0}if(d&&kn(o,"start",!0)&&kn(i,"end")){let m=i,g=[];for(;;){if(g.push(m),m.isTextblock)break;m=m.lastChild}let b=o,y=1;for(;!b.isTextblock;b=b.firstChild)y++;if(m.canReplace(m.childCount,m.childCount,b.content)){if(n){let S=k.empty;for(let U=g.length-1;U>=0;U--)S=k.from(g[U].copy(S));let L=t.tr.step(new ft(e.pos-g.length,e.pos+o.nodeSize,e.pos+y,e.pos+o.nodeSize-y,new I(S,g.length,0),0,!0));n(L.scrollIntoView())}return!0}}return!1}function $a(t){return function(e,n){let r=e.selection,i=t<0?r.$from:r.$to,o=i.depth;while(i.node(o).isInline){if(!o)return!1;o--}if(!i.node(o).isTextblock)return!1;if(n)n(e.tr.setSelection(R.create(e.doc,t<0?i.start(o):i.end(o))));return!0}}var ph=$a(-1),_h=$a(1);function Ja(t,e=null){return function(n,r){let{$from:i,$to:o}=n.selection,s=i.blockRange(o),l=s&&cn(s,t,e);if(!l)return!1;if(r)r(n.tr.wrap(s,l).scrollIntoView());return!0}}function ko(t,e=null){return function(n,r){let i=!1;for(let o=0;o{if(i)return!1;if(!c.isTextblock||c.hasMarkup(t,e))return;if(c.type==t)i=!0;else{let f=n.doc.resolve(d),h=f.index();i=f.parent.canReplaceWith(h,h+1,t)}})}if(!i)return!1;if(r){let o=n.tr;for(let s=0;s{if(l||!r&&c.isAtom&&c.isInline&&d>=o.pos&&d+c.nodeSize<=s.pos)return!1;l=c.inlineContent&&c.type.allowsMarkType(n)}),l)return!0}return!1}function mh(t){let e=[];for(let n=0;n{if(o.isAtom&&o.content.size&&o.isInline&&s>=r.pos&&s+o.nodeSize<=i.pos){if(s+1>r.pos)e.push(new qn(r,r.doc.resolve(s+1)));return r=r.doc.resolve(s+1+o.content.size),!1}}),r.poss.doc.rangeHasMark(m.$from.pos,m.$to.pos,t));else h=!f.every((m)=>{let g=!1;return p.doc.nodesBetween(m.$from.pos,m.$to.pos,(b,y,S)=>{if(g)return!1;g=!t.isInSet(b.marks)&&!!S&&S.type.allowsMarkType(t)&&!(b.isText&&/^\s*$/.test(b.textBetween(Math.max(0,m.$from.pos-y),Math.min(b.nodeSize,m.$to.pos-y))))}),!g});for(let m=0;me[i]??r):n}class Jt{constructor(t,e,n={}){this.match=t,this.match=t,this.handler=typeof e=="string"?xh(e):e,this.undoable=n.undoable!==!1,this.inCode=n.inCode||!1,this.inCodeMark=n.inCodeMark!==!1}}function xh(t){return function(e,n,r,i){let o=t;if(n[1]){let s=n[0].lastIndexOf(n[1]);o+=n[0].slice(s+n[1].length),r+=s;let l=r-i;if(l>0)o=n[0].slice(s-l,s)+o,r=i}return e.tr.insertText(o,r,i)}}var Ih=500;function Ya({rules:t}){let e=new st({state:{init(){return null},apply(n,r){let i=n.getMeta(this);if(i)return i;return n.selectionSet||n.docChanged?null:r}},props:{handleTextInput(n,r,i,o){return Ka(n,r,i,o,t,e)},handleDOMEvents:{compositionend:(n)=>{setTimeout(()=>{let{$cursor:r}=n.state.selection;if(r)Ka(n,r.pos,r.pos,"",t,e)})}}},isInputRules:!0});return e}function Ka(t,e,n,r,i,o){if(t.composing)return!1;let s=t.state,l=s.doc.resolve(e),c=l.parent.textBetween(Math.max(0,l.parentOffset-Ih),l.parentOffset,null,"")+r;for(let d=0;dg.type.spec.code))continue;if(l.parent.type.spec.code){if(!f.inCode)continue}else if(f.inCode==="only")continue;let h=f.match.exec(c);if(!h||h[0].length{if(b.isInline&&b.marks.some((y)=>y.type.spec.code))g=!0}),g)continue}let m=f.handler(s,h,p,n);if(!m)continue;if(f.undoable)m.setMeta(o,{transform:m,from:e,to:n,text:r});return t.dispatch(m),!0}return!1}var Xa=(t,e)=>{let n=t.plugins;for(let r=0;r=0;c--)s.step(l.steps[c].invert(l.docs[c]));if(o.text){let c=s.doc.resolve(o.from).marks();s.replaceWith(o.from,o.to,t.schema.text(o.text,c))}else s.delete(o.from,o.to);e(s)}return!0}}return!1},u_=new Jt(/--$/,"—",{inCodeMark:!1}),f_=new Jt(/\.\.\.$/,"…",{inCodeMark:!1}),h_=new Jt(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(")$/,"“",{inCodeMark:!1}),p_=new Jt(/"$/,"”",{inCodeMark:!1}),__=new Jt(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(')$/,"‘",{inCodeMark:!1}),g_=new Jt(/'$/,"’",{inCodeMark:!1});function Hr(t,e,n=null,r){return new Jt(t,(i,o,s,l)=>{let c=n instanceof Function?n(o):n,d=i.tr.delete(s,l),f=d.doc.resolve(s),h=f.blockRange(),p=h&&cn(h,e,c);if(!p)return null;d.wrap(h,p);let m=d.doc.resolve(s-1).nodeBefore;if(m&&m.type==e&&$e(d.doc,s-1)&&(!r||r(o,m)))d.join(s-1);return d})}function Io(t,e,n=null){return new Jt(t,(r,i,o,s)=>{let l=r.doc.resolve(o),c=n instanceof Function?n(i):n;if(!l.node(-1).canReplaceWith(l.index(-1),l.indexAfter(-1),e))return null;return r.tr.delete(o,s).setBlockType(o,o,e,c)})}function Ga(t={}){return new st({view(e){return new Qa(e,t)}})}class Qa{constructor(t,e){var n;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,this.lastDragEvent=null,this.width=(n=e.width)!==null&&n!==void 0?n:1,this.color=e.color===!1?void 0:e.color||"black",this.class=e.class,this.handlers=["dragover","dragend","drop","dragleave"].map((r)=>{let i=(o)=>{this[r](o)};return t.dom.addEventListener(r,i),{name:r,handler:i}})}destroy(){this.setCursor(null),this.handlers.forEach(({name:t,handler:e})=>this.editorView.dom.removeEventListener(t,e))}update(t,e){if(this.cursorPos!=null&&e.doc!=t.state.doc)if(this.lastDragEvent){let n=this.computeTarget(this.lastDragEvent);if(n==this.cursorPos)this.updateOverlay();else this.setCursor(n)}else this.updateOverlay()}setCursor(t){if(t==this.cursorPos)return;if(this.cursorPos=t,t==null)this.element.parentNode.removeChild(this.element),this.element=null;else this.updateOverlay()}updateOverlay(){let t=this.editorView.state.doc.resolve(this.cursorPos),e=!t.parent.inlineContent,n,r=this.editorView.dom,i=r.getBoundingClientRect(),o=i.width/r.offsetWidth,s=i.height/r.offsetHeight;if(e){let{nodeBefore:f,nodeAfter:h}=t;if(f||h){let p=this.editorView.nodeDOM(this.cursorPos-(f?f.nodeSize:0));if(p){let m=p.getBoundingClientRect(),g=f?m.bottom:m.top;if(f&&h)g=(g+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2;let b=this.width/2*s;n={left:m.left,right:m.right,top:g-b,bottom:g+b}}}}if(!n){let f=this.editorView.coordsAtPos(this.cursorPos),h=this.width/2*o;n={left:f.left-h,right:f.left+h,top:f.top,bottom:f.bottom}}let l=this.editorView.dom.offsetParent;if(!this.element){if(this.element=l.appendChild(document.createElement("div")),this.class)this.element.className=this.class;if(this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color)this.element.style.backgroundColor=this.color}this.element.classList.toggle("prosemirror-dropcursor-block",e),this.element.classList.toggle("prosemirror-dropcursor-inline",!e);let c,d;if(!l||l==document.body&&getComputedStyle(l).position=="static")c=-pageXOffset,d=-pageYOffset;else{let f=l.getBoundingClientRect(),h=f.width/l.offsetWidth,p=f.height/l.offsetHeight;c=f.left-l.scrollLeft*h,d=f.top-l.scrollTop*p}this.element.style.left=(n.left-c)/o+"px",this.element.style.top=(n.top-d)/s+"px",this.element.style.width=(n.right-n.left)/o+"px",this.element.style.height=(n.bottom-n.top)/s+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}computeTarget(t){let e=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),n=e&&e.inside>=0&&this.editorView.state.doc.nodeAt(e.inside),r=n&&n.type.spec.disableDropCursor,i=typeof r=="function"?r(this.editorView,e,t):r;if(!e||i)return null;let o=e.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let s=vr(this.editorView.state.doc,o,this.editorView.dragging.slice);if(s!=null)o=s}return o}dragover(t){if(!this.editorView.editable)return;this.lastDragEvent=t;let e=this.computeTarget(t);if(e!=null)this.setCursor(e),this.scheduleRemoval(5000)}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(t){if(!this.editorView.dom.contains(t.relatedTarget))this.setCursor(null)}}class lt extends F{constructor(t){super(t,t)}map(t,e){let n=t.resolve(e.map(this.head));return lt.valid(n)?new lt(n):F.near(n)}content(){return I.empty}eq(t){return t instanceof lt&&t.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(t,e){if(typeof e.pos!="number")throw RangeError("Invalid input for GapCursor.fromJSON");return new lt(t.resolve(e.pos))}getBookmark(){return new vo(this.anchor)}static valid(t){let e=t.parent;if(e.inlineContent||!vh(t)||!Sh(t))return!1;let n=e.type.spec.allowGapCursor;if(n!=null)return n;let r=e.contentMatchAt(t.index()).defaultType;return r&&r.isTextblock}static findGapCursorFrom(t,e,n=!1){t:for(;;){if(!n&<.valid(t))return t;let r=t.pos,i=null;for(let o=t.depth;;o--){let s=t.node(o);if(e>0?t.indexAfter(o)0){i=s.child(e>0?t.indexAfter(o):t.index(o)-1);break}else if(o==0)return null;r+=e;let l=t.doc.resolve(r);if(lt.valid(l))return l}for(;;){let o=e>0?i.firstChild:i.lastChild;if(!o){if(i.isAtom&&!i.isText&&!T.isSelectable(i)){t=t.doc.resolve(r+i.nodeSize*e),n=!1;continue t}break}i=o,r+=e;let s=t.doc.resolve(r);if(lt.valid(s))return s}return null}}}lt.prototype.visible=!1;lt.findFrom=lt.findGapCursorFrom;F.jsonID("gapcursor",lt);class vo{constructor(t){this.pos=t}map(t){return new vo(t.map(this.pos))}resolve(t){let e=t.resolve(this.pos);return lt.valid(e)?new lt(e):F.near(e)}}function Za(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function vh(t){for(let e=t.depth;e>=0;e--){let n=t.index(e),r=t.node(e);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(n-1);;i=i.lastChild){if(i.childCount==0&&!i.inlineContent||Za(i.type))return!0;if(i.inlineContent)return!1}}return!0}function Sh(t){for(let e=t.depth;e>=0;e--){let n=t.indexAfter(e),r=t.node(e);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(n);;i=i.firstChild){if(i.childCount==0&&!i.inlineContent||Za(i.type))return!0;if(i.inlineContent)return!1}}return!0}function tc(){return new st({props:{decorations:Ah,createSelectionBetween(t,e,n){return e.pos==n.pos&<.valid(n)?new lt(n):null},handleClick:Oh,handleKeyDown:Ch,handleDOMEvents:{beforeinput:Mh}}})}var Ch=bo({ArrowLeft:Kr("horiz",-1),ArrowRight:Kr("horiz",1),ArrowUp:Kr("vert",-1),ArrowDown:Kr("vert",1)});function Kr(t,e){let n=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,i,o){let s=r.selection,l=e>0?s.$to:s.$from,c=s.empty;if(s instanceof R){if(!o.endOfTextblock(n)||l.depth==0)return!1;c=!1,l=r.doc.resolve(e>0?l.after():l.before())}let d=lt.findGapCursorFrom(l,e,c);if(!d)return!1;if(i)i(r.tr.setSelection(new lt(d)));return!0}}function Oh(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!lt.valid(r))return!1;let i=t.posAtCoords({left:n.clientX,top:n.clientY});if(i&&i.inside>-1&&T.isSelectable(t.state.doc.nodeAt(i.inside)))return!1;return t.dispatch(t.state.tr.setSelection(new lt(r))),!0}function Mh(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof lt))return!1;let{$from:n}=t.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(t.state.schema.nodes.text);if(!r)return!1;let i=k.empty;for(let s=r.length-1;s>=0;s--)i=k.from(r[s].createAndFill(null,i));let o=t.state.tr.replace(n.pos,n.pos,new I(i,0,0));return o.setSelection(R.near(o.doc.resolve(n.pos+1))),t.dispatch(o),!1}function Ah(t){if(!(t.selection instanceof lt))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",G.create(t.doc,[_t.widget(t.selection.head,e,{key:"gapcursor"})])}function re(t,e){let{from:n,to:r,empty:i,$from:o}=t.selection;if(i)return!!e.isInSet(t.storedMarks||o.marks());return t.doc.rangeHasMark(n,r,e)}function _e(t,e,n){let r=t.selection.$from.parent;if(r.type!==e)return!1;return!n||Object.keys(n).every((i)=>r.attrs[i]===n[i])}function lr(t,e){let{$from:n}=t.selection;for(let r=n.depth;r>0;r--){let i=n.node(r);if(e(i))return{node:i,pos:n.before(r)}}return null}function So(t,e,n){return new Jt(t,(r,i,o,s)=>{let l=i[1];if(!l)return null;let c=o+i[0].length-n-l.length,d=c+l.length,f=c-n,h=r.tr;return h.delete(d,s),h.delete(f,c),h.addMark(f,f+l.length,e.create()),h.removeStoredMark(e),h})}function Yr(t,e,n){let r=t.resolve(e);if(!r.parent.inlineContent)return null;let i=r.start(),o=null;return r.parent.forEach((s,l)=>{if(o)return;let c=i+l,d=c+s.nodeSize,f=n.isInSet(s.marks);if(f&&c<=e&&e<=d)o={from:c,to:d,mark:f}}),o}function ec(t){let e=t.trim();if(!e)return null;if(/^(javascript|data|vbscript):/i.test(e.replace(/[\s\x00-\x1f]/g,"")))return null;if(/^[a-z][a-z\d+.-]*:/i.test(e)||e.startsWith("/")||e.startsWith("#"))return e;return`https://${e}`}function nc(t,e){let{paragraph:n,heading:r,code_block:i,blockquote:o,horizontal_rule:s,bullet_list:l,ordered_list:c,list_item:d}=t.nodes,{strong:f,em:h,code:p,link:m}=t.marks,g=ko(n),b=(P,V)=>(j,X)=>_e(j,P,V)?g(j,X):ko(P,V)(j,X),y=(P)=>(V,j)=>{let X=lr(V,(nt)=>nt.type===l||nt.type===c);if(!X)return Ra(P)(V,j);if(X.node.type===P)return Jr(d)(V,j);if(j)j(V.tr.setNodeMarkup(X.pos,P));return!0},S=(P,V)=>lr(P,(j)=>j.type===o)?qa(P,V):Ja(o)(P,V),L=(P,V,j)=>{let{$from:X,empty:nt}=P.selection,Vt=nt&&Yr(P.doc,P.selection.from,m)!==null,ge=!nt&&X.parent.inlineContent&&X.parent.type.allowsMarkType(m);if(!Vt&&!ge)return!1;if(V&&j)e.requestLink(j);return!0},U=(P,V)=>{let{$from:j}=P.selection;if(j.parent.type.spec.code)return!1;if(!V)return!0;let X=P.tr.replaceSelectionWith(s.create());if(!X.selection.$from.parent.inlineContent){let nt=X.selection.from;X.insert(nt,n.create()),X.setSelection(R.create(X.doc,nt+1))}return V(X.scrollIntoView()),!0},et=new Jt(/^---$/,(P,V,j,X)=>{let nt=P.doc.resolve(j),Vt=nt.depth;if(Vt<1||nt.parent.type.spec.code)return null;let ge=nt.index(Vt-1),Cn=nt.node(Vt-1),D=k.from([s.create(),n.create()]);if(!Cn.canReplace(ge,ge+1,D))return null;let A=nt.before(),N=P.tr.replaceWith(A,nt.after(),[s.create(),n.create()]);return N.setSelection(R.create(N.doc,A+s.create().nodeSize+1)),N}),at=0,Ft=new st({props:{transformPastedHTML(P){return P.replace(/\s(?:style|class)\s*=\s*("[^"]*"|'[^']*')/gi,"")},handleKeyDown(P,V){if((V.metaKey||V.ctrlKey)&&V.shiftKey&&V.key.toLowerCase()==="v")at=Date.now()+1000;return!1},handlePaste(P,V){if(Date.now()>at)return!1;at=0;let j=V.clipboardData?.getData("text/plain");if(!j)return!1;return P.pasteText(j),!0}}}),z=yn({"Mod-Alt-0":g,"Mod-Alt-1":b(r,{level:1}),"Mod-Alt-2":b(r,{level:2}),"Mod-Alt-3":b(r,{level:3}),"Mod-Shift-8":y(l),"Mod-Shift-9":y(c),"Mod-k":L,"Mod-e":pe(p),Backspace:Xa}),Y=Ya({rules:[Io(/^(#{1,3})\s$/,r,(P)=>({level:P[1].length})),Io(/^```$/,i),Hr(/^\s*([-*])\s$/,l),Hr(/^(\d+)\.\s$/,c,(P)=>({order:Number(P[1])}),(P,V)=>V.childCount+V.attrs.order===Number(P[1])),Hr(/^\s*>\s$/,o),So(/\*\*([^*]+)\*\*$/,f,2),So(/(?:^|[^*])\*([^*]+)\*$/,h,1),So(/`([^`]+)`$/,p,1),et]}),Z=new st({props:{decorations(P){let{doc:V}=P,j=V.firstChild;if(V.childCount!==1||!j||j.type!==n||j.content.size>0)return null;return G.create(V,[_t.node(0,j.nodeSize,{class:"is-placeholder","data-placeholder":C("placeholder")})])}}});return{plugins:[Ft,z,Y,Ga({color:"var(--primary)",width:2}),tc(),Z],paragraph:g,heading:(P)=>b(r,{level:P}),codeBlock:b(i),bold:pe(f),italic:pe(h),inlineCode:pe(p),link:L,bulletList:y(l),orderedList:y(c),blockquote:S,horizontalRule:U}}var Co=/Mac|iPhone|iPad|iPod/.test(navigator.platform||navigator.userAgent),Q=Co?"⌘":"Ctrl",Qe=Co?"⇧":"Shift",Xt=Co?"⌥":"Alt";function B(t,e={},...n){let r=document.createElement(t);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return r.append(...n),r}function Gt(...t){return B("span",{class:"keycaps","aria-hidden":"true"},...t.map((e)=>B("kbd",{class:"keycap"},e)))}function Xr(t,e,n){let r=[B("span",{class:"tip-label"},t)];if(e.length)r.push(Gt(...e));if(n)r.push(B("span",{class:"tip-reason"},n));return B("span",{class:"tip","aria-hidden":"true",role:"presentation"},...r)}function xn(t,e,n){let r=t.coordsAtPos(e),i=t.coordsAtPos(n);return{top:Math.min(r.top,i.top),bottom:Math.max(r.bottom,i.bottom),left:Math.min(r.left,i.left),right:Math.max(r.right,i.right)}}var Ae=8;function In(t,e,n){let{offsetWidth:r,offsetHeight:i}=t,o=e.top-i-Ae,s=e.bottom+Ae,l;if(n==="above")l=o>=Ae?o:s;else l=s+i<=window.innerHeight-Ae?s:o;let c=(e.left+e.right)/2,d=Math.min(Math.max(c-r/2,Ae),window.innerWidth-r-Ae);t.style.top=`${Math.max(l,Ae)}px`,t.style.left=`${Math.max(d,Ae)}px`}var Eh=120;function Gr(t){return!!t&&t.startsWith("/notes/")}function Nh(t,e){let{selection:n}=t;if(!(n instanceof R)||!n.empty)return null;let r=n.$from;if(!r.parent.isTextblock||r.parent.type.spec.code)return null;if(e.isInSet(t.storedMarks||r.marks()))return null;let i=r.parent.textBetween(0,r.parentOffset,void 0,` +`),o=/\[\[([^\[\]\n]*)$/.exec(i);if(!o)return null;return{from:r.pos-o[0].length,query:o[1]}}function Dh(t){if(!Array.isArray(t))return[];return t.filter((e)=>typeof e==="object"&&e!==null&&typeof e.id==="string"&&typeof e.title==="string")}async function Th(t){let e=await fetch("/notes/quick",{method:"POST",body:new URLSearchParams({title:t})});if(!e.ok)throw Error(`quick ${e.status}`);let n=(await e.text()).trim();if(!n)throw Error("empty note id");return n}function rc(t,e){let n=t.marks.link,r=t.marks.code,i=e.currentNoteId,o=null,s=null,l=null,c=[],d=!1,f=[],h=0,p=!1,m,g=null,b=B("div",{class:"popover slash-menu note-menu",role:"presentation"});b.hidden=!0;let y=B("div",{class:"slash-list",role:"listbox","aria-label":C("noteMenu")}),S=B("div",{class:"slash-footer","aria-hidden":"true"},Gt("↑","↓"),` ${C("navigate")} `,Gt("↵"),` ${C("insert")} `,Gt("Esc"),` ${C("close")}`);b.append(y,S),b.addEventListener("mousedown",(D)=>D.preventDefault());function L(D){if(D.kind==="create")return D.title;return D.hit.title.trim()||C("untitled")}function U(D){return D.kind==="create"?C("createNote",{q:D.title}):L(D)}function et(D){let A=c.map((jt)=>({kind:"note",hit:jt})),N=D.trim(),rt=c.some((jt)=>jt.title.trim().toLowerCase()===N.toLowerCase());if(N&&!rt)A.push({kind:"create",title:N});return A}function at(){clearTimeout(m),g?.abort(),g=null}function Ft(){at(),s=null,f=[],c=[],d=!1,h=0,b.hidden=!0,o?.dom.removeAttribute("aria-activedescendant")}async function z(D){let A=new AbortController;g=A;try{let N=await fetch(`/notes/titles.json?q=${encodeURIComponent(D)}`,{signal:A.signal,headers:{accept:"application/json"}});if(!N.ok)throw Error(`titles ${N.status}`);let rt=await N.json();if(A.signal.aborted)return;c=Dh(rt).filter((jt)=>jt.id!==i)}catch(N){if(A.signal.aborted)return;console.error("note search failed",N),c=[]}if(g===A)g=null;d=!0,V()}function Y(D){at(),d=!1,m=setTimeout(()=>void z(D),Eh)}function Z(){if(!o)return;let D=y.querySelectorAll(".slash-item");D.forEach((N,rt)=>N.setAttribute("aria-selected",String(rt===h)));let A=D[h];if(A)o.dom.setAttribute("aria-activedescendant",A.id),A.scrollIntoView({block:"nearest"})}function P(D){h=D,Z()}function V(){if(!o||!s)return;if(f=et(s.query),h>=f.length)h=0;if(f.length===0){y.replaceChildren(...d?[B("div",{class:"slash-empty",role:"presentation"},C("noNotesFound"))]:[]),o.dom.removeAttribute("aria-activedescendant");return}y.replaceChildren(...f.map((D,A)=>{let N=B("div",{class:"slash-item",role:"option",id:`note-opt-${A}`,"aria-selected":String(A===h)},B("span",{class:"slash-label"},U(D)));return N.addEventListener("mouseenter",()=>P(A)),N.addEventListener("click",()=>Vt(D)),N})),Z()}function j(D){if(!s)return;In(b,xn(D,s.from,D.state.selection.from),"below")}function X(D,A,N,rt,jt){let Et=D.state.tr.replaceWith(A,N,t.text(rt,[n.create({href:`/notes/${jt}`})])),Ht=A+rt.length;Et.insert(Ht,t.text(" ")),Et.setSelection(R.create(Et.doc,Ht+1)),Et.setStoredMarks([]),D.dispatch(Et.scrollIntoView()),D.focus()}async function nt(D,A,N,rt){let jt=D.state.doc.textBetween(A,N);p=!0;let Et;try{Et=await Th(rt)}catch(ni){console.error("note create failed",ni);return}finally{p=!1}let Ht=o;if(!Ht)return;let On=Ht.state.selection;if(!On.empty||On.from!==N||Ht.state.doc.textBetween(A,N)!==jt)return;X(Ht,A,N,rt,Et)}function Vt(D){let A=o;if(!A||!s||p)return;let{from:N}=s,rt=A.state.selection.from;if(D.kind==="note"){X(A,N,rt,L(D),D.hit.id);return}nt(A,N,rt,D.title)}function ge(D){o=D;let A=Nh(D.state,r);if(!A){l=null,Ft();return}if(A.from===l){Ft();return}let N=!s||A.from!==s.from||A.query!==s.query;if(s=A,N)h=0,Y(A.query);if(b.hidden=!1,N)V();j(D)}return{plugins:[new st({props:{handleKeyDown(D,A){if(!s)return!1;let N=f.length;if(A.key==="Escape")return l=s.from,Ft(),!0;if(A.key==="ArrowDown"&&N)return P((h+1)%N),!0;if(A.key==="ArrowUp"&&N)return P((h-1+N)%N),!0;if((A.key==="Enter"||A.key==="Tab")&&N){if(!p)Vt(f[h]);return!0}return!1},handleDOMEvents:{click(D,A){if(!(A.ctrlKey||A.metaKey))return!1;let rt=A.target?.closest?.("a")?.getAttribute("href");if(!rt||!Gr(rt))return!1;return A.preventDefault(),location.assign(rt),!0}}},view(D){o=D,document.body.append(b);let A=()=>{if(o)j(o)};return window.addEventListener("scroll",A,{capture:!0,passive:!0}),window.addEventListener("resize",A),{update(N){ge(N)},destroy(){window.removeEventListener("scroll",A,{capture:!0}),window.removeEventListener("resize",A),at(),b.remove(),o=null}}}})]}}function Rh(t){let{selection:e}=t;if(!(e instanceof R)||!e.empty)return null;let n=e.$from;if(!n.parent.isTextblock||n.parent.type.spec.code)return null;let r=n.parent.textBetween(0,n.parentOffset,void 0,` +`),i=/(?:^|\s)\/([^\s/]*)$/.exec(r);if(!i)return null;return{from:n.pos-i[1].length-1,query:i[1]}}function Lh(t,e,n,r){let i=null;return t.doc.nodesBetween(e,n,(o)=>{if(i!==null)return!1;let s=r.isInSet(o.marks);if(s)i=String(s.attrs.href);return i===null}),i}function ic(t,e){let{strong:n,em:r,code:i,link:o}=t.marks,{heading:s}=t.nodes,l=null,c=!1,d=null,f=null,h="",p=0,m=[],g=null,b=[{id:"bold",label:C("bold"),glyph:"B",keys:[Q,"B"],run:e.bold,active:(v)=>re(v,n)},{id:"italic",label:C("italic"),glyph:"I",keys:[Q,"I"],run:e.italic,active:(v)=>re(v,r)},{id:"code",label:C("inlineCode"),glyph:"",keys:[Q,"E"],run:e.inlineCode,active:(v)=>re(v,i)},{id:"link",label:C("link"),glyph:"Link",keys:[Q,"K"],run:e.link,active:(v)=>re(v,o)},{id:"h1",label:C("heading1"),glyph:"H1",keys:[Q,Xt,"1"],run:e.heading(1),active:(v)=>_e(v,s,{level:1})},{id:"h2",label:C("heading2"),glyph:"H2",keys:[Q,Xt,"2"],run:e.heading(2),active:(v)=>_e(v,s,{level:2})},{id:"h3",label:C("heading3"),glyph:"H3",keys:[Q,Xt,"3"],run:e.heading(3),active:(v)=>_e(v,s,{level:3})}],y=B("div",{class:"bubble",role:"toolbar","aria-label":C("bubbleLabel")});y.hidden=!0;let S=b.map((v)=>{let O=B("button",{type:"button",class:"bubble-btn","aria-label":v.label,"data-command":v.id},B("span",{class:"bubble-glyph","aria-hidden":"true"},v.glyph),Xr(v.label,v.keys));return O.addEventListener("click",()=>{if(!l)return;if(v.run(l.state,l.dispatch,l),v.id!=="link")l.focus()}),y.append(O),{btn:O,item:v}});y.addEventListener("mousedown",(v)=>v.preventDefault());let L=B("div",{class:"popover link-popover",role:"dialog","aria-label":C("linkDialog")});L.hidden=!0;let U=B("form",{class:"link-edit",novalidate:""}),et=B("input",{type:"text",class:"link-input",inputmode:"url",autocomplete:"off",autocapitalize:"off",spellcheck:"false",placeholder:"https://","aria-label":C("linkUrl"),"aria-describedby":"link-error"}),at=B("p",{class:"link-error",id:"link-error",role:"alert"});at.hidden=!0;let Ft=B("button",{type:"submit",class:"btn btn-primary"},C("apply"),Gt("↵")),z=B("button",{type:"button",class:"btn"},C("remove")),Y=B("button",{type:"button",class:"btn"},C("open"));U.append(B("div",{class:"link-row"},et,Ft),at,B("div",{class:"link-actions"},z,Y));let Z=B("div",{class:"link-view",role:"menu","aria-label":C("linkMenu")}),P=B("span",{class:"link-href"}),V=B("button",{type:"button",class:"btn",role:"menuitem"},C("edit")),j=B("button",{type:"button",class:"btn",role:"menuitem"},C("remove")),X=B("button",{type:"button",class:"btn",role:"menuitem"},C("open"));Z.append(P,B("div",{class:"link-actions",role:"none"},V,j,X)),L.append(U,Z);function nt(v){if(!d)return;if(d=null,L.hidden=!0,v)l?.focus()}function Vt(v,O,W,H){Et();let dt=Lh(v.state,O,W,o);d={from:O,to:W,mode:H,href:dt},L.hidden=!1,U.hidden=H!=="edit",Z.hidden=H!=="view",at.hidden=!0,et.removeAttribute("aria-invalid"),et.value=dt??"",P.textContent=dt??"";for(let Kt of[z,Y,j,X])Kt.disabled=dt===null,Kt.title=dt===null?C("linkNeedsLink"):"";if(Mn(v),H==="edit")et.focus(),et.select();else V.focus()}function ge(v){let O=v.state.selection,W=O.empty?Yr(v.state.doc,O.from,o):{from:O.from,to:O.to};if(!W)return;Vt(v,W.from,W.to,"edit")}U.addEventListener("submit",(v)=>{if(v.preventDefault(),!d||!l)return;let O=ec(et.value);if(!O){at.textContent=C("linkInvalid"),at.hidden=!1,et.setAttribute("aria-invalid","true"),et.focus();return}let{from:W,to:H}=d;nt(!1),l.dispatch(l.state.tr.removeMark(W,H,o).addMark(W,H,o.create({href:O}))),l.focus()});function Cn(){if(!d||!l)return;let{from:v,to:O}=d;nt(!1),l.dispatch(l.state.tr.removeMark(v,O,o)),l.focus()}function D(){if(!d?.href)return;if(Gr(d.href)){location.assign(d.href);return}window.open(d.href,"_blank","noopener,noreferrer")}z.addEventListener("click",Cn),j.addEventListener("click",Cn),Y.addEventListener("click",D),X.addEventListener("click",D),V.addEventListener("click",()=>{if(l&&d)Vt(l,d.from,d.to,"edit")}),L.addEventListener("keydown",(v)=>{if(v.key==="Escape"){v.preventDefault(),v.stopPropagation(),nt(!0);return}if((v.key==="ArrowDown"||v.key==="ArrowUp")&&!Z.hidden){let O=[V,j,X].filter((Kt)=>!Kt.disabled),W=O.indexOf(document.activeElement),H=v.key==="ArrowDown"?1:-1,dt=O[(W+H+O.length)%O.length];if(dt)v.preventDefault(),dt.focus()}});let A=[{id:"text",label:C("paragraph"),keywords:"text paragraph p",keys:[Q,Xt,"0"],run:e.paragraph},{id:"h1",label:C("heading1"),keywords:"heading title h1",keys:[Q,Xt,"1"],run:e.heading(1)},{id:"h2",label:C("heading2"),keywords:"heading subtitle h2",keys:[Q,Xt,"2"],run:e.heading(2)},{id:"h3",label:C("heading3"),keywords:"heading h3",keys:[Q,Xt,"3"],run:e.heading(3)},{id:"bullets",label:C("bulletList"),keywords:"list ul bullet unordered",keys:[Q,Qe,"8"],run:e.bulletList},{id:"ordered",label:C("numberedList"),keywords:"list ol number ordered",keys:[Q,Qe,"9"],run:e.orderedList},{id:"quote",label:C("quote"),keywords:"blockquote quote",keys:[">"],run:e.blockquote},{id:"codeblock",label:C("codeBlock"),keywords:"code pre fence",keys:["```"],run:e.codeBlock},{id:"divider",label:C("divider"),keywords:"hr rule line divider",keys:["---"],run:e.horizontalRule}],N=B("div",{class:"popover slash-menu",role:"presentation"});N.hidden=!0;let rt=B("div",{class:"slash-list",role:"listbox","aria-label":C("blockMenu")}),jt=B("div",{class:"slash-footer","aria-hidden":"true"},Gt("↑","↓"),` ${C("navigate")} `,Gt("↵"),` ${C("insert")} `,Gt("Esc"),` ${C("close")}`);N.append(rt,jt),N.addEventListener("mousedown",(v)=>v.preventDefault());function Et(){f=null,N.hidden=!0,l?.dom.removeAttribute("aria-activedescendant")}function Ht(){if(!l||f===null)return;let v=h.toLowerCase();if(m=A.filter((W)=>!v||W.label.toLowerCase().includes(v)||W.keywords.split(" ").some((H)=>H.startsWith(v))),p>=m.length)p=0;if(m.length===0){rt.replaceChildren(B("div",{class:"slash-empty",role:"presentation"},C("noMatches"))),l.dom.removeAttribute("aria-activedescendant");return}rt.replaceChildren(...m.map((W,H)=>{let dt=B("div",{class:"slash-item",role:"option",id:`slash-opt-${W.id}`,"aria-selected":String(H===p)},B("span",{class:"slash-label"},W.label),Gt(...W.keys));return dt.addEventListener("click",()=>On(W)),dt}));let O=m[p];l.dom.setAttribute("aria-activedescendant",`slash-opt-${O.id}`),rt.querySelector(`#slash-opt-${O.id}`)?.scrollIntoView({block:"nearest"})}function On(v){let O=l;if(!O||f===null)return;let W=f,H=O.state.selection.from;Et(),O.dispatch(O.state.tr.delete(W,H)),v.run(O.state,O.dispatch,O),O.focus()}function ni(v){let O=Rh(v.state);if(!O){g=null,Et();return}if(O.from===g||d){Et();return}if(O.from!==f||O.query!==h)p=0;f=O.from,h=O.query,N.hidden=!1,Ht()}function To(v){let O=v.state.selection;return O instanceof R&&!O.empty&&!v.composing&&!c&&d===null}function Mn(v){l=v;let O=v.state,W=To(v);if(y.hidden=!W,W){for(let{btn:H,item:dt}of S){let Kt=dt.active(O);H.dataset.active=String(Kt),H.setAttribute("aria-pressed",String(Kt)),H.disabled=!dt.run(O)}In(y,xn(v,O.selection.from,O.selection.to),"above")}if(d)In(L,xn(v,d.from,d.to),"above");if(f!==null&&!N.hidden)In(N,xn(v,f,O.selection.from),"below")}return{plugins:[new st({props:{handleKeyDown(v,O){if(f!==null){let W=m.length;if(O.key==="ArrowDown"&&W)return p=(p+1)%W,Ht(),!0;if(O.key==="ArrowUp"&&W)return p=(p-1+W)%W,Ht(),!0;if(O.key==="Enter"&&W)return On(m[p]),!0;if(O.key==="Escape")return g=f,Et(),!0}if(O.key==="Escape"&&To(v))return c=!0,Mn(v),!0;return!1},handleClick(v,O,W){let dt=W.target?.closest?.("a");if(!dt)return!1;if((W.ctrlKey||W.metaKey)&&Gr(dt.getAttribute("href")))return!1;let Kt=Yr(v.state.doc,O,o);if(Kt)Vt(v,Kt.from,Kt.to,"view");return!1}},view(v){l=v,document.body.append(y,L,N);let O=()=>{if(l)Mn(l)},W=(H)=>{if(d&&!L.contains(H.target))nt(!1)};return window.addEventListener("scroll",O,{capture:!0,passive:!0}),window.addEventListener("resize",O),document.addEventListener("mousedown",W,!0),Mn(v),{update(H,dt){if(!dt.selection.eq(H.state.selection))c=!1;if(d&&H.state.doc!==dt.doc)nt(!1);ni(H),Mn(H)},destroy(){window.removeEventListener("scroll",O,{capture:!0}),window.removeEventListener("resize",O),document.removeEventListener("mousedown",W,!0),y.remove(),L.remove(),N.remove(),l=null}}}})],openLink:ge}}var At={undo:'',redo:'',paragraph:'',h1:'',h2:'',h3:'',bold:'',italic:'',code:'',link:'',bullets:'',ordered:'',quote:'',codeBlock:'',rule:''};function Ph(t,e,n){let{paragraph:r,heading:i,code_block:o,blockquote:s,bullet_list:l,ordered_list:c}=t.nodes,{strong:d,em:f,code:h,link:p}=t.marks,m=(b)=>({id:`h${b}`,label:C(`heading${b}`),keys:[Q,Xt,String(b)],icon:b===1?At.h1:b===2?At.h2:At.h3,run:e.heading(b),isActive:(y)=>_e(y,i,{level:b})}),g=(b)=>(y)=>lr(y,(S)=>S.type===b)!==null;return[{id:"undo",label:C("undo"),keys:[Q,"Z"],icon:At.undo,run:n.undo},{id:"redo",label:C("redo"),keys:[Q,Qe,"Z"],icon:At.redo,run:n.redo},"|",{id:"paragraph",label:C("paragraph"),keys:[Q,Xt,"0"],icon:At.paragraph,run:e.paragraph,isActive:(b)=>_e(b,r)},m(1),m(2),m(3),"|",{id:"bold",label:C("bold"),keys:[Q,"B"],icon:At.bold,run:e.bold,isActive:(b)=>re(b,d)},{id:"italic",label:C("italic"),keys:[Q,"I"],icon:At.italic,run:e.italic,isActive:(b)=>re(b,f)},{id:"code",label:C("inlineCode"),keys:[Q,"E"],icon:At.code,run:e.inlineCode,isActive:(b)=>re(b,h)},{id:"link",label:C("link"),keys:[Q,"K"],icon:At.link,run:e.link,isActive:(b)=>re(b,p)},"|",{id:"bullets",label:C("bulletList"),keys:[Q,Qe,"8"],icon:At.bullets,run:e.bulletList,isActive:g(l)},{id:"ordered",label:C("numberedList"),keys:[Q,Qe,"9"],icon:At.ordered,run:e.orderedList,isActive:g(c)},{id:"quote",label:C("quote"),keys:[">"],icon:At.quote,run:e.blockquote,isActive:(b)=>lr(b,(y)=>y.type===s)!==null},{id:"codeblock",label:C("codeBlock"),keys:["```"],icon:At.codeBlock,run:e.codeBlock,isActive:(b)=>_e(b,o)},{id:"rule",label:C("divider"),keys:["---"],icon:At.rule,run:e.horizontalRule}]}var oc=["history","headings","marks","blocks"];function sc(t,e,n,r){let i=document.getElementById("editor-toolbar");if(!i)i=document.createElement("div"),i.id="editor-toolbar",t.before(i);i.classList.add("editor-toolbar"),i.setAttribute("role","toolbar"),i.setAttribute("aria-label",C("toolbarLabel"));let o=null,s=[],l=B("div",{class:"editor-toolbar-group","data-group":oc[0]});i.append(l);let c=0;for(let p of Ph(e,n,r)){if(p==="|"){c+=1,l=B("div",{class:"editor-toolbar-group","data-group":oc[c]}),i.append(l);continue}let m=B("button",{type:"button",class:"editor-toolbar-btn","aria-label":p.label,"aria-keyshortcuts":Bh(p.keys),"data-command":p.id,tabindex:"-1"},B("span",{class:"editor-toolbar-icon","aria-hidden":"true"}),Xr(p.label,p.keys,C("unavailable")));m.querySelector(".editor-toolbar-icon").innerHTML=``,m.disabled=!0,m.addEventListener("click",()=>{if(!o)return;p.run(o.state,o.dispatch,o),o.focus()}),l.append(m),s.push({btn:m,item:p,enabled:!1})}i.addEventListener("mousedown",(p)=>p.preventDefault());let d=()=>s.map((p)=>p.btn).filter((p)=>!p.disabled),f=(p)=>{for(let{btn:m}of s)m.tabIndex=m===p?0:-1};i.addEventListener("keydown",(p)=>{let m=d();if(!m.length)return;let g=m.indexOf(document.activeElement),b;if(p.key==="ArrowRight")b=m[(g+1+m.length)%m.length];else if(p.key==="ArrowLeft")b=m[(g-1+m.length)%m.length];else if(p.key==="Home")b=m[0];else if(p.key==="End")b=m[m.length-1];if(!b)return;p.preventDefault(),f(b),b.focus()});let h=(p)=>{for(let g of s)if(g.enabled=!!g.item.run(p),g.btn.disabled=!g.enabled,g.item.isActive){let b=g.item.isActive(p);g.btn.dataset.active=String(b),g.btn.setAttribute("aria-pressed",String(b))}let m=s.find((g)=>g.btn.tabIndex===0&&!g.btn.disabled)?.btn??d()[0];if(m)f(m)};return new st({view(p){return o=p,h(p.state),{update(m){h(m.state)},destroy(){o=null}}}})}function Bh(t){let e={Ctrl:"Control","⌘":"Meta",Shift:"Shift","⇧":"Shift",Alt:"Alt","⌥":"Alt"};return t.map((n)=>e[n]??n).join("+")}await _i({module_or_path:new URL("/loro-856987111b05.wasm",location.origin)});var dc=1,Oo=2,Mo=3,zh={...$r.spec.nodes.get("code_block"),attrs:{language:{default:null}},parseDOM:[{tag:"pre",preserveWhitespace:"full",getAttrs:(t)=>({language:t.dataset.language||null})}],toDOM:(t)=>["pre",t.attrs.language?{"data-language":t.attrs.language}:{},["code",0]]},Qt=new sn({nodes:Ta($r.spec.nodes.update("code_block",zh),"paragraph block*","block"),marks:$r.spec.marks});function Fh(){let e=null;try{let n=sessionStorage.getItem("project-note-peer");if(n)e=JSON.parse(n)}catch{e=null}if(!e){let n=1000+Math.floor(Math.random()*9000),r=Math.floor(Math.random()*360);e={name:`user-${n}`,color:`hsl(${r} 70% 45%)`};try{sessionStorage.setItem("project-note-peer",JSON.stringify(e))}catch{}}return e}var vn=document.getElementById("editor");if(!vn)throw Error("#editor element not found");var uc=vn.dataset.noteId??"",Vh=vn.dataset.noteTitle?.trim()||document.querySelector("header span.truncate")?.textContent?.trim()||"Note",Ne=new Pt,Wh=Fh(),cr=new Ea(Ne.peerIdStr),lc=tp(vn),qh=ep();function Uh(t){let n=cr.getAll()[t]?.user?.color??"currentColor";return{class:"loro-selection","data-peer":t,style:`background-color: color-mix(in srgb, ${n} 28%, transparent)`}}var No=nc(Qt,{requestLink:(t)=>fc.openLink(t)}),fc=ic(Qt,No),$h=sc(vn,Qt,No,{undo:_o,redo:Ur}),Jh=rc(Qt,{currentNoteId:uc}),jh=yn({Enter:La(Qt.nodes.list_item),Tab:Pa(Qt.nodes.list_item),"Shift-Tab":Jr(Qt.nodes.list_item),"Mod-b":pe(Qt.marks.strong),"Mod-i":pe(Qt.marks.em),"Mod-`":pe(Qt.marks.code)}),Hh=ye.create({schema:Qt,plugins:[Ma({doc:Ne}),Da({doc:Ne}),yn({"Mod-z":_o,"Mod-y":Ur,"Shift-Mod-z":Ur}),...fc.plugins,...Jh.plugins,jh,...No.plugins,yn(Ha),$h,Na(cr,{user:Wh,createSelection:Uh})]}),Zr=null,ti=null;function ac(){if(Zr||!ti)return;let t=Ne.oplogVersion(),e=ti.compare(t);if(e===void 0||e>0)return;Zr=new Zn(vn,{state:Hh,attributes:{role:"textbox","aria-multiline":"true","aria-label":Vh}})}var Kh=`${location.protocol==="https:"?"wss":"ws"}://${location.host}/notes/${encodeURIComponent(uc)}/ws`,hc=500,Yh=5000,Ee=null,Qr=hc,ei=!1;function Xh(t,e){let n=new Uint8Array(e.length+1);return n[0]=t,n.set(e,1),n}function pc(){return Ee!==null&&Ee.readyState===WebSocket.OPEN}function dr(t,e){if(pc())Ee.send(Xh(t,e))}var Gh={connecting:"statusConnecting",reconnecting:"statusReconnecting",saved:"statusSaved",saving:"statusSaving",local:"statusLocal"},_c=!1,gc=!1,ar=!1,Do=!1,Ao,Eo;function Qh(){if(navigator.onLine===!1)return"local";if(!_c)return gc?"reconnecting":"connecting";return Do?"saving":"saved"}function Sn(){let t=Qh();lc.dataset.state=t,lc.textContent=C(Gh[t])}function Zh(){if(!ar)ar=!0,clearTimeout(Ao),Ao=setTimeout(()=>{if(ar)Do=!0,Sn()},1500);clearTimeout(Eo),Eo=setTimeout(mc,300)}function mc(){if(!ar)return;if(pc()&&Ee.bufferedAmount>0){Eo=setTimeout(mc,100);return}ar=!1,clearTimeout(Ao),Do=!1,Sn()}function cc(t){if(_c=t,t)gc=!0;Sn()}function tp(t){let e=document.getElementById("sync-status");if(!e){e=document.createElement("span"),e.id="sync-status";let n=document.getElementById("sync-slot");if(n)n.append(e);else t.before(e)}return e}function ep(){let t=B("div",{class:"sr-only",role:"status","aria-live":"polite"});return document.body.append(t),t}function bc(t){qh.textContent=t}window.addEventListener("offline",()=>{Sn(),bc(C("announceOffline"))});window.addEventListener("online",()=>{Sn(),bc(C("announceOnline"))});Ne.subscribeLocalUpdates((t)=>{dr(Oo,t),Zh()});cr.subscribeLocalUpdates((t)=>{if(ei)dr(Mo,t)});function np(t){if(typeof t==="string")return;let e=new Uint8Array(t);if(e.length===0)return;let n=e[0],r=e.subarray(1);switch(n){case dc:{let i=Dt.decode(r),o=Ne.export({mode:"update",from:i});if(dr(Oo,o),!ei)ei=!0,dr(Mo,cr.encodeAll());if(!ti)ti=i,ac();break}case Oo:try{Ne.import(r),ac()}catch(i){console.error("failed to import update",i)}break;case Mo:try{cr.apply(r)}catch(i){console.error("failed to apply presence",i)}break;default:console.warn("unknown frame tag",n)}}function wc(){let t=new WebSocket(Kh);t.binaryType="arraybuffer",Ee=t,t.onopen=()=>{Qr=hc,cc(!0),ei=!1,dr(dc,Ne.oplogVersion().encode())},t.onmessage=(e)=>np(e.data),t.onerror=()=>{t.close()},t.onclose=()=>{if(Ee===t)Ee=null;if(yc)return;cc(!1),setTimeout(wc,Qr),Qr=Math.min(Qr*2,Yh)}}var yc=!1;window.addEventListener("note:detach",()=>{yc=!0,Ee?.close(),Zr?.destroy(),Zr=null});Sn();wc(); + +//# debugId=0E2F6C17ACB8E4C864756E2164756E21 +//# sourceMappingURL=editor.js.map diff --git a/assets/editor.js.map b/assets/editor.js.map new file mode 100644 index 0000000..aa38022 --- /dev/null +++ b/assets/editor.js.map @@ -0,0 +1,37 @@ +{ + "version": 3, + "sources": ["../web/node_modules/loro-crdt/web/snippets/loro-wasm-974365e04a0511fb/inline0.js", "../web/node_modules/loro-crdt/web/loro_wasm.js", "../web/node_modules/loro-crdt/web/index.js", "../web/node_modules/orderedmap/dist/index.js", "../web/node_modules/prosemirror-model/dist/index.js", "../web/node_modules/prosemirror-transform/dist/index.js", "../web/node_modules/prosemirror-state/dist/index.js", "../web/node_modules/prosemirror-view/dist/index.js", "../web/node_modules/lib0/trait/equality.js", "../web/node_modules/lib0/object.js", "../web/node_modules/lib0/function.js", "../web/node_modules/lib0/diff.js", "../web/node_modules/loro-prosemirror/dist/index.js", "../web/node_modules/prosemirror-schema-basic/dist/index.js", "../web/node_modules/prosemirror-schema-list/dist/index.js", "../web/node_modules/w3c-keyname/index.js", "../web/node_modules/prosemirror-keymap/dist/index.js", "../web/node_modules/prosemirror-commands/dist/index.js", "../web/src/i18n.ts", "../web/node_modules/prosemirror-inputrules/dist/index.js", "../web/node_modules/prosemirror-dropcursor/dist/index.js", "../web/node_modules/prosemirror-gapcursor/dist/index.js", "../web/src/editing.ts", "../web/src/dom.ts", "../web/src/noteLinks.ts", "../web/src/floating.ts", "../web/src/toolbar.ts", "../web/src/editor.ts"], + "sourcesContent": [ + "\nconst kinds = ['Map', 'List', 'MovableList', 'Text', 'Tree', 'Counter'];\nexport function stateOptions(options, document) {\n if (typeof options !== 'object' || options === null || Array.isArray(options)) throw new Error('Invalid toContainerTree options');\n for (const key of Object.keys(options)) {\n if (key !== 'text' && !(document && key === 'roots')) throw new Error('Unknown toContainerTree option: ' + key);\n }\n if (document && options.roots !== undefined && !Array.isArray(options.roots)) throw new Error('roots must be an array');\n return options;\n}\nexport function stateSlice(node, start, totalLength) { return {cid:node.cid, start, totalLength, items:node.value}; }\nexport function stateContainer(kind, cid, value) { return {type: kinds[kind], cid, value}; }\nexport function stateCid(peer,counter,kind) { return 'cid:'+counter+'@'+peer+':'+kinds[kind]; }\nexport function stateRootCid(name,kind) { return 'cid:root-'+name+':'+kinds[kind]; }\nexport function stateValue(value) { return {type: 'Value', value}; }\nexport function stateBinary(bytes) { return bytes.slice(); }\nexport function stateIndex(array, index, value) { Object.defineProperty(array, index, {value, enumerable: true, writable: true, configurable: true}); }\nexport function stateSet(object, key, value) { Object.defineProperty(object, key, {value, enumerable: true, writable: true, configurable: true}); }\n", + "import { stateBinary, stateCid, stateContainer, stateIndex, stateOptions, stateRootCid, stateSet, stateSlice, stateValue } from './snippets/loro-wasm-974365e04a0511fb/inline0.js';\n\nlet wasm;\n\nconst heap = new Array(128).fill(undefined);\n\nheap.push(undefined, null, true, false);\n\nfunction getObject(idx) { return heap[idx]; }\n\nlet WASM_VECTOR_LEN = 0;\n\nlet cachedUint8ArrayMemory0 = null;\n\nfunction getUint8ArrayMemory0() {\n if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {\n cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachedUint8ArrayMemory0;\n}\n\nconst cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder('utf-8') : { encode: () => { throw Error('TextEncoder not available') } } );\n\nconst encodeString = (typeof cachedTextEncoder.encodeInto === 'function'\n ? function (arg, view) {\n return cachedTextEncoder.encodeInto(arg, view);\n}\n : function (arg, view) {\n const buf = cachedTextEncoder.encode(arg);\n view.set(buf);\n return {\n read: arg.length,\n written: buf.length\n };\n});\n\nfunction passStringToWasm0(arg, malloc, realloc) {\n\n if (realloc === undefined) {\n const buf = cachedTextEncoder.encode(arg);\n const ptr = malloc(buf.length, 1) >>> 0;\n getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);\n WASM_VECTOR_LEN = buf.length;\n return ptr;\n }\n\n let len = arg.length;\n let ptr = malloc(len, 1) >>> 0;\n\n const mem = getUint8ArrayMemory0();\n\n let offset = 0;\n\n for (; offset < len; offset++) {\n const code = arg.charCodeAt(offset);\n if (code > 0x7F) break;\n mem[ptr + offset] = code;\n }\n\n if (offset !== len) {\n if (offset !== 0) {\n arg = arg.slice(offset);\n }\n ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;\n const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);\n const ret = encodeString(arg, view);\n\n offset += ret.written;\n ptr = realloc(ptr, len, offset, 1) >>> 0;\n }\n\n WASM_VECTOR_LEN = offset;\n return ptr;\n}\n\nlet cachedDataViewMemory0 = null;\n\nfunction getDataViewMemory0() {\n if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {\n cachedDataViewMemory0 = new DataView(wasm.memory.buffer);\n }\n return cachedDataViewMemory0;\n}\n\nlet heap_next = heap.length;\n\nfunction addHeapObject(obj) {\n if (heap_next === heap.length) heap.push(heap.length + 1);\n const idx = heap_next;\n heap_next = heap[idx];\n\n heap[idx] = obj;\n return idx;\n}\n\nfunction handleError(f, args) {\n try {\n return f.apply(this, args);\n } catch (e) {\n wasm.__wbindgen_exn_store(addHeapObject(e));\n }\n}\n\nconst cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } );\n\nif (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); };\n\nfunction getStringFromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));\n}\n\nfunction dropObject(idx) {\n if (idx < 132) return;\n heap[idx] = heap_next;\n heap_next = idx;\n}\n\nfunction takeObject(idx) {\n const ret = getObject(idx);\n dropObject(idx);\n return ret;\n}\n\nfunction getArrayU8FromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);\n}\n\nfunction isLikeNone(x) {\n return x === undefined || x === null;\n}\n\nconst CLOSURE_DTORS = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(state => {\n wasm.__wbindgen_export_4.get(state.dtor)(state.a, state.b)\n});\n\nfunction makeMutClosure(arg0, arg1, dtor, f) {\n const state = { a: arg0, b: arg1, cnt: 1, dtor };\n const real = (...args) => {\n // First up with a closure we increment the internal reference\n // count. This ensures that the Rust closure environment won't\n // be deallocated while we're invoking it.\n state.cnt++;\n const a = state.a;\n state.a = 0;\n try {\n return f(a, state.b, ...args);\n } finally {\n if (--state.cnt === 0) {\n wasm.__wbindgen_export_4.get(state.dtor)(a, state.b);\n CLOSURE_DTORS.unregister(state);\n } else {\n state.a = a;\n }\n }\n };\n real.original = state;\n CLOSURE_DTORS.register(real, state, state);\n return real;\n}\n\nfunction debugString(val) {\n // primitive types\n const type = typeof val;\n if (type == 'number' || type == 'boolean' || val == null) {\n return `${val}`;\n }\n if (type == 'string') {\n return `\"${val}\"`;\n }\n if (type == 'symbol') {\n const description = val.description;\n if (description == null) {\n return 'Symbol';\n } else {\n return `Symbol(${description})`;\n }\n }\n if (type == 'function') {\n const name = val.name;\n if (typeof name == 'string' && name.length > 0) {\n return `Function(${name})`;\n } else {\n return 'Function';\n }\n }\n // objects\n if (Array.isArray(val)) {\n const length = val.length;\n let debug = '[';\n if (length > 0) {\n debug += debugString(val[0]);\n }\n for(let i = 1; i < length; i++) {\n debug += ', ' + debugString(val[i]);\n }\n debug += ']';\n return debug;\n }\n // Test for built-in\n const builtInMatches = /\\[object ([^\\]]+)\\]/.exec(toString.call(val));\n let className;\n if (builtInMatches && builtInMatches.length > 1) {\n className = builtInMatches[1];\n } else {\n // Failed to match the standard '[object ClassName]'\n return toString.call(val);\n }\n if (className == 'Object') {\n // we're a user defined class or Object\n // JSON.stringify avoids problems with cycles, and is generally much\n // easier than looping through ownProperties of `val`.\n try {\n return 'Object(' + JSON.stringify(val) + ')';\n } catch (_) {\n return 'Object';\n }\n }\n // errors\n if (val instanceof Error) {\n return `${val.name}: ${val.message}\\n${val.stack}`;\n }\n // TODO we could test for more things here, like `Set`s and `Map`s.\n return className;\n}\n/**\n * Get the version of Loro\n * @returns {string}\n */\nexport function LORO_VERSION() {\n let deferred1_0;\n let deferred1_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.LORO_VERSION(retptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n deferred1_0 = r0;\n deferred1_1 = r1;\n return getStringFromWasm0(r0, r1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n}\n\nfunction passArray8ToWasm0(arg, malloc) {\n const ptr = malloc(arg.length * 1, 1) >>> 0;\n getUint8ArrayMemory0().set(arg, ptr / 1);\n WASM_VECTOR_LEN = arg.length;\n return ptr;\n}\n/**\n * Decode the metadata of the import blob.\n *\n * This method is useful to get the following metadata of the import blob:\n *\n * - startVersionVector\n * - endVersionVector\n * - startTimestamp\n * - endTimestamp\n * - mode\n * - changeNum\n * @param {Uint8Array} blob\n * @param {boolean} check_checksum\n * @returns {ImportBlobMetadata}\n */\nexport function decodeImportBlobMeta(blob, check_checksum) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(blob, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.decodeImportBlobMeta(retptr, ptr0, len0, check_checksum);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n}\n\nexport function callPendingEvents() {\n wasm.callPendingEvents();\n}\n\n/**\n * Redacts sensitive content in JSON updates within the specified version range.\n *\n * This function allows you to share document history while removing potentially sensitive content.\n * It preserves the document structure and collaboration capabilities while replacing content with\n * placeholders according to these redaction rules:\n *\n * - Preserves delete and move operations\n * - Replaces text insertion content with the Unicode replacement character\n * - Substitutes list and map insert values with null\n * - Maintains structure of child containers\n * - Replaces text mark values with null\n * - Preserves map keys and text annotation keys\n *\n * @param {Object|string} jsonUpdates - The JSON updates to redact (object or JSON string)\n * @param {Object} versionRange - Version range defining what content to redact,\n * format: { peerId: [startCounter, endCounter], ... }\n * @returns {Object} The redacted JSON updates\n * @param {string | JsonSchema} json_updates\n * @param {any} version_range\n * @returns {JsonSchema}\n */\nexport function redactJsonUpdates(json_updates, version_range) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.redactJsonUpdates(retptr, addHeapObject(json_updates), addHeapObject(version_range));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n}\n\n/**\n * Returns whether `value` is a syntactically valid container ID.\n * @param {string} value\n * @returns {boolean}\n */\nexport function isValidContainerId(value) {\n const ptr0 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.isValidContainerId(ptr0, len0);\n return ret !== 0;\n}\n\nexport function run() {\n wasm.run();\n}\n\nfunction passArrayJsValueToWasm0(array, malloc) {\n const ptr = malloc(array.length * 4, 4) >>> 0;\n const mem = getDataViewMemory0();\n for (let i = 0; i < array.length; i++) {\n mem.setUint32(ptr + 4 * i, addHeapObject(array[i]), true);\n }\n WASM_VECTOR_LEN = array.length;\n return ptr;\n}\n/**\n * @param {({ peer: PeerID, counter: number })[]} frontiers\n * @returns {Uint8Array}\n */\nexport function encodeFrontiers(frontiers) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(frontiers, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.encodeFrontiers(retptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v2 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v2;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {{ peer: PeerID, counter: number }[]}\n */\nexport function decodeFrontiers(bytes) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.decodeFrontiers(retptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n}\n\n/**\n * Enable debug info of Loro\n */\nexport function setDebug() {\n wasm.setDebug();\n}\n\nlet stack_pointer = 128;\n\nfunction addBorrowedObject(obj) {\n if (stack_pointer == 1) throw new Error('out of js stack');\n heap[--stack_pointer] = obj;\n return stack_pointer;\n}\n\nfunction _assertClass(instance, klass) {\n if (!(instance instanceof klass)) {\n throw new Error(`expected instance of ${klass.name}`);\n }\n}\n\nfunction getArrayJsValueFromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n const mem = getDataViewMemory0();\n const result = [];\n for (let i = ptr; i < ptr + 4 * len; i += 4) {\n result.push(takeObject(mem.getUint32(i, true)));\n }\n return result;\n}\nfunction __wbg_adapter_58(arg0, arg1, arg2) {\n wasm._dyn_core_ed718c3d60ebd546___ops__function__FnMut_______Output______as_wasm_bindgen_cfd5deec16e3bd1c___closure__WasmClosure___describe__invoke___wasm_bindgen_cfd5deec16e3bd1c___JsValue_____(arg0, arg1, addHeapObject(arg2));\n}\n\nfunction __wbg_adapter_61(arg0, arg1) {\n wasm._dyn_core_ed718c3d60ebd546___ops__function__FnMut_____Output______as_wasm_bindgen_cfd5deec16e3bd1c___closure__WasmClosure___describe__invoke______(arg0, arg1);\n}\n\nconst AwarenessWasmFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_awarenesswasm_free(ptr >>> 0, 1));\n/**\n * `Awareness` is a structure that tracks the ephemeral state of peers.\n *\n * It can be used to synchronize cursor positions, selections, and the names of the peers.\n *\n * The state of a specific peer is expected to be removed after a specified timeout. Use\n * `remove_outdated` to eliminate outdated states.\n */\nexport class AwarenessWasm {\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n AwarenessWasmFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_awarenesswasm_free(ptr, 0);\n }\n /**\n * Get the state of all peers.\n * @returns {{[peer in PeerID]: unknown}}\n */\n getAllStates() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.awarenesswasm_getAllStates(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the timestamp of the state of a given peer.\n * @param {number | bigint | `${number}`} peer\n * @returns {number | undefined}\n */\n getTimestamp(peer) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-32);\n wasm.awarenesswasm_getTimestamp(retptr, this.__wbg_ptr, addHeapObject(peer));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r2 = getDataViewMemory0().getFloat64(retptr + 8 * 1, true);\n var r4 = getDataViewMemory0().getInt32(retptr + 4 * 4, true);\n var r5 = getDataViewMemory0().getInt32(retptr + 4 * 5, true);\n if (r5) {\n throw takeObject(r4);\n }\n return r0 === 0 ? undefined : r2;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(32);\n }\n }\n /**\n * Sets the state of the local peer.\n * @param {any} value\n */\n setLocalState(value) {\n wasm.awarenesswasm_setLocalState(this.__wbg_ptr, addHeapObject(value));\n }\n /**\n * Remove the states of outdated peers.\n * @returns {PeerID[]}\n */\n removeOutdated() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.awarenesswasm_removeOutdated(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Creates a new `Awareness` instance.\n *\n * The `timeout` parameter specifies the duration in milliseconds.\n * A state of a peer is considered outdated, if the last update of the state of the peer\n * is older than the `timeout`.\n * @param {number | bigint | `${number}`} peer\n * @param {number} timeout\n */\n constructor(peer, timeout) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.awarenesswasm_new(retptr, addHeapObject(peer), timeout);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n this.__wbg_ptr = r0 >>> 0;\n AwarenessWasmFinalization.register(this, this.__wbg_ptr, this);\n return this;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the PeerID of the local peer.\n * @returns {PeerID}\n */\n peer() {\n const ret = wasm.awarenesswasm_peer(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Applies the encoded state of peers.\n *\n * Each peer's deletion countdown will be reset upon update, requiring them to pass through the `timeout`\n * interval again before being eligible for deletion.\n * @param {Uint8Array} encoded_peers_info\n * @returns {{ updated: PeerID[], added: PeerID[] }}\n */\n apply(encoded_peers_info) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(encoded_peers_info, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.awarenesswasm_apply(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get all the peers\n * @returns {PeerID[]}\n */\n peers() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.awarenesswasm_peers(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Encodes the state of the given peers.\n * @param {Array} peers\n * @returns {Uint8Array}\n */\n encode(peers) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.awarenesswasm_encode(retptr, this.__wbg_ptr, addHeapObject(peers));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the number of peers.\n * @returns {number}\n */\n length() {\n const ret = wasm.awarenesswasm_length(this.__wbg_ptr);\n return ret;\n }\n /**\n * If the state is empty.\n * @returns {boolean}\n */\n isEmpty() {\n const ret = wasm.awarenesswasm_isEmpty(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the state of a given peer.\n * @param {number | bigint | `${number}`} peer\n * @returns {any}\n */\n getState(peer) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.awarenesswasm_getState(retptr, this.__wbg_ptr, addHeapObject(peer));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Encodes the state of all peers.\n * @returns {Uint8Array}\n */\n encodeAll() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.awarenesswasm_encodeAll(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst ChangeModifierFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_changemodifier_free(ptr >>> 0, 1));\n\nexport class ChangeModifier {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(ChangeModifier.prototype);\n obj.__wbg_ptr = ptr;\n ChangeModifierFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n ChangeModifierFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_changemodifier_free(ptr, 0);\n }\n /**\n * @param {string} message\n * @returns {ChangeModifier}\n */\n setMessage(message) {\n const ptr0 = passStringToWasm0(message, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.changemodifier_setMessage(this.__wbg_ptr, ptr0, len0);\n return ChangeModifier.__wrap(ret);\n }\n /**\n * @param {number} timestamp\n * @returns {ChangeModifier}\n */\n setTimestamp(timestamp) {\n const ret = wasm.changemodifier_setTimestamp(this.__wbg_ptr, timestamp);\n return ChangeModifier.__wrap(ret);\n }\n}\n\nconst CursorFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_cursor_free(ptr >>> 0, 1));\n/**\n * Cursor is a stable position representation in the doc.\n * When expressing the position of a cursor, using \"index\" can be unstable\n * because the cursor's position may change due to other deletions and insertions,\n * requiring updates with each edit. To stably represent a position or range within\n * a list structure, we can utilize the ID of each item/character on List CRDT or\n * Text CRDT for expression.\n *\n * Loro optimizes State metadata by not storing the IDs of deleted elements. This\n * approach complicates tracking cursors since they rely on these IDs. The solution\n * recalculates position by replaying relevant history to update cursors\n * accurately. To minimize the performance impact of history replay, the system\n * updates cursor info to reference only the IDs of currently present elements,\n * thereby reducing the need for replay.\n *\n * @example\n * ```ts\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"123\");\n * const pos0 = text.getCursor(0, 0);\n * {\n * const ans = doc.getCursorPos(pos0!);\n * expect(ans.offset).toBe(0);\n * }\n * text.insert(0, \"1\");\n * {\n * const ans = doc.getCursorPos(pos0!);\n * expect(ans.offset).toBe(1);\n * }\n * ```\n */\nexport class Cursor {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(Cursor.prototype);\n obj.__wbg_ptr = ptr;\n CursorFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n CursorFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_cursor_free(ptr, 0);\n }\n /**\n * Get the id of the given container.\n * @returns {ContainerID}\n */\n containerId() {\n const ret = wasm.cursor_containerId(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the ID that represents the position.\n *\n * It can be undefined if it's not bind into a specific ID.\n * @returns {{ peer: PeerID, counter: number } | undefined}\n */\n pos() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.cursor_pos(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * \"Cursor\"\n * @returns {any}\n */\n kind() {\n const ret = wasm.cursor_kind(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get which side of the character/list item the cursor is on.\n * @returns {Side}\n */\n side() {\n const ret = wasm.cursor_side(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Decode the cursor from a Uint8Array.\n * @param {Uint8Array} data\n * @returns {Cursor}\n */\n static decode(data) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.cursor_decode(retptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return Cursor.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Encode the cursor into a Uint8Array.\n * @returns {Uint8Array}\n */\n encode() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.cursor_encode(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst EphemeralStoreWasmFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_ephemeralstorewasm_free(ptr >>> 0, 1));\n\nexport class EphemeralStoreWasm {\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n EphemeralStoreWasmFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_ephemeralstorewasm_free(ptr, 0);\n }\n /**\n * @returns {any}\n */\n getAllStates() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.ephemeralstorewasm_getAllStates(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n removeOutdated() {\n wasm.ephemeralstorewasm_removeOutdated(this.__wbg_ptr);\n }\n /**\n * @param {Function} f\n * @returns {any}\n */\n subscribeLocalUpdates(f) {\n const ret = wasm.ephemeralstorewasm_subscribeLocalUpdates(this.__wbg_ptr, addHeapObject(f));\n return takeObject(ret);\n }\n /**\n * @param {string} key\n * @returns {any}\n */\n get(key) {\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.ephemeralstorewasm_get(this.__wbg_ptr, ptr0, len0);\n return takeObject(ret);\n }\n /**\n * Creates a new `EphemeralStore` instance.\n *\n * The `timeout` parameter specifies the duration in milliseconds.\n * A state of a peer is considered outdated, if the last update of the state of the peer\n * is older than the `timeout`.\n * @param {number} timeout\n */\n constructor(timeout) {\n const ret = wasm.ephemeralstorewasm_new(timeout);\n this.__wbg_ptr = ret >>> 0;\n EphemeralStoreWasmFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * @param {string} key\n * @param {any} value\n */\n set(key, value) {\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.ephemeralstorewasm_set(this.__wbg_ptr, ptr0, len0, addHeapObject(value));\n }\n /**\n * @returns {string[]}\n */\n keys() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.ephemeralstorewasm_keys(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @param {Uint8Array} data\n */\n apply(data) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.ephemeralstorewasm_apply(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @param {string} key\n */\n delete(key) {\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.ephemeralstorewasm_delete(this.__wbg_ptr, ptr0, len0);\n }\n /**\n * @param {string} key\n * @returns {Uint8Array}\n */\n encode(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.ephemeralstorewasm_encode(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v2 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v2;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * If the state is empty.\n * @returns {boolean}\n */\n isEmpty() {\n const ret = wasm.ephemeralstorewasm_isEmpty(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * @returns {Uint8Array}\n */\n encodeAll() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.ephemeralstorewasm_encodeAll(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n const ret = wasm.ephemeralstorewasm_subscribe(this.__wbg_ptr, addHeapObject(f));\n return takeObject(ret);\n }\n}\n\nconst LoroCounterFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_lorocounter_free(ptr >>> 0, 1));\n/**\n * The handler of a counter container.\n */\nexport class LoroCounter {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroCounter.prototype);\n obj.__wbg_ptr = ptr;\n LoroCounterFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroCounterFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_lorocounter_free(ptr, 0);\n }\n /**\n * Convert this attached container and all descendants to an independent tree.\n * Text format applies recursively. Does not commit; throws for detached\n * containers, unsupported types, invalid options, or nesting above 256.\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerNode}\n */\n toContainerTree(opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_toContainerTree(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Whether the container is attached to a docuemnt.\n *\n * If it's detached, the operations on the container will not be persisted.\n * @returns {boolean}\n */\n isAttached() {\n const ret = wasm.lorocounter_isAttached(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the attached container associated with this.\n *\n * Returns an attached `Container` that equals to this or created by this, otherwise `undefined`.\n * @returns {LoroTree | undefined}\n */\n getAttached() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_getAttached(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the value of the counter.\n * @returns {number}\n */\n getShallowValue() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_getShallowValue(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getFloat64(retptr + 8 * 0, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n return r0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * The container id of this handler.\n * @returns {ContainerID}\n */\n get id() {\n const ret = wasm.lorocounter_id(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Create a new LoroCounter.\n */\n constructor() {\n const ret = wasm.lorocounter_new();\n this.__wbg_ptr = ret >>> 0;\n LoroCounterFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * \"Counter\"\n * @returns {'Counter'}\n */\n kind() {\n const ret = wasm.lorocounter_kind(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the parent container of the counter container.\n *\n * - The parent container of the root counter is `undefined`.\n * - The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n * @returns {Container | undefined}\n */\n parent() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_parent(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @returns {number}\n */\n toJSON() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_getShallowValue(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getFloat64(retptr + 8 * 0, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n return r0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Decrement the counter by the given value.\n * @param {number} value\n */\n decrement(value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_decrement(retptr, this.__wbg_ptr, value);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the value of the counter.\n * @returns {number}\n */\n get value() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_getShallowValue(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getFloat64(retptr + 8 * 0, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n return r0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Increment the counter by the given value.\n * @param {number} value\n */\n increment(value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_increment(retptr, this.__wbg_ptr, value);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Subscribe to the changes of the counter.\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_subscribe(retptr, this.__wbg_ptr, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst LoroDocFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_lorodoc_free(ptr >>> 0, 1));\n/**\n * The CRDTs document. Loro supports different CRDTs include [**List**](LoroList),\n * [**RichText**](LoroText), [**Map**](LoroMap) and [**Movable Tree**](LoroTree),\n * you could build all kind of applications by these.\n *\n * **Important:** Loro is a pure library and does not handle network protocols.\n * It is the responsibility of the user to manage the storage, loading, and synchronization\n * of the bytes exported by Loro in a manner suitable for their specific environment.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\"\n *\n * const loro = new LoroDoc();\n * const text = loro.getText(\"text\");\n * const list = loro.getList(\"list\");\n * const map = loro.getMap(\"Map\");\n * const tree = loro.getTree(\"tree\");\n * ```\n */\nexport class LoroDoc {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroDoc.prototype);\n obj.__wbg_ptr = ptr;\n LoroDocFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroDocFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_lorodoc_free(ptr, 0);\n }\n /**\n * Apply a batch of diff to the document\n *\n * A diff batch represents a set of changes between two versions of the document.\n * You can calculate a diff batch using `doc.diff()`.\n *\n * Changes are associated with container IDs. During diff application, if new containers were created in the source\n * document, they will be assigned fresh IDs in the target document. Loro automatically handles remapping these\n * container IDs from their original IDs to the new IDs as the diff is applied.\n *\n * @example\n * ```ts\n * const doc1 = new LoroDoc();\n * const doc2 = new LoroDoc();\n *\n * // Make some changes to doc1\n * const text = doc1.getText(\"text\");\n * text.insert(0, \"Hello\");\n *\n * // Calculate diff between empty and current state\n * const diff = doc1.diff([], doc1.frontiers());\n *\n * // Apply changes to doc2\n * doc2.applyDiff(diff);\n * console.log(doc2.getText(\"text\").toString()); // \"Hello\"\n * ```\n *\n * Pass `{ fullState: true }` when applying the result of `doc.diff()` to a document that may\n * keep hidden state for a mergeable child the diff makes visible again (e.g. applying\n * `doc.diff(afterDelete, beforeDelete)` to `doc` itself or to a copy of it). The child's\n * entry is then read as its full content and aligned with that hidden state. Without it\n * (the default), entries are applied as increments, which is right for events forwarded to\n * a document that shares the source's hidden state. Never pass it for events from local\n * commits; see `ApplyDiffOptions.fullState`.\n *\n * ```ts\n * const text = doc.getMap(\"m\").ensureMergeableText(\"t\");\n * text.insert(0, \"hello\");\n * const before = doc.frontiers();\n * doc.getMap(\"m\").delete(\"t\");\n * doc.applyDiff(doc.diff(doc.frontiers(), before), { fullState: true });\n * console.log(doc.getMap(\"m\").get(\"t\").toString()); // \"hello\"\n * ```\n * @param {[ContainerID, Diff|JsonDiff][]} diff\n * @param {ApplyDiffOptions | null} [options]\n */\n applyDiff(diff, options) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_applyDiff(retptr, this.__wbg_ptr, addHeapObject(diff), isLikeNone(options) ? 0 : addHeapObject(options));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Check if the doc contains the full history.\n * @returns {boolean}\n */\n isShallow() {\n const ret = wasm.lorodoc_isShallow(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the number of changes in the oplog.\n * @returns {number}\n */\n changeCount() {\n const ret = wasm.lorodoc_changeCount(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * Get the value or container at the given path\n *\n * The path can be specified in different ways depending on the container type:\n *\n * For Tree:\n * 1. Using node IDs: `tree/{node_id}/property`\n * 2. Using indices: `tree/0/1/property`\n *\n * For List and MovableList:\n * - Using indices: `list/0` or `list/1/property`\n *\n * For Map:\n * - Using keys: `map/key` or `map/nested/property`\n *\n * For tree structures, index-based paths follow depth-first traversal order.\n * The indices start from 0 and represent the position of a node among its siblings.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"key\", 1);\n * console.log(doc.getByPath(\"map/key\")); // 1\n * console.log(doc.getByPath(\"map\")); // LoroMap\n * ```\n * @param {string} path\n * @returns {Value | Container | undefined}\n */\n getByPath(path) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(path, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_getByPath(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get a LoroCounter by container id\n *\n * If the container does not exist, an error will be thrown.\n * @param {ContainerID | string} cid\n * @returns {LoroCounter}\n */\n getCounter(cid) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getCounter(retptr, this.__wbg_ptr, addBorrowedObject(cid));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroCounter.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * `detached` indicates that the `DocState` is not synchronized with the latest version of `OpLog`.\n *\n * > The document becomes detached during a `checkout` operation.\n * > Being `detached` implies that the `DocState` is not synchronized with the latest version of the `OpLog`.\n * > In a detached state, the document is not editable by default, and any `import` operations will be\n * > recorded in the `OpLog` without being applied to the `DocState`.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * const frontiers = doc.frontiers();\n * text.insert(0, \"Hello World!\");\n * console.log(doc.isDetached()); // false\n * doc.checkout(frontiers);\n * console.log(doc.isDetached()); // true\n * doc.attach();\n * console.log(doc.isDetached()); // false\n * ```\n * @returns {boolean}\n */\n isDetached() {\n const ret = wasm.lorodoc_isDetached(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get peer id in decimal string.\n * @returns {PeerID}\n */\n get peerIdStr() {\n const ret = wasm.lorodoc_peerIdStr(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Set the peer ID of the current writer.\n *\n * It must be a number, a BigInt, or a decimal string that can be parsed to a unsigned 64-bit integer.\n *\n * Note: use it with caution. You need to make sure there is not chance that two peers\n * have the same peer ID. Otherwise, we cannot ensure the consistency of the document.\n * @param {number | bigint | `${number}`} peer_id\n */\n setPeerId(peer_id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_setPeerId(retptr, this.__wbg_ptr, addHeapObject(peer_id));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the absolute position of the given Cursor\n *\n * @example\n * ```ts\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"123\");\n * const pos0 = text.getCursor(0, 0);\n * {\n * const ans = doc.getCursorPos(pos0!);\n * expect(ans.offset).toBe(0);\n * }\n * text.insert(0, \"1\");\n * {\n * const ans = doc.getCursorPos(pos0!);\n * expect(ans.offset).toBe(1);\n * }\n * ```\n * @param {Cursor} cursor\n * @returns {{ update?: Cursor, offset: number, side: Side } | undefined}\n */\n getCursorPos(cursor) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n _assertClass(cursor, Cursor);\n wasm.lorodoc_getCursorPos(retptr, this.__wbg_ptr, cursor.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Check if the doc contains the target container.\n *\n * A root container always exists, while a normal container exists\n * if it has ever been created on the doc.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroMap, LoroText, LoroList } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * doc.setPeerId(\"1\");\n * const text = doc.getMap(\"map\").setContainer(\"text\", new LoroText());\n * const list = doc.getMap(\"map\").setContainer(\"list\", new LoroList());\n * expect(doc.isContainerExists(\"cid:root-map:Map\")).toBe(true);\n * expect(doc.isContainerExists(\"cid:0@1:Text\")).toBe(true);\n * expect(doc.isContainerExists(\"cid:1@1:List\")).toBe(true);\n *\n * const doc2 = new LoroDoc();\n * // Containers exist, as long as the history or the doc state include it\n * doc.detach();\n * doc2.import(doc.export({ mode: \"update\" }));\n * expect(doc2.isContainerExists(\"cid:root-map:Map\")).toBe(true);\n * expect(doc2.isContainerExists(\"cid:0@1:Text\")).toBe(true);\n * expect(doc2.isContainerExists(\"cid:1@1:List\")).toBe(true);\n * ```\n * @param {ContainerID} container_id\n * @returns {boolean}\n */\n hasContainer(container_id) {\n const ret = wasm.lorodoc_hasContainer(this.__wbg_ptr, addHeapObject(container_id));\n return ret !== 0;\n }\n /**\n * Import a batch of updates or snapshots.\n *\n * It's more efficient than importing updates one by one.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * const updates = doc.export({ mode: \"update\" });\n * const snapshot = doc.export({ mode: \"snapshot\" });\n * const doc2 = new LoroDoc();\n * doc2.importBatch([snapshot, updates]);\n * ```\n * @param {Uint8Array[]} data\n * @returns {ImportStatus}\n */\n importBatch(data) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_importBatch(retptr, this.__wbg_ptr, addHeapObject(data));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Compare the ordering of two Frontiers.\n *\n * It's assumed that both Frontiers are included by the doc. Otherwise, an error will be thrown.\n *\n * Return value:\n *\n * - -1: a < b\n * - 0: a == b\n * - 1: a > b\n * - undefined: a ∥ b: a and b are concurrent\n * @param {({ peer: PeerID, counter: number })[]} a\n * @param {({ peer: PeerID, counter: number })[]} b\n * @returns {-1 | 1 | 0 | undefined}\n */\n cmpFrontiers(a, b) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(a, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArrayJsValueToWasm0(b, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n wasm.lorodoc_cmpFrontiers(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Debug the size of the history\n */\n debugHistory() {\n wasm.lorodoc_debugHistory(this.__wbg_ptr);\n }\n /**\n * Create a loro document from the snapshot.\n *\n * @see You can learn more [here](https://loro.dev/docs/tutorial/encoding).\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\"\n *\n * const doc = new LoroDoc();\n * // ...\n * const bytes = doc.export({ mode: \"snapshot\" });\n * const loro = LoroDoc.fromSnapshot(bytes);\n * ```\n * @param {Uint8Array} snapshot\n * @returns {LoroDoc}\n */\n static fromSnapshot(snapshot) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(snapshot, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_fromSnapshot(retptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroDoc.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the change that contains the specific ID\n * @param {{ peer: PeerID, counter: number }} id\n * @returns {Change}\n */\n getChangeAt(id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getChangeAt(retptr, this.__wbg_ptr, addHeapObject(id));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the version vector of the latest known version in OpLog.\n *\n * If you checkout to a specific version, this version vector will not change.\n * @returns {VersionVector}\n */\n oplogVersion() {\n const ret = wasm.lorodoc_oplogVersion(this.__wbg_ptr);\n return VersionVector.__wrap(ret);\n }\n /**\n * Get a LoroMovableList by container id\n *\n * The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n *\n * If the container does not exist, an error will be thrown.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getMovableList(\"list\");\n * ```\n * @param {ContainerID | string} cid\n * @returns {LoroMovableList}\n */\n getMovableList(cid) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getMovableList(retptr, this.__wbg_ptr, addBorrowedObject(cid));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroMovableList.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Convert frontiers to a version vector\n *\n * Learn more about frontiers and version vector [here](https://loro.dev/docs/advanced/version_deep_dive)\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * const frontiers = doc.frontiers();\n * const version = doc.frontiersToVV(frontiers);\n * ```\n * @param {({ peer: PeerID, counter: number })[]} frontiers\n * @returns {VersionVector}\n */\n frontiersToVV(frontiers) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(frontiers, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_frontiersToVV(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return VersionVector.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get all of changes in the oplog.\n *\n * Note: this method is expensive when the oplog is large. O(n)\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * const changes = doc.getAllChanges();\n *\n * for (let [peer, c] of changes.entries()){\n * console.log(\"peer: \", peer);\n * for (let change of c){\n * console.log(\"change: \", change);\n * }\n * }\n * ```\n * @returns {Map}\n */\n getAllChanges() {\n const ret = wasm.lorodoc_getAllChanges(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the [frontiers](https://loro.dev/docs/advanced/version_deep_dive) of the latest version in OpLog.\n *\n * If you checkout to a specific version, this value will not change.\n * @returns {{ peer: PeerID, counter: number }[]}\n */\n oplogFrontiers() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_oplogFrontiers(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert a version vector to frontiers\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * const version = doc.version();\n * const frontiers = doc.vvToFrontiers(version);\n * ```\n * @param {VersionVector} vv\n * @returns {{ peer: PeerID, counter: number }[]}\n */\n vvToFrontiers(vv) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n _assertClass(vv, VersionVector);\n wasm.lorodoc_vvToFrontiers(retptr, this.__wbg_ptr, vv.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * The doc only contains the history since this version\n *\n * This is empty if the doc is not shallow.\n *\n * The ops included by the shallow history start version vector are not in the doc.\n * @returns {VersionVector}\n */\n shallowSinceVV() {\n const ret = wasm.lorodoc_shallowSinceVV(this.__wbg_ptr);\n return VersionVector.__wrap(ret);\n }\n /**\n * Set the rich text format configuration of the document.\n *\n * You need to config it if you use rich text `mark` method.\n * Specifically, you need to config the `expand` property of each style.\n *\n * Expand is used to specify the behavior of expanding when new text is inserted at the\n * beginning or end of the style.\n *\n * You can specify the `expand` option to set the behavior when inserting text at the boundary of the range.\n *\n * - `after`(default): when inserting text right after the given range, the mark will be expanded to include the inserted text\n * - `before`: when inserting text right before the given range, the mark will be expanded to include the inserted text\n * - `none`: the mark will not be expanded to include the inserted text at the boundaries\n * - `both`: when inserting text either right before or right after the given range, the mark will be expanded to include the inserted text\n *\n * @example\n * ```ts\n * const doc = new LoroDoc();\n * doc.configTextStyle({\n * bold: { expand: \"after\" },\n * link: { expand: \"before\" }\n * });\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello World!\");\n * text.mark({ start: 0, end: 5 }, \"bold\", true);\n * expect(text.toDelta()).toStrictEqual([\n * {\n * insert: \"Hello\",\n * attributes: {\n * bold: true,\n * },\n * },\n * {\n * insert: \" World!\",\n * },\n * ] as Delta[]);\n * ```\n * @param {{[key: string]: { expand: 'before'|'after'|'none'|'both' }}} styles\n */\n configTextStyle(styles) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_configTextStyle(retptr, this.__wbg_ptr, addHeapObject(styles));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get all ops of the change that contains the specific ID\n * @param {{ peer: PeerID, counter: number }} id\n * @returns {any[]}\n */\n getOpsInChange(id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getOpsInChange(retptr, this.__wbg_ptr, addHeapObject(id));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the shallow json format of the document state.\n *\n * Unlike `toJSON()` which recursively resolves all containers to their values,\n * `getShallowValue()` returns container IDs as strings for any nested containers.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * const tree = doc.getTree(\"tree\");\n * const map = doc.getMap(\"map\");\n * const shallowValue = doc.getShallowValue();\n * console.log(shallowValue);\n * // {\n * // list: 'cid:root-list:List',\n * // tree: 'cid:root-tree:Tree',\n * // map: 'cid:root-map:Map'\n * // }\n *\n * // It points to the same container as `list`\n * const listB = doc.getContainerById(shallowValue.list);\n * ```\n * @returns {Record}\n */\n getShallowValue() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getShallowValue(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Checkout the `DocState` to the latest version of `OpLog`.\n *\n * > The document becomes detached during a `checkout` operation.\n * > Being `detached` implies that the `DocState` is not synchronized with the latest version of the `OpLog`.\n * > In a detached state, the document is not editable by default, and any `import` operations will be\n * > recorded in the `OpLog` without being applied to the `DocState`.\n *\n * This has the same effect as `attach`.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * const frontiers = doc.frontiers();\n * text.insert(0, \"Hello World!\");\n * doc.checkout(frontiers);\n * // you need call `checkoutToLatest()` or `attach()` before changing the doc.\n * doc.checkoutToLatest();\n * text.insert(0, \"Hi\");\n * ```\n */\n checkoutToLatest() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_checkoutToLatest(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Compare the version of the OpLog with the specified frontiers.\n *\n * This method is useful to compare the version by only a small amount of data.\n *\n * This method returns an integer indicating the relationship between the version of the OpLog (referred to as 'self')\n * and the provided 'frontiers' parameter:\n *\n * - -1: The version of 'self' is either less than 'frontiers' or is non-comparable (parallel) to 'frontiers',\n * indicating that it is not definitively less than 'frontiers'.\n * - 0: The version of 'self' is equal to 'frontiers'.\n * - 1: The version of 'self' is greater than 'frontiers'.\n *\n * # Internal\n *\n * Frontiers cannot be compared without the history of the OpLog.\n * @param {({ peer: PeerID, counter: number })[]} frontiers\n * @returns {number}\n */\n cmpWithFrontiers(frontiers) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(frontiers, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_cmpWithFrontiers(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @param {{ peer: PeerID, counter: number, length: number }} idSpan\n * @returns {any}\n */\n exportJsonInIdSpan(idSpan) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_exportJsonInIdSpan(retptr, this.__wbg_ptr, addHeapObject(idSpan));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Subscribe to changes that may affect a JSONPath query.\n *\n * The callback receives no query result; it is a lightweight notifier and may\n * fire false positives so callers can debounce/throttle before running JSONPath\n * themselves.\n * @param {string} jsonpath\n * @param {Function} f\n * @returns {any}\n */\n subscribeJsonpath(jsonpath, f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(jsonpath, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_subscribeJsonpath(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Delete all content from a root container and hide it from the document.\n *\n * When a root container is empty and hidden:\n * - It won't show up in `get_deep_value()` results\n * - It won't be included in document snapshots\n *\n * Only works on root containers (containers without parents).\n * @param {ContainerID} cid\n */\n deleteRootContainer(cid) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_deleteRootContainer(retptr, this.__wbg_ptr, addHeapObject(cid));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Export updates in the given range in JSON format.\n * @param {any} start_vv\n * @param {any} end_vv\n * @param {boolean | null} [with_peer_compression]\n * @returns {JsonSchema}\n */\n exportJsonUpdates(start_vv, end_vv, with_peer_compression) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_exportJsonUpdates(retptr, this.__wbg_ptr, addHeapObject(start_vv), addHeapObject(end_vv), isLikeNone(with_peer_compression) ? 0xFFFFFF : with_peer_compression ? 1 : 0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the container corresponding to the container id.\n *\n * If the container does not exist, it returns `undefined`.\n *\n * A mergeable container (created via `ensureMergeableMap` and friends) is resolvable\n * right after it has been ensured — even before any op is written into it — for as\n * long as the parent map's child ref is alive. A mergeable container id that was\n * never ensured on this doc resolves to `undefined`.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * let text = doc.getText(\"text\");\n * const textId = text.id;\n * text = doc.getContainerById(textId);\n * ```\n * @param {ContainerID} container_id\n * @returns {any}\n */\n getContainerById(container_id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getContainerById(retptr, this.__wbg_ptr, addHeapObject(container_id));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the number of operations in the pending transaction.\n *\n * The pending transaction is the one that is not committed yet. It will be committed\n * automatically after calling `doc.commit()`, `doc.export(mode)` or `doc.checkout(version)`.\n * @returns {number}\n */\n getPendingTxnLength() {\n const ret = wasm.lorodoc_getPendingTxnLength(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * Import updates from the JSON format.\n *\n * only supports backward compatibility but not forward compatibility.\n * @param {string | JsonSchema} json\n * @returns {ImportStatus}\n */\n importJsonUpdates(json) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_importJsonUpdates(retptr, this.__wbg_ptr, addHeapObject(json));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Import a batch of updates and snapshots.\n *\n * It's more efficient than importing updates one by one.\n *\n * @deprecated Use `importBatch` instead.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * const updates = doc.export({ mode: \"update\" });\n * const snapshot = doc.export({ mode: \"snapshot\" });\n * const doc2 = new LoroDoc();\n * doc2.importBatch([snapshot, updates]);\n * ```\n * @param {Uint8Array[]} data\n * @returns {ImportStatus}\n */\n importUpdateBatch(data) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_importBatch(retptr, this.__wbg_ptr, addHeapObject(data));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Enables editing in detached mode, which is disabled by default.\n *\n * The doc enter detached mode after calling `detach` or checking out a non-latest version.\n *\n * # Important Notes:\n *\n * - This mode uses a different PeerID for each checkout.\n * - Ensure no concurrent operations share the same PeerID if set manually.\n * - Importing does not affect the document's state or version; changes are\n * recorded in the [OpLog] only. Call `checkout` to apply changes.\n * @param {boolean} enable\n */\n setDetachedEditing(enable) {\n wasm.lorodoc_setDetachedEditing(this.__wbg_ptr, enable);\n }\n /**\n * Set whether to record the timestamp of each change. Default is `false`.\n *\n * If enabled, the Unix timestamp (in seconds) will be recorded for each change automatically.\n *\n * You can also set each timestamp manually when you commit a change.\n * The timestamp manually set will override the automatic one.\n *\n * NOTE: Timestamps are forced to be in ascending order in the OpLog's history.\n * If you commit a new change with a timestamp that is less than the existing one,\n * the largest existing timestamp will be used instead.\n * @param {boolean} auto_record\n */\n setRecordTimestamp(auto_record) {\n wasm.lorodoc_setRecordTimestamp(this.__wbg_ptr, auto_record);\n }\n /**\n * Subscribe to the pre-commit event.\n *\n * The callback will be called when the changes are committed but not yet applied to the OpLog.\n * You can modify the commit message and timestamp in the callback by `ChangeModifier`.\n * @param {Function} f\n * @returns {any}\n */\n subscribePreCommit(f) {\n const ret = wasm.lorodoc_subscribePreCommit(this.__wbg_ptr, addHeapObject(f));\n return takeObject(ret);\n }\n /**\n * Find the op id spans that between the `from` version and the `to` version.\n *\n * You can combine it with `exportJsonInIdSpan` to get the changes between two versions.\n *\n * You can use it to travel all the changes from `from` to `to`. `from` and `to` are frontiers,\n * and they can be concurrent to each other. You can use it to find all the changes related to an event:\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const docA = new LoroDoc();\n * docA.setPeerId(\"1\");\n * const docB = new LoroDoc();\n *\n * docA.getText(\"text\").update(\"Hello\");\n * docA.commit();\n * const snapshot = docA.export({ mode: \"snapshot\" });\n * let done = false;\n * docB.subscribe(e => {\n * const spans = docB.findIdSpansBetween(e.from, e.to);\n * const changes = docB.exportJsonInIdSpan(spans.forward[0]);\n * console.log(changes);\n * // [{\n * // id: \"0@1\",\n * // timestamp: expect.any(Number),\n * // deps: [],\n * // lamport: 0,\n * // msg: undefined,\n * // ops: [{\n * // container: \"cid:root-text:Text\",\n * // counter: 0,\n * // content: {\n * // type: \"insert\",\n * // pos: 0,\n * // text: \"Hello\"\n * // }\n * // }]\n * // }]\n * });\n * docB.import(snapshot);\n * ```\n * @param {({ peer: PeerID, counter: number })[]} from\n * @param {({ peer: PeerID, counter: number })[]} to\n * @returns {VersionVectorDiff}\n */\n findIdSpansBetween(from, to) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(from, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArrayJsValueToWasm0(to, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n wasm.lorodoc_findIdSpansBetween(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the change of with specific peer_id and lamport <= given lamport\n * @param {string} peer_id\n * @param {number} lamport\n * @returns {Change | undefined}\n */\n getChangeAtLamport(peer_id, lamport) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(peer_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_getChangeAtLamport(retptr, this.__wbg_ptr, ptr0, len0, lamport);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the path from the root to the container\n * @param {ContainerID} id\n * @returns {(string|number)[] | undefined}\n */\n getPathToContainer(id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getPathToContainer(retptr, this.__wbg_ptr, addHeapObject(id));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Export remote updates received through import APIs that are still waiting\n * for missing causal dependencies. These differ from uncommitted local operations.\n *\n * Returns `undefined` when no remote updates are pending. Ordinary snapshot\n * and update exports exclude these pending updates, so persist this result\n * as a separate sidecar to a normal snapshot. Export errors are thrown;\n * they are not returned as `undefined`.\n *\n * Restore the snapshot first, then pass the sidecar bytes to ordinary\n * `import()`. The restored updates remain pending until later imports supply\n * their real missing dependencies. This method only exports operations already\n * received; it cannot supply missing predecessors.\n *\n * This method is read-only: it does not consume pending updates, advance the\n * applied version vector/frontiers, emit document events, or commit a local\n * transaction. Uncommitted local operations are excluded. Ordinary snapshot\n * export still commits local operations as usual.\n *\n * Coordinate document mutations while collecting the snapshot and sidecar,\n * and persist them as one consistent checkpoint. The two export calls do not\n * form an atomic capture. Replace the saved checkpoint only after both exports\n * succeed. As part of that successful replacement, `undefined` means remove\n * any old pending sidecar. If either export throws, keep the previous checkpoint.\n *\n * This method does not define or advance a sync cursor or establish that the\n * document is synced. `undefined` only means no received remote updates are\n * currently pending.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const source = new LoroDoc();\n * source.setPeerId(\"1\");\n * source.getText(\"text\").insert(0, \"base|\");\n * const baseSnapshot = source.export({ mode: \"snapshot\" });\n * const beforeA = source.oplogVersion();\n * source.getText(\"text\").insert(5, \"A\");\n * const a = source.export({ mode: \"update\", from: beforeA });\n * const beforeB = source.oplogVersion();\n * source.getText(\"text\").insert(6, \"B\");\n * const b = source.export({ mode: \"update\", from: beforeB });\n *\n * const doc = new LoroDoc();\n * doc.import(baseSnapshot);\n * doc.import(b); // A is missing, so B stays pending.\n * // Coordinate checkpoint collection and storage with document mutations.\n * let savedCheckpoint = {\n * snapshot: doc.export({ mode: \"snapshot\" }),\n * pending: doc.exportPendingUpdates(),\n * };\n *\n * const restored = new LoroDoc();\n * restored.import(savedCheckpoint.snapshot);\n * if (savedCheckpoint.pending !== undefined) restored.import(savedCheckpoint.pending);\n * console.assert(restored.getText(\"text\").toString() === \"base|\");\n * restored.import(a);\n * console.assert(restored.getText(\"text\").toString() === \"base|AB\");\n *\n * savedCheckpoint = {\n * snapshot: restored.export({ mode: \"snapshot\" }),\n * pending: restored.exportPendingUpdates(),\n * };\n * console.assert(savedCheckpoint.pending === undefined);\n * // After both exports succeed, replace the checkpoint and remove its old pending sidecar.\n * ```\n * @returns {Uint8Array | undefined}\n */\n exportPendingUpdates() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_exportPendingUpdates(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n let v1;\n if (r0 !== 0) {\n v1 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n }\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Gets container IDs modified in the given ID range.\n *\n * **NOTE:** This method will implicitly commit.\n *\n * This method identifies which containers were affected by changes in a given range of operations.\n * It can be used together with `doc.travelChangeAncestors()` to analyze the history of changes\n * and determine which containers were modified by each change.\n *\n * @param id - The starting ID of the change range\n * @param len - The length of the change range to check\n * @returns An array of container IDs that were modified in the given range\n * @param {{ peer: PeerID, counter: number }} id\n * @param {number} len\n * @returns {ContainerID[]}\n */\n getChangedContainersIn(id, len) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getChangedContainersIn(retptr, this.__wbg_ptr, addHeapObject(id), len);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get deep value of the document with container id\n * @returns {any}\n */\n getDeepValueWithID() {\n const ret = wasm.lorodoc_getDeepValueWithID(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Set the origin of the next commit\n * @param {string} origin\n */\n setNextCommitOrigin(origin) {\n const ptr0 = passStringToWasm0(origin, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_setNextCommitOrigin(this.__wbg_ptr, ptr0, len0);\n }\n /**\n * Get the pending operations from the current transaction in JSON format\n *\n * This method returns a JSON representation of operations that have been applied\n * but not yet committed in the current transaction.\n *\n * It will use the same data format as `doc.exportJsonUpdates()`\n *\n * @example\n * ```ts\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * // Get pending ops before commit\n * const pendingOps = doc.getPendingOpsFromCurrentTxnAsJson();\n * doc.commit();\n * const emptyOps = doc.getPendingOpsFromCurrentTxnAsJson(); // this is undefined\n * ```\n * @returns {JsonSchema | undefined}\n */\n getUncommittedOpsAsJson() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getUncommittedOpsAsJson(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Set the commit message of the next commit\n * @param {string} msg\n */\n setNextCommitMessage(msg) {\n const ptr0 = passStringToWasm0(msg, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_setNextCommitMessage(this.__wbg_ptr, ptr0, len0);\n }\n /**\n * Set the options of the next commit\n * @param {{ origin?: string, timestamp?: number, message?: string }} options\n */\n setNextCommitOptions(options) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_setNextCommitOptions(retptr, this.__wbg_ptr, addHeapObject(options));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * The doc only contains the history since this version\n *\n * This is empty if the doc is not shallow.\n *\n * The ops included by the shallow history start frontiers are not in the doc.\n * @returns {{ peer: PeerID, counter: number }[]}\n */\n shallowSinceFrontiers() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_shallowSinceFrontiers(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Subscribe the updates from local edits\n * @param {Function} f\n * @returns {any}\n */\n subscribeLocalUpdates(f) {\n const ret = wasm.lorodoc_subscribeLocalUpdates(this.__wbg_ptr, addHeapObject(f));\n return takeObject(ret);\n }\n /**\n * Visit all the ancestors of the changes in causal order.\n *\n * @param ids - the changes to visit\n * @param f - the callback function, return `true` to continue visiting, return `false` to stop\n * @param {({ peer: PeerID, counter: number })[]} ids\n * @param {(change: Change) => boolean} f\n */\n travelChangeAncestors(ids, f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(ids, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_travelChangeAncestors(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Clear the options of the next commit\n */\n clearNextCommitOptions() {\n wasm.lorodoc_clearNextCommitOptions(this.__wbg_ptr);\n }\n /**\n * Configures the default text style for the document.\n *\n * This method sets the default text style configuration for the document when using LoroText.\n * If `None` is provided, the default style is reset.\n * @param {{ expand: 'before'|'after'|'none'|'both' } | undefined} style\n */\n configDefaultTextStyle(style) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_configDefaultTextStyle(retptr, this.__wbg_ptr, addHeapObject(style));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Maximum number of lazily loaded container values retained by handler reads.\n * The default is 2048.\n * @returns {number}\n */\n getDecodedValueCacheLimit() {\n const ret = wasm.lorodoc_getDecodedValueCacheLimit(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * If two continuous local changes are within (<=) the interval(**in seconds**), they will be merged into one change.\n *\n * The default value is 1_000 seconds.\n *\n * By default, we record timestamps in seconds for each change. So if the merge interval is 1, and changes A and B\n * have timestamps of 3 and 4 respectively, then they will be merged into one change\n * @param {number} interval\n */\n setChangeMergeInterval(interval) {\n wasm.lorodoc_setChangeMergeInterval(this.__wbg_ptr, interval);\n }\n /**\n * Set the timestamp of the next commit\n * @param {number} timestamp\n */\n setNextCommitTimestamp(timestamp) {\n wasm.lorodoc_setNextCommitTimestamp(this.__wbg_ptr, timestamp);\n }\n /**\n * Set whether to hide empty root containers.\n *\n * @example\n * ```ts\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * console.log(doc.toJSON()); // { map: {} }\n * doc.setHideEmptyRootContainers(true);\n * console.log(doc.toJSON()); // {}\n * ```\n * @param {boolean} hide\n */\n setHideEmptyRootContainers(hide) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_setHideEmptyRootContainers(retptr, this.__wbg_ptr, hide);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Whether the editing is enabled in detached mode.\n *\n * The doc enter detached mode after calling `detach` or checking out a non-latest version.\n *\n * # Important Notes:\n *\n * - This mode uses a different PeerID for each checkout.\n * - Ensure no concurrent operations share the same PeerID if set manually.\n * - Importing does not affect the document's state or version; changes are\n * recorded in the [OpLog] only. Call `checkout` to apply changes.\n * @returns {boolean}\n */\n isDetachedEditingEnabled() {\n const ret = wasm.lorodoc_isDetachedEditingEnabled(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Set how many lazily loaded container values handler reads may cache.\n *\n * The default is 2048. A larger finite limit trades memory for faster repeated\n * reads of large imported snapshots. Zero disables this cache. Lowering the\n * limit immediately evicts excess cached values without losing local edits.\n *\n * This counts cached values, not bytes or all document state: modified\n * containers and materialized tree state are outside this bound. Bulk reads\n * such as `doc.toJSON()` do not populate this cache.\n *\n * The setting is local to this document, is copied independently by forks,\n * and is not encoded in snapshots or updates. `limit` must be a finite\n * integer between 0 and 4294967295 (inclusive); Infinity is not supported.\n * @param {number} limit\n */\n setDecodedValueCacheLimit(limit) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_setDecodedValueCacheLimit(retptr, this.__wbg_ptr, limit);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @param {Function} f\n * @returns {any}\n */\n subscribeFirstCommitFromPeer(f) {\n const ret = wasm.lorodoc_subscribeFirstCommitFromPeer(this.__wbg_ptr, addHeapObject(f));\n return takeObject(ret);\n }\n /**\n * Create a new loro document.\n *\n * New document will have a random peer id.\n */\n constructor() {\n const ret = wasm.lorodoc_new();\n this.__wbg_ptr = ret >>> 0;\n LoroDocFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * Calculate the differences between two frontiers\n *\n * The entries in the returned object are sorted by causal order: the creation of a child container will be\n * presented before its use.\n * @param {({ peer: PeerID, counter: number })[]} from\n * @param {({ peer: PeerID, counter: number })[]} to\n * @param {boolean | null} [for_json]\n * @returns {[ContainerID, Diff|JsonDiff][]}\n */\n diff(from, to, for_json) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(from, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArrayJsValueToWasm0(to, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n wasm.lorodoc_diff(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1, isLikeNone(for_json) ? 0xFFFFFF : for_json ? 1 : 0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Duplicate the document with a different PeerID\n *\n * The time complexity and space complexity of this operation are both O(n),\n *\n * When called in detached mode, it will fork at the current state frontiers.\n * It will have the same effect as `forkAt(&self.frontiers())`.\n * @returns {LoroDoc}\n */\n fork() {\n const ret = wasm.lorodoc_fork(this.__wbg_ptr);\n return LoroDoc.__wrap(ret);\n }\n /**\n * Attach the document state to the latest known version.\n *\n * > The document becomes detached during a `checkout` operation.\n * > Being `detached` implies that the `DocState` is not synchronized with the latest version of the `OpLog`.\n * > In a detached state, the document is not editable, and any `import` operations will be\n * > recorded in the `OpLog` without being applied to the `DocState`.\n *\n * This method has the same effect as invoking `checkoutToLatest`.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * const frontiers = doc.frontiers();\n * text.insert(0, \"Hello World!\");\n * doc.checkout(frontiers);\n * // you need call `attach()` or `checkoutToLatest()` before changing the doc.\n * doc.attach();\n * text.insert(0, \"Hi\");\n * ```\n */\n attach() {\n wasm.lorodoc_attach(this.__wbg_ptr);\n }\n /**\n * Commit the cumulative auto-committed transaction.\n *\n * You can specify the `origin`, `timestamp`, and `message` of the commit.\n *\n * - The `origin` is used to mark the event\n * - The `message` works like a git commit message, which will be recorded and synced to peers\n * - The `timestamp` is the number of seconds that have elapsed since 00:00:00 UTC on January 1, 1970.\n * It defaults to `Date.now() / 1000` when timestamp recording is enabled\n *\n * The events will be emitted after a transaction is committed. A transaction is committed when:\n *\n * - `doc.commit()` is called.\n * - `doc.export(mode)` is called.\n * - `doc.import(data)` is called.\n * - `doc.checkout(version)` is called.\n *\n * NOTE: Timestamps are forced to be in ascending order.\n * If you commit a new change with a timestamp that is less than the existing one,\n * the largest existing timestamp will be used instead.\n *\n * NOTE: The `origin` will not be persisted, but the `message` will.\n *\n * Behavior on empty commits:\n * - This method is an explicit commit. If the pending transaction is empty, any provided\n * options (message/timestamp/origin) are swallowed and will not carry over to the next commit.\n * - Implicit commits triggered by `export`/`checkout` act as processing barriers. If the\n * transaction is empty in those cases, `message`/`timestamp`/`origin` are preserved for the\n * next commit.\n * @param {{ origin?: string, timestamp?: number, message?: string } | null} [options]\n */\n commit(options) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_commit(retptr, this.__wbg_ptr, isLikeNone(options) ? 0 : addHeapObject(options));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Detach the document state from the latest known version.\n *\n * After detaching, all import operations will be recorded in the `OpLog` without being applied to the `DocState`.\n * When `detached`, the document is not editable.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * doc.detach();\n * console.log(doc.isDetached()); // true\n * ```\n */\n detach() {\n wasm.lorodoc_detach(this.__wbg_ptr);\n }\n /**\n * Export the document based on the specified ExportMode.\n *\n * @param mode - The export mode to use. Can be one of:\n * - `{ mode: \"snapshot\" }`: Export a full snapshot of the document.\n * - `{ mode: \"update\", from?: VersionVector }`: Export updates from the given version vector.\n * If `from` is not provided, it will export the whole history of the document.\n * - `{ mode: \"updates-in-range\", spans: { id: ID, len: number }[] }`: Export updates within the specified ID spans.\n * - `{ mode: \"shallow-snapshot\", frontiers: Frontiers }`: Export a garbage-collected snapshot up to the given frontiers.\n *\n * @returns A byte array containing the exported data.\n *\n * This export commits the current local transaction before producing bytes.\n *\n * Snapshot and update exports do not include remote updates that are still\n * waiting for missing causal dependencies. Use `exportPendingUpdates()` to\n * persist those updates separately.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * doc.setPeerId(\"1\");\n * doc.getText(\"text\").update(\"Hello World\");\n *\n * // Export a full snapshot\n * const snapshotBytes = doc.export({ mode: \"snapshot\" });\n *\n * // Export updates from a specific version\n * const vv = doc.oplogVersion();\n * doc.getText(\"text\").update(\"Hello Loro\");\n * const updateBytes = doc.export({ mode: \"update\", from: vv });\n *\n * // Export a shallow snapshot that only includes the history since the frontiers\n * const shallowBytes = doc.export({ mode: \"shallow-snapshot\", frontiers: doc.oplogFrontiers() });\n *\n * // Export updates within specific ID spans\n * const spanBytes = doc.export({\n * mode: \"updates-in-range\",\n * spans: [{ id: { peer: \"1\", counter: 0 }, len: 10 }]\n * });\n * ```\n * @param {ExportMode} mode\n * @returns {Uint8Array}\n */\n export(mode) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_export(retptr, this.__wbg_ptr, addHeapObject(mode));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Import snapshot or updates into current doc.\n *\n * Note:\n * - Updates within the current version will be ignored\n * - Updates with missing dependencies will be pending until the dependencies are received\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * // get all updates of the doc\n * const updates = doc.export({ mode: \"update\" });\n * const snapshot = doc.export({ mode: \"snapshot\" });\n * const doc2 = new LoroDoc();\n * // import snapshot\n * doc2.import(snapshot);\n * // or import updates\n * doc2.import(updates);\n * ```\n * @param {Uint8Array} update_or_snapshot\n * @returns {ImportStatus}\n */\n import(update_or_snapshot) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(update_or_snapshot, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_import(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Creates a new LoroDoc at a specified version (Frontiers)\n *\n * The created doc will only contain the history before the specified frontiers.\n * @param {({ peer: PeerID, counter: number })[]} frontiers\n * @returns {LoroDoc}\n */\n forkAt(frontiers) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(frontiers, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_forkAt(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroDoc.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get a LoroMap by container id\n *\n * The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n *\n * If the container does not exist, an error will be thrown.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * ```\n * @param {ContainerID | string} cid\n * @returns {LoroMap}\n */\n getMap(cid) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getMap(retptr, this.__wbg_ptr, addBorrowedObject(cid));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroMap.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get the number of ops in the oplog.\n * @returns {number}\n */\n opCount() {\n const ret = wasm.lorodoc_opCount(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * Peer ID of the current writer.\n * @returns {bigint}\n */\n get peerId() {\n const ret = wasm.lorodoc_peerId(this.__wbg_ptr);\n return BigInt.asUintN(64, ret);\n }\n /**\n * Get the json format of the entire document state.\n *\n * Unlike `getShallowValue()` which returns container IDs as strings,\n * `toJSON()` recursively resolves all containers to their actual values.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText, LoroMap } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, \"Hello\");\n * const text = list.insertContainer(0, new LoroText());\n * text.insert(0, \"Hello\");\n * const map = list.insertContainer(1, new LoroMap());\n * map.set(\"foo\", \"bar\");\n * console.log(doc.toJSON());\n * // {\"list\": [\"Hello\", {\"foo\": \"bar\"}]}\n * ```\n * @returns {any}\n */\n toJSON() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_toJSON(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the version vector of the current document state.\n *\n * If you checkout to a specific version, the version vector will change.\n * @returns {VersionVector}\n */\n version() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_version(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return VersionVector.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Checkout the `DocState` to a specific version.\n *\n * > The document becomes detached during a `checkout` operation.\n * > Being `detached` implies that the `DocState` is not synchronized with the latest version of the `OpLog`.\n * > In a detached state, the document is not editable, and any `import` operations will be\n * > recorded in the `OpLog` without being applied to the `DocState`.\n *\n * You should call `attach` to attach the `DocState` to the latest version of `OpLog`.\n *\n * @param frontiers - the specific frontiers\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * const frontiers = doc.frontiers();\n * text.insert(0, \"Hello World!\");\n * doc.checkout(frontiers);\n * console.log(doc.toJSON()); // {\"text\": \"\"}\n * ```\n * @param {({ peer: PeerID, counter: number })[]} frontiers\n */\n checkout(frontiers) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(frontiers, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_checkout(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get a LoroList by container id\n *\n * The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n *\n * If the container does not exist, an error will be thrown.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * ```\n * @param {ContainerID | string} cid\n * @returns {LoroList}\n */\n getList(cid) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getList(retptr, this.__wbg_ptr, addBorrowedObject(cid));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroList.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get a LoroText by container id.\n *\n * The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n *\n * If the container does not exist, an error will be thrown.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * ```\n * @param {ContainerID | string} cid\n * @returns {LoroText}\n */\n getText(cid) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getText(retptr, this.__wbg_ptr, addBorrowedObject(cid));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroText.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get a LoroTree by container id\n *\n * The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n *\n * If the container does not exist, an error will be thrown.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * ```\n * @param {ContainerID | string} cid\n * @returns {LoroTree}\n */\n getTree(cid) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getTree(retptr, this.__wbg_ptr, addBorrowedObject(cid));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroTree.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get the [frontiers](https://loro.dev/docs/advanced/version_deep_dive) of the current document state.\n *\n * If you checkout to a specific version, this value will change.\n * @returns {{ peer: PeerID, counter: number }[]}\n */\n frontiers() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_frontiers(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Evaluate JSONPath against a LoroDoc\n * @param {string} jsonpath\n * @returns {Array}\n */\n JSONPath(jsonpath) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(jsonpath, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_JSONPath(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Revert the document to the given frontiers.\n *\n * The doc will not become detached when using this method. Instead, it will generate a series\n * of operations to revert the document to the given version.\n *\n * @example\n * ```ts\n * const doc = new LoroDoc();\n * doc.setPeerId(\"1\");\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * doc.commit();\n * doc.revertTo([{ peer: \"1\", counter: 1 }]);\n * expect(doc.getText(\"text\").toString()).toBe(\"He\");\n * ```\n * @param {({ peer: PeerID, counter: number })[]} frontiers\n */\n revertTo(frontiers) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(frontiers, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_revertTo(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Subscribe to the changes of the loro document. The function will be called when the\n * transaction is committed and after importing updates/snapshot from remote.\n *\n * Returns a subscription callback, which can be used to unsubscribe.\n *\n * The events will be emitted after a transaction is committed. A transaction is committed when:\n *\n * - `doc.commit()` is called.\n * - `doc.export(mode)` is called.\n * - `doc.import(data)` is called.\n * - `doc.checkout(version)` is called.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * const sub = doc.subscribe((event)=>{\n * console.log(event);\n * });\n * text.insert(0, \"Hello\");\n * // the events will be emitted when `commit()` is called.\n * doc.commit();\n * // unsubscribe\n * sub();\n * ```\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n const ret = wasm.lorodoc_subscribe(this.__wbg_ptr, addHeapObject(f));\n return takeObject(ret);\n }\n /**\n * Convert visible roots to independent container trees without committing.\n * The text format applies recursively, including Tree metadata. Unknown or\n * hidden roots are omitted; roots: [] returns an empty object. Reads never\n * create roots. Binary values are owned Uint8Arrays. Not a CRDT export.\n * @param {DocumentContainerTreeOptions | null} [opts]\n * @returns {Record}\n */\n toContainerTree(opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_toContainerTree(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Read visible roots as one JSON string, using the same node shapes and text\n * formats as toContainerTree. No per-value JS calls or implicit commit.\n * Throws for binary or non-finite numbers rather than losing their values.\n * @param {DocumentContainerTreeOptions | null} [opts]\n * @returns {string}\n */\n toContainerTreeJson(opts) {\n let deferred2_0;\n let deferred2_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_toContainerTreeJson(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n var ptr1 = r0;\n var len1 = r1;\n if (r3) {\n ptr1 = 0; len1 = 0;\n throw takeObject(r2);\n }\n deferred2_0 = ptr1;\n deferred2_1 = len1;\n return getStringFromWasm0(ptr1, len1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);\n }\n }\n}\n\nconst LoroListFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_lorolist_free(ptr >>> 0, 1));\n/**\n * The handler of a list container.\n *\n * Learn more at https://loro.dev/docs/tutorial/list\n */\nexport class LoroList {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroList.prototype);\n obj.__wbg_ptr = ptr;\n LoroListFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroListFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_lorolist_free(ptr, 0);\n }\n /**\n * Whether the container is attached to a document.\n *\n * If it's detached, the operations on the container will not be persisted.\n * @returns {boolean}\n */\n isAttached() {\n const ret = wasm.lorolist_isAttached(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the attached container associated with this.\n *\n * Returns an attached `Container` that equals to this or created by this, otherwise `undefined`.\n * @returns {LoroList | undefined}\n */\n getAttached() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_getAttached(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @param {Container} child\n * @returns {Container}\n */\n pushContainer(child) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_pushContainer(retptr, this.__wbg_ptr, addHeapObject(child));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the deep value of the elements in the range `[start, end)`.\n *\n * Each child container in the range is recursively resolved to its deep\n * value. Negative bounds are clamped to 0 and out-of-range bounds are\n * clamped to the list length; an empty or inverted range returns `[]`.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.getRangeValue(0, 2)); // [100, \"Hello\"]\n * ```\n * @param {number} start\n * @param {number} end\n * @returns {any}\n */\n getRangeValue(start, end) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_getRangeValue(retptr, this.__wbg_ptr, start, end);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Insert a container at the index.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.toJSON()); // [100, \"Hello\"];\n * ```\n * @param {number} index\n * @param {Container} child\n * @returns {Container}\n */\n insertContainer(index, child) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_insertContainer(retptr, this.__wbg_ptr, index, addHeapObject(child));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the shallow value of the list.\n *\n * Unlike `toJSON()` which recursively resolves all containers to their values,\n * `getShallowValue()` returns container IDs as strings for any nested containers.\n *\n * ```js\n * const doc = new LoroDoc();\n * doc.setPeerId(\"1\");\n * const list = doc.getList(\"list\");\n * list.insert(0, 1);\n * list.insert(1, \"two\");\n * const subList = list.insertContainer(2, new LoroList());\n * subList.insert(0, \"sub\");\n * list.getShallowValue(); // [1, \"two\", \"cid:2@1:List\"]\n * list.toJSON(); // [1, \"two\", [\"sub\"]]\n * ```\n * @returns {Value[]}\n */\n getShallowValue() {\n const ret = wasm.lorolist_getShallowValue(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the deep value of the list with its container id.\n *\n * The result is a `{ cid, value }` object, where `cid` is the container id\n * string (the same as `list.id`) and `value` is the deep value of the\n * list. Child containers inside `value` are recursively replaced by their\n * own `{ cid, value }` nodes. This is the same node shape that\n * `LoroDoc.getDeepValueWithID()` emits for every container.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.getDeepValueWithID());\n * // { cid: \"cid:root-list:List\",\n * // value: [100, { cid: \"cid:0@1:Text\", value: \"Hello\" }] }\n * ```\n * @returns {any}\n */\n getDeepValueWithID() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_getDeepValueWithID(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the deep value of the elements in the range `[start, end)`, with\n * container ids.\n *\n * Each child container in the range is recursively replaced by its own\n * `{ cid, value }` node. Negative bounds are clamped to 0 and\n * out-of-range bounds are clamped to the list length; an empty or\n * inverted range returns `[]`.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.getRangeDeepValueWithID(0, 2));\n * // [100, { cid: \"cid:0@1:Text\", value: \"Hello\" }]\n * ```\n * @param {number} start\n * @param {number} end\n * @returns {any}\n */\n getRangeDeepValueWithID(start, end) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_getRangeDeepValueWithID(retptr, this.__wbg_ptr, start, end);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the id of this container.\n * @returns {ContainerID}\n */\n get id() {\n const ret = wasm.lorolist_id(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the value at the index. If the value is a container, the corresponding handler will be returned.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * console.log(list.get(0)); // 100\n * console.log(list.get(1)); // undefined\n * ```\n * @param {number} index\n * @returns {Value | Container | undefined}\n */\n get(index) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_get(retptr, this.__wbg_ptr, index);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Create a new detached LoroList (not attached to any LoroDoc).\n *\n * The edits on a detached container will not be persisted.\n * To attach the container to the document, please insert it into an attached container.\n */\n constructor() {\n const ret = wasm.lorolist_new();\n this.__wbg_ptr = ret >>> 0;\n LoroListFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * Pop a value from the end of the list.\n * @returns {Value | undefined}\n */\n pop() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_pop(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * \"List\"\n * @returns {'List'}\n */\n kind() {\n const ret = wasm.lorolist_kind(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Push a value to the end of the list.\n * @param {Value} value\n */\n push(value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_push(retptr, this.__wbg_ptr, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Delete all elements in the list.\n */\n clear() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_clear(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Delete elements from index to index + len.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.delete(0, 1);\n * console.log(list.value); // []\n * ```\n * @param {number} index\n * @param {number} len\n */\n delete(index, len) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_delete(retptr, this.__wbg_ptr, index, len);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Insert a value at index.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.insert(1, \"foo\");\n * list.insert(2, true);\n * console.log(list.value); // [100, \"foo\", true];\n * ```\n * @param {number} index\n * @param {Value} value\n */\n insert(index, value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_insert(retptr, this.__wbg_ptr, index, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the length of list.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.insert(1, \"foo\");\n * list.insert(2, true);\n * console.log(list.length); // 3\n * ```\n * @returns {number}\n */\n get length() {\n const ret = wasm.lorolist_length(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * Get the parent container.\n *\n * - The parent container of the root tree is `undefined`.\n * - The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n * @returns {Container | undefined}\n */\n parent() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_parent(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @param {number} pos\n * @returns {{ peer: PeerID, counter: number } | undefined}\n */\n getIdAt(pos) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_getIdAt(retptr, this.__wbg_ptr, pos);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get elements of the list. If the type of a element is a container, it will be\n * resolved recursively.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.toJSON()); // [100, \"Hello\"];\n * ```\n * @returns {any}\n */\n toJSON() {\n const ret = wasm.lorolist_toJSON(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get elements of the list. If the value is a child container, the corresponding\n * `Container` will be returned.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.insert(1, \"foo\");\n * list.insert(2, true);\n * list.insertContainer(3, new LoroText());\n * console.log(list.value); // [100, \"foo\", true, LoroText];\n * ```\n * @returns {(Value | Container)[]}\n */\n toArray() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_toArray(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the cursor at the position.\n *\n * - The first argument is the position .\n * - The second argument is the side: `-1` for left, `0` for middle, `1` for right.\n * @param {number} pos\n * @param {Side} side\n * @returns {Cursor | undefined}\n */\n getCursor(pos, side) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_getCursor(retptr, this.__wbg_ptr, pos, addHeapObject(side));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 === 0 ? undefined : Cursor.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Check if the container is deleted\n * @returns {boolean}\n */\n isDeleted() {\n const ret = wasm.lorolist_isDeleted(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Subscribe to the changes of the list.\n *\n * Returns a subscription callback, which can be used to unsubscribe.\n *\n * The events will be emitted after a transaction is committed. A transaction is committed when:\n *\n * - `doc.commit()` is called.\n * - `doc.export(mode)` is called.\n * - `doc.import(data)` is called.\n * - `doc.checkout(version)` is called.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.subscribe((event)=>{\n * console.log(event);\n * });\n * list.insert(0, 100);\n * doc.commit();\n * ```\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_subscribe(retptr, this.__wbg_ptr, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert this attached container and all descendants to an independent tree.\n * Text format applies recursively. Does not commit; throws for detached\n * containers, unsupported types, invalid options, or nesting above 256.\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerNode}\n */\n toContainerTree(opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_toContainerTree(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Read [start,end), clamped to list length. Inverted bounds return no items.\n * Returns actual start, totalLength and items; this is not a complete container.\n * Only selected descendants are traversed; parent shallow list access is O(N).\n * @param {number} start\n * @param {number} end\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerTreeSlice}\n */\n toContainerTreeSlice(start, end, opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_toContainerTreeSlice(retptr, this.__wbg_ptr, start, end, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst LoroMapFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_loromap_free(ptr >>> 0, 1));\n/**\n * The handler of a map container.\n *\n * Learn more at https://loro.dev/docs/tutorial/map\n *\n * ## Mergeable child containers\n *\n * `ensureMergeable*` methods create deterministic child containers under a map\n * key. If two peers independently call the same method with the same parent\n * map, key, and container type, they get the same child container id and their\n * subsequent edits merge in that child.\n *\n * Loro activates a mergeable child by writing a specially constructed binary\n * marker value into the parent map slot. String values do not activate\n * mergeable children. If the key already holds a non-mergeable value,\n * `ensureMergeable*` returns an error and leaves the value unchanged.\n * Calling `ensureMergeable*` with a different container type at an existing\n * mergeable key is a deliberate kind change: the map slot activates the new\n * type, while the state of the other mergeable child remains preserved under\n * its deterministic id.\n *\n * Deleting the map key clears the ref and hides the mergeable child, but the\n * child's state is preserved. Calling the same `ensureMergeable*` method again\n * writes the ref back and resurfaces the preserved state.\n */\nexport class LoroMap {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroMap.prototype);\n obj.__wbg_ptr = ptr;\n LoroMapFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroMapFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_loromap_free(ptr, 0);\n }\n /**\n * Whether the container is attached to a document.\n *\n * If it's detached, the operations on the container will not be persisted.\n * @returns {boolean}\n */\n isAttached() {\n const ret = wasm.loromap_isAttached(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the attached container associated with this.\n *\n * Returns an attached `Container` that equals to this or created by this, otherwise `undefined`.\n * @returns {LoroMap | undefined}\n */\n getAttached() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_getAttached(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the peer id of the last editor on the given entry\n * @param {string} key\n * @returns {PeerID | undefined}\n */\n getLastEditor(key) {\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.loromap_getLastEditor(this.__wbg_ptr, ptr0, len0);\n return takeObject(ret);\n }\n /**\n * Set the key with a regular child container.\n *\n * The inserted child receives a regular op-created container id. Use this\n * for replacement semantics or when each creation should produce a distinct\n * child. Use `ensureMergeable*` when peers may lazily initialize the same\n * logical child under a map key.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText, LoroList } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * const text = map.setContainer(\"text\", new LoroText());\n * const list = map.setContainer(\"list\", new LoroList());\n * ```\n * @param {string} key\n * @param {Container} child\n * @returns {Container}\n */\n setContainer(key, child) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_setContainer(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(child));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the shallow value of the map.\n *\n * Unlike `toJSON()` which recursively resolves all containers to their values,\n * `getShallowValue()` returns container IDs as strings for any nested containers.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * doc.setPeerId(\"1\");\n * const map = doc.getMap(\"map\");\n * map.set(\"key\", \"value\");\n * const subText = map.setContainer(\"text\", new LoroText());\n * subText.insert(0, \"Hello\");\n *\n * // Get shallow value - nested containers are represented by their IDs\n * console.log(map.getShallowValue());\n * // Output: { key: \"value\", text: \"cid:1@1:Text\" }\n *\n * // Get full value with nested containers resolved by `toJSON()`\n * console.log(map.toJSON());\n * // Output: { key: \"value\", text: \"Hello\" }\n * ```\n * @returns {Record}\n */\n getShallowValue() {\n const ret = wasm.loromap_getShallowValue(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Ensure a mergeable Map exists under the given key and return it.\n *\n * If the map is detached, or if the key already holds a non-mergeable\n * value, this throws and leaves the value unchanged.\n *\n * Prefer to avoid very deep mergeable-map chains: mergeable cids encode\n * their flattened logical path, so cid size still grows with depth and\n * rides through every op/snapshot reference to it.\n * @param {string} key\n * @returns {LoroMap}\n */\n ensureMergeableMap(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_ensureMergeableMap(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroMap.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Ensure a mergeable List exists under the given key and return it.\n *\n * If the map is detached, or if the key already holds a non-mergeable\n * value, this throws and leaves the value unchanged.\n * @param {string} key\n * @returns {LoroList}\n */\n ensureMergeableList(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_ensureMergeableList(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroList.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Ensure a mergeable Text exists under the given key and return it.\n *\n * If the map is detached, or if the key already holds a non-mergeable\n * value, this throws and leaves the value unchanged.\n * @param {string} key\n * @returns {LoroText}\n */\n ensureMergeableText(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_ensureMergeableText(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroText.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Ensure a mergeable Tree exists under the given key and return it.\n *\n * If the map is detached, or if the key already holds a non-mergeable\n * value, this throws and leaves the value unchanged.\n * @param {string} key\n * @returns {LoroTree}\n */\n ensureMergeableTree(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_ensureMergeableTree(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroTree.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the deep value of the map with its container id.\n *\n * The result is a `{ cid, value }` object, where `cid` is the container id\n * string (the same as `map.id`) and `value` is the deep value of the map.\n * Child containers inside `value` are recursively replaced by their own\n * `{ cid, value }` nodes. This is the same node shape that\n * `LoroDoc.getDeepValueWithID()` emits for every container.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * const text = map.setContainer(\"text\", new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(map.getDeepValueWithID());\n * // { cid: \"cid:root-map:Map\",\n * // value: { foo: \"bar\", text: { cid: \"cid:0@1:Text\", value: \"Hello\" } } }\n * ```\n * @returns {any}\n */\n getDeepValueWithID() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_getDeepValueWithID(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get or create a regular child container at the given key.\n *\n * @deprecated Use `ensureMergeable*` for lazy map-key child creation. This\n * method creates regular op-id children, so concurrent first creation at\n * the same key can fork child state and leave one branch hidden by map\n * conflict resolution. Use `setContainer` for regular replacement/attach\n * semantics.\n *\n * If the key is empty or `null`, this creates a regular child container.\n * If the key already holds a child of the same type, it returns that child.\n * If the key holds a scalar or a child of another type, it throws.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * const text = map.getOrCreateContainer(\"text\", new LoroText());\n * text.insert(0, \"legacy regular child\");\n * ```\n * @param {string} key\n * @param {Container} child\n * @returns {Container}\n */\n getOrCreateContainer(key, child) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_getOrCreateContainer(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(child));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Ensure a mergeable Counter exists under the given key and return it.\n *\n * If the map is detached, or if the key already holds a non-mergeable\n * value, this throws and leaves the value unchanged.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const counter = doc.getMap(\"state\").ensureMergeableCounter(\"revision\");\n * counter.increment(1);\n * ```\n * @param {string} key\n * @returns {LoroCounter}\n */\n ensureMergeableCounter(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_ensureMergeableCounter(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroCounter.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Ensure a mergeable MovableList exists under the given key and return it.\n *\n * If the map is detached, or if the key already holds a non-mergeable\n * value, this throws and leaves the value unchanged.\n * @param {string} key\n * @returns {LoroMovableList}\n */\n ensureMergeableMovableList(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_ensureMergeableMovableList(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroMovableList.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * The container id of this handler.\n * @returns {ContainerID}\n */\n get id() {\n const ret = wasm.loromap_id(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the value of the key. If the value is a child container, the corresponding\n * `Container` will be returned.\n *\n * The object/value returned is a new js object/value each time because it need to cross\n * the WASM boundary.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * const bar = map.get(\"foo\");\n * ```\n * @param {string} key\n * @returns {Value | Container | undefined}\n */\n get(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_get(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Create a new detached LoroMap (not attached to any LoroDoc).\n *\n * The edits on a detached container will not be persisted.\n * To attach the container to the document, please insert it into an attached container.\n */\n constructor() {\n const ret = wasm.loromap_new();\n this.__wbg_ptr = ret >>> 0;\n LoroMapFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * Get the keys of the map.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * map.set(\"baz\", \"bar\");\n * const keys = map.keys(); // [\"foo\", \"baz\"]\n * ```\n * @returns {any[]}\n */\n keys() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_keys(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * \"Map\"\n * @returns {'Map'}\n */\n kind() {\n const ret = wasm.loromap_kind(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the size of the map.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * console.log(map.size); // 1\n * ```\n * @returns {number}\n */\n get size() {\n const ret = wasm.loromap_size(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * Delete all key-value pairs in the map.\n */\n clear() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_clear(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Remove the key from the map.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * map.delete(\"foo\");\n * ```\n * @param {string} key\n */\n delete(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_delete(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Set the key with the value.\n *\n * If the value of the key is exist, the old value will be updated.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * map.set(\"foo\", \"baz\");\n * ```\n * @param {string} key\n * @param {Value} value\n */\n set(key, value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_set(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the parent container.\n *\n * - The parent container of the root tree is `undefined`.\n * - The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n * @returns {Container | undefined}\n */\n parent() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_parent(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the values of the map. If the value is a child container, the corresponding\n * `Container` will be returned.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * map.set(\"baz\", \"bar\");\n * const values = map.values(); // [\"bar\", \"bar\"]\n * ```\n * @returns {any[]}\n */\n values() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_values(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the entries of the map. If the value is a child container, the corresponding\n * `Container` will be returned.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * map.set(\"baz\", \"bar\");\n * const entries = map.entries(); // [[\"foo\", \"bar\"], [\"baz\", \"bar\"]]\n * ```\n * @returns {([string, Value | Container])[]}\n */\n entries() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_entries(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the keys and the values. If the type of value is a child container,\n * it will be resolved recursively.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * const text = map.setContainer(\"text\", new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(map.toJSON()); // {\"foo\": \"bar\", \"text\": \"Hello\"}\n * ```\n * @returns {any}\n */\n toJSON() {\n const ret = wasm.loromap_toJSON(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Check if the container is deleted\n * @returns {boolean}\n */\n isDeleted() {\n const ret = wasm.loromap_isDeleted(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Subscribe to the changes of the map.\n *\n * Returns a subscription callback, which can be used to unsubscribe.\n *\n * The events will be emitted after a transaction is committed. A transaction is committed when:\n *\n * - `doc.commit()` is called.\n * - `doc.export(mode)` is called.\n * - `doc.import(data)` is called.\n * - `doc.checkout(version)` is called.\n *\n * @param {Listener} f - Event listener\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.subscribe((event)=>{\n * console.log(event);\n * });\n * map.set(\"foo\", \"bar\");\n * doc.commit();\n * ```\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_subscribe(retptr, this.__wbg_ptr, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert this attached container and all descendants to an independent tree.\n * Text format applies recursively. Does not commit; throws for detached\n * containers, unsupported types, invalid options, or nesting above 256.\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerNode}\n */\n toContainerTree(opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_toContainerTree(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst LoroMovableListFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_loromovablelist_free(ptr >>> 0, 1));\n/**\n * The handler of a list container.\n *\n * Learn more at https://loro.dev/docs/tutorial/list\n */\nexport class LoroMovableList {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroMovableList.prototype);\n obj.__wbg_ptr = ptr;\n LoroMovableListFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroMovableListFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_loromovablelist_free(ptr, 0);\n }\n /**\n * Whether the container is attached to a document.\n *\n * If it's detached, the operations on the container will not be persisted.\n * @returns {boolean}\n */\n isAttached() {\n const ret = wasm.loromovablelist_isAttached(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the creator of the list item at the given position.\n * @param {number} pos\n * @returns {PeerID | undefined}\n */\n getCreatorAt(pos) {\n const ret = wasm.loromovablelist_getCreatorAt(this.__wbg_ptr, pos);\n return takeObject(ret);\n }\n /**\n * Get the attached container associated with this.\n *\n * Returns an attached `Container` that equals to this or created by this, otherwise `undefined`.\n * @returns {LoroList | undefined}\n */\n getAttached() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_getAttached(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Set the container at the given position.\n * @param {number} pos\n * @param {Container} child\n * @returns {Container}\n */\n setContainer(pos, child) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_setContainer(retptr, this.__wbg_ptr, pos, addHeapObject(child));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the last mover of the list item at the given position.\n * @param {number} pos\n * @returns {PeerID | undefined}\n */\n getLastMoverAt(pos) {\n const ret = wasm.loromovablelist_getLastMoverAt(this.__wbg_ptr, pos);\n return takeObject(ret);\n }\n /**\n * Push a container to the end of the list.\n * @param {Container} child\n * @returns {Container}\n */\n pushContainer(child) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_pushContainer(retptr, this.__wbg_ptr, addHeapObject(child));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the last editor of the list item at the given position.\n * @param {number} pos\n * @returns {PeerID | undefined}\n */\n getLastEditorAt(pos) {\n const ret = wasm.loromovablelist_getLastEditorAt(this.__wbg_ptr, pos);\n return takeObject(ret);\n }\n /**\n * Get the deep value of the elements in the range `[start, end)`.\n *\n * Each child container in the range is recursively resolved to its deep\n * value. Negative bounds are clamped to 0 and out-of-range bounds are\n * clamped to the list length; an empty or inverted range returns `[]`.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getMovableList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.getRangeValue(0, 2)); // [100, \"Hello\"]\n * ```\n * @param {number} start\n * @param {number} end\n * @returns {any}\n */\n getRangeValue(start, end) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_getRangeValue(retptr, this.__wbg_ptr, start, end);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Insert a container at the index.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.toJSON()); // [100, \"Hello\"];\n * ```\n * @param {number} index\n * @param {Container} child\n * @returns {Container}\n */\n insertContainer(index, child) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_insertContainer(retptr, this.__wbg_ptr, index, addHeapObject(child));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the shallow value of the movable list.\n *\n * Unlike `toJSON()` which recursively resolves all containers to their values,\n * `getShallowValue()` returns container IDs as strings for any nested containers.\n *\n * ```js\n * const doc = new LoroDoc();\n * doc.setPeerId(\"1\");\n * const list = doc.getMovableList(\"list\");\n * list.insert(0, 1);\n * list.insert(1, \"two\");\n * const subList = list.insertContainer(2, new LoroList());\n * subList.insert(0, \"sub\");\n * list.getShallowValue(); // [1, \"two\", \"cid:2@1:List\"]\n * list.toJSON(); // [1, \"two\", [\"sub\"]]\n * ```\n * @returns {Value[]}\n */\n getShallowValue() {\n const ret = wasm.loromovablelist_getShallowValue(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the deep value of the movable list with its container id.\n *\n * The result is a `{ cid, value }` object, where `cid` is the container id\n * string (the same as `list.id`) and `value` is the deep value of the\n * list. Child containers inside `value` are recursively replaced by their\n * own `{ cid, value }` nodes. This is the same node shape that\n * `LoroDoc.getDeepValueWithID()` emits for every container.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getMovableList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.getDeepValueWithID());\n * // { cid: \"cid:root-list:MovableList\",\n * // value: [100, { cid: \"cid:0@1:Text\", value: \"Hello\" }] }\n * ```\n * @returns {any}\n */\n getDeepValueWithID() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_getDeepValueWithID(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the deep value of the elements in the range `[start, end)`, with\n * container ids.\n *\n * Each child container in the range is recursively replaced by its own\n * `{ cid, value }` node. Negative bounds are clamped to 0 and\n * out-of-range bounds are clamped to the list length; an empty or\n * inverted range returns `[]`.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getMovableList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.getRangeDeepValueWithID(0, 2));\n * // [100, { cid: \"cid:0@1:Text\", value: \"Hello\" }]\n * ```\n * @param {number} start\n * @param {number} end\n * @returns {any}\n */\n getRangeDeepValueWithID(start, end) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_getRangeDeepValueWithID(retptr, this.__wbg_ptr, start, end);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the id of this container.\n * @returns {ContainerID}\n */\n get id() {\n const ret = wasm.loromovablelist_id(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the value at the index. If the value is a container, the corresponding handler will be returned.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * console.log(list.get(0)); // 100\n * console.log(list.get(1)); // undefined\n * ```\n * @param {number} index\n * @returns {Value | Container | undefined}\n */\n get(index) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_get(retptr, this.__wbg_ptr, index);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Move the element from `from` to `to`.\n *\n * The new position of the element will be `to`.\n * Move the element from `from` to `to`.\n *\n * The new position of the element will be `to`. This method is optimized to prevent redundant\n * operations that might occur with a naive remove and insert approach. Specifically, it avoids\n * creating surplus values in the list, unlike a delete followed by an insert, which can lead to\n * additional values in cases of concurrent edits. This ensures more efficient and accurate\n * operations in a MovableList.\n * @param {number} from\n * @param {number} to\n */\n move(from, to) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_move(retptr, this.__wbg_ptr, from, to);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Create a new detached LoroMovableList (not attached to any LoroDoc).\n *\n * The edits on a detached container will not be persisted.\n * To attach the container to the document, please insert it into an attached container.\n */\n constructor() {\n const ret = wasm.loromovablelist_new();\n this.__wbg_ptr = ret >>> 0;\n LoroMovableListFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * Pop a value from the end of the list.\n * @returns {Value | undefined}\n */\n pop() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_pop(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Set the value at the given position.\n *\n * It's different from `delete` + `insert` that it will replace the value at the position.\n *\n * For example, if you have a list `[1, 2, 3]`, and you call `set(1, 100)`, the list will be `[1, 100, 3]`.\n * If concurrently someone call `set(1, 200)`, the list will be `[1, 200, 3]` or `[1, 100, 3]`.\n *\n * But if you use `delete` + `insert` to simulate the set operation, they may create redundant operations\n * and the final result will be `[1, 100, 200, 3]` or `[1, 200, 100, 3]`.\n * @param {number} pos\n * @param {Value} value\n */\n set(pos, value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_set(retptr, this.__wbg_ptr, pos, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * \"MovableList\"\n * @returns {'MovableList'}\n */\n kind() {\n const ret = wasm.loromovablelist_kind(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Push a value to the end of the list.\n * @param {Value} value\n */\n push(value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_push(retptr, this.__wbg_ptr, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Delete all elements in the list.\n */\n clear() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_clear(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Delete elements from index to index + len.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.delete(0, 1);\n * console.log(list.value); // []\n * ```\n * @param {number} index\n * @param {number} len\n */\n delete(index, len) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_delete(retptr, this.__wbg_ptr, index, len);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Insert a value at index.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.insert(1, \"foo\");\n * list.insert(2, true);\n * console.log(list.value); // [100, \"foo\", true];\n * ```\n * @param {number} index\n * @param {Value} value\n */\n insert(index, value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_insert(retptr, this.__wbg_ptr, index, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the length of list.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.insert(1, \"foo\");\n * list.insert(2, true);\n * console.log(list.length); // 3\n * ```\n * @returns {number}\n */\n get length() {\n const ret = wasm.loromovablelist_length(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * Get the parent container.\n *\n * - The parent container of the root tree is `undefined`.\n * - The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n * @returns {Container | undefined}\n */\n parent() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_parent(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get elements of the list. If the type of a element is a container, it will be\n * resolved recursively.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.toJSON()); // [100, \"Hello\"];\n * ```\n * @returns {any}\n */\n toJSON() {\n const ret = wasm.loromovablelist_toJSON(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get elements of the list. If the value is a child container, the corresponding\n * `Container` will be returned.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.insert(1, \"foo\");\n * list.insert(2, true);\n * list.insertContainer(3, new LoroText());\n * console.log(list.value); // [100, \"foo\", true, LoroText];\n * ```\n * @returns {(Value | Container)[]}\n */\n toArray() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_toArray(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the cursor of the container.\n * @param {number} pos\n * @param {Side} side\n * @returns {Cursor | undefined}\n */\n getCursor(pos, side) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_getCursor(retptr, this.__wbg_ptr, pos, addHeapObject(side));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 === 0 ? undefined : Cursor.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Check if the container is deleted\n * @returns {boolean}\n */\n isDeleted() {\n const ret = wasm.loromovablelist_isDeleted(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Subscribe to the changes of the list.\n *\n * Returns a subscription callback, which can be used to unsubscribe.\n *\n * The events will be emitted after a transaction is committed. A transaction is committed when:\n *\n * - `doc.commit()` is called.\n * - `doc.export(mode)` is called.\n * - `doc.import(data)` is called.\n * - `doc.checkout(version)` is called.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.subscribe((event)=>{\n * console.log(event);\n * });\n * list.insert(0, 100);\n * doc.commit();\n * ```\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_subscribe(retptr, this.__wbg_ptr, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert this attached container and all descendants to an independent tree.\n * Text format applies recursively. Does not commit; throws for detached\n * containers, unsupported types, invalid options, or nesting above 256.\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerNode}\n */\n toContainerTree(opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_toContainerTree(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Read [start,end), clamped to list length. Inverted bounds return no items.\n * Returns actual start, totalLength and items; this is not a complete container.\n * Only selected descendants are traversed; parent shallow list access is O(N).\n * @param {number} start\n * @param {number} end\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerTreeSlice}\n */\n toContainerTreeSlice(start, end, opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_toContainerTreeSlice(retptr, this.__wbg_ptr, start, end, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst LoroTextFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_lorotext_free(ptr >>> 0, 1));\n/**\n * The handler of a text container. It supports rich text CRDT.\n *\n * Learn more at https://loro.dev/docs/tutorial/text\n */\nexport class LoroText {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroText.prototype);\n obj.__wbg_ptr = ptr;\n LoroTextFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroTextFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_lorotext_free(ptr, 0);\n }\n /**\n * Change the state of this text by delta.\n *\n * If a delta item is `insert`, it should include all the attributes of the inserted text.\n * Loro's rich text CRDT may make the inserted text inherit some styles when you use\n * `insert` method directly. However, when you use `applyDelta` if some attributes are\n * inherited from CRDT but not included in the delta, they will be removed.\n *\n * Another special property of `applyDelta` is if you format an attribute for ranges out of\n * the text length, Loro will insert new lines to fill the gap first. It's useful when you\n * build the binding between Loro and rich text editors like Quill, which might assume there\n * is always a newline at the end of the text implicitly.\n *\n * @example\n * ```ts\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * doc.configTextStyle({bold: {expand: \"after\"}});\n * text.insert(0, \"Hello World!\");\n * text.mark({ start: 0, end: 5 }, \"bold\", true);\n * const delta = text.toDelta();\n * const text2 = doc.getText(\"text2\");\n * text2.applyDelta(delta);\n * expect(text2.toDelta()).toStrictEqual(delta);\n * ```\n * @param {Delta[]} delta\n */\n applyDelta(delta) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_applyDelta(retptr, this.__wbg_ptr, addHeapObject(delta));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert a position between coordinate systems.\n *\n * Supported values: `\"unicode\"`, `\"utf16\"`, `\"utf8\"`.\n *\n * Returns `undefined` when out of bounds or unsupported.\n * @param {number} index\n * @param {string} from\n * @param {string} to\n * @returns {any}\n */\n convertPos(index, from, to) {\n const ptr0 = passStringToWasm0(from, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passStringToWasm0(to, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.lorotext_convertPos(this.__wbg_ptr, index, ptr0, len0, ptr1, len1);\n return takeObject(ret);\n }\n /**\n * Delete elements from index to utf-8 index + len\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insertUtf8(0, \"Hello\");\n * text.deleteUtf8(1, 3);\n * const s = text.toString();\n * console.log(s); // \"Ho\"\n * ```\n * @param {number} index\n * @param {number} len\n */\n deleteUtf8(index, len) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_deleteUtf8(retptr, this.__wbg_ptr, index, len);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the editor of the text at the given position.\n *\n * Returns `undefined` if the position is out of range.\n * @param {number} pos\n * @returns {PeerID | undefined}\n */\n getEditorOf(pos) {\n const ret = wasm.lorotext_getEditorOf(this.__wbg_ptr, pos);\n return takeObject(ret);\n }\n /**\n * Insert some string at utf-8 index.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insertUtf8(0, \"Hello\");\n * ```\n * @param {number} index\n * @param {string} content\n */\n insertUtf8(index, content) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_insertUtf8(retptr, this.__wbg_ptr, index, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Whether the container is attached to a LoroDoc.\n *\n * If it's detached, the operations on the container will not be persisted.\n * @returns {boolean}\n */\n isAttached() {\n const ret = wasm.lorotext_isAttached(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the rich text delta in the given range (utf-16 index).\n * @param {number} start\n * @param {number} end\n * @returns {Delta[]}\n */\n sliceDelta(start, end) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_sliceDelta(retptr, this.__wbg_ptr, start, end);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the attached container associated with this.\n *\n * Returns an attached `Container` that is equal to this or created by this; otherwise, it returns `undefined`.\n * @returns {LoroText | undefined}\n */\n getAttached() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_getAttached(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Update the current text to the target text, the difference is calculated line by line.\n *\n * It uses Myers' diff algorithm to compute the optimal difference.\n * @param {string} text\n * @param {any} options\n */\n updateByLine(text, options) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_updateByLine(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(options));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the rich text delta in the given range (utf-8 index).\n * @param {number} start\n * @param {number} end\n * @returns {Delta[]}\n */\n sliceDeltaUtf8(start, end) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_sliceDeltaUtf8(retptr, this.__wbg_ptr, start, end);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the shallow value of the text. This equals to `text.toString()`.\n * @returns {string}\n */\n getShallowValue() {\n let deferred1_0;\n let deferred1_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_getShallowValue(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n deferred1_0 = r0;\n deferred1_1 = r1;\n return getStringFromWasm0(r0, r1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n }\n /**\n * Get the deep value of the text with its container id.\n *\n * The result is a `{ cid, value }` object, where `cid` is the container id\n * string (the same as `text.id`) and `value` is the text content. This is\n * the same node shape that `LoroDoc.getDeepValueWithID()` emits for every\n * container.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * console.log(text.getDeepValueWithID()); // { cid: \"cid:root-text:Text\", value: \"Hello\" }\n * ```\n * @returns {any}\n */\n getDeepValueWithID() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_getDeepValueWithID(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the container id of the text.\n * @returns {ContainerID}\n */\n get id() {\n const ret = wasm.lorotext_id(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Create a new detached LoroText (not attached to any LoroDoc).\n *\n * The edits on a detached container will not be persisted.\n * To attach the container to the document, please insert it into an attached container.\n */\n constructor() {\n const ret = wasm.lorotext_new();\n this.__wbg_ptr = ret >>> 0;\n LoroTextFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * Iterate each text span(internal storage unit)\n *\n * The callback function will be called for each span in the text.\n * If the callback returns `false`, the iteration will stop.\n *\n * The current text chunks are snapshotted before callbacks run, so the callback\n * may read or mutate the document without re-entering internal state locks.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * text.iter((str) => (console.log(str), true));\n * ```\n * @param {(text: string) => boolean} callback\n */\n iter(callback) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_iter(retptr, this.__wbg_ptr, addHeapObject(callback));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * \"Text\"\n * @returns {'Text'}\n */\n kind() {\n const ret = wasm.lorotext_kind(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Mark a range of text with a key and a value (utf-16 index).\n *\n * > You should call `configTextStyle` before using `mark` and `unmark`.\n *\n * You can use it to create a highlight, make a range of text bold, or add a link to a range of text.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * doc.configTextStyle({bold: {expand: \"after\"}});\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello World!\");\n * text.mark({ start: 0, end: 5 }, \"bold\", true);\n * ```\n * @param {{ start: number, end: number }} range\n * @param {string} key\n * @param {any} value\n */\n mark(range, key, value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_mark(retptr, this.__wbg_ptr, addHeapObject(range), ptr0, len0, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Push a string to the end of the text.\n * @param {string} s\n */\n push(s) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(s, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_push(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get a string slice (utf-16 index).\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * text.slice(0, 2); // \"He\"\n * ```\n * @param {number} start_index\n * @param {number} end_index\n * @returns {string}\n */\n slice(start_index, end_index) {\n let deferred2_0;\n let deferred2_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_slice(retptr, this.__wbg_ptr, start_index, end_index);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n var ptr1 = r0;\n var len1 = r1;\n if (r3) {\n ptr1 = 0; len1 = 0;\n throw takeObject(r2);\n }\n deferred2_0 = ptr1;\n deferred2_1 = len1;\n return getStringFromWasm0(ptr1, len1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);\n }\n }\n /**\n * Delete elements from index to index + len (utf-16 index).\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * text.delete(1, 3);\n * const s = text.toString();\n * console.log(s); // \"Ho\"\n * ```\n * @param {number} index\n * @param {number} len\n */\n delete(index, len) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_delete(retptr, this.__wbg_ptr, index, len);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Insert the string at the given index (utf-16 index).\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * ```\n * @param {number} index\n * @param {string} content\n */\n insert(index, content) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_insert(retptr, this.__wbg_ptr, index, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the length of text (utf-16 length).\n * @returns {number}\n */\n get length() {\n const ret = wasm.lorotext_length(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * Get the parent container.\n *\n * - The parent of the root is `undefined`.\n * - The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n * @returns {Container | undefined}\n */\n parent() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_parent(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Delete and return the string at the given range and insert a string at the same position (utf-16 index).\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * text.splice(2, 3, \"llo\"); // \"llo\"\n * ```\n * @param {number} pos\n * @param {number} len\n * @param {string} s\n * @returns {string}\n */\n splice(pos, len, s) {\n let deferred3_0;\n let deferred3_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(s, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_splice(retptr, this.__wbg_ptr, pos, len, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n var ptr2 = r0;\n var len2 = r1;\n if (r3) {\n ptr2 = 0; len2 = 0;\n throw takeObject(r2);\n }\n deferred3_0 = ptr2;\n deferred3_1 = len2;\n return getStringFromWasm0(ptr2, len2);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);\n }\n }\n /**\n * Unmark a range of text with a key and a value (utf-16 index).\n *\n * > You should call `configTextStyle` before using `mark` and `unmark`.\n *\n * You can use it to remove highlights, bolds or links\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * doc.configTextStyle({bold: {expand: \"after\"}});\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello World!\");\n * text.mark({ start: 0, end: 5 }, \"bold\", true);\n * text.unmark({ start: 0, end: 5 }, \"bold\");\n * ```\n * @param {{ start: number, end: number }} range\n * @param {string} key\n */\n unmark(range, key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_unmark(retptr, this.__wbg_ptr, addHeapObject(range), ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Update the current text to the target text.\n *\n * It will calculate the minimal difference and apply it to the current text.\n * It uses Myers' diff algorithm to compute the optimal difference.\n *\n * This could take a long time for large texts (e.g. > 50_000 characters).\n * In that case, you should use `updateByLine` instead.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * text.update(\"Hello World\");\n * console.log(text.toString()); // \"Hello World\"\n * ```\n * @param {string} text\n * @param {any} options\n */\n update(text, options) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_update(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(options));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the character at the given position (utf-16 index).\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * text.charAt(0); // \"H\"\n * ```\n * @param {number} pos\n * @returns {string}\n */\n charAt(pos) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_charAt(retptr, this.__wbg_ptr, pos);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return String.fromCodePoint(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the JSON representation of the text.\n * @returns {any}\n */\n toJSON() {\n const ret = wasm.lorotext_toJSON(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the text in [Delta](https://quilljs.com/docs/delta/) format.\n *\n * The returned value will include the rich text information.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * doc.configTextStyle({bold: {expand: \"after\"}});\n * text.insert(0, \"Hello World!\");\n * text.mark({ start: 0, end: 5 }, \"bold\", true);\n * console.log(text.toDelta()); // [ { insert: 'Hello', attributes: { bold: true } } ]\n * ```\n * @returns {Delta[]}\n */\n toDelta() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_toDelta(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the cursor at the given position.\n *\n * - The first argument is the position (utf16-index).\n * - The second argument is the side: `-1` for left, `0` for middle, `1` for right.\n * @param {number} pos\n * @param {Side} side\n * @returns {Cursor | undefined}\n */\n getCursor(pos, side) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_getCursor(retptr, this.__wbg_ptr, pos, addHeapObject(side));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 === 0 ? undefined : Cursor.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Check if the container is deleted\n * @returns {boolean}\n */\n isDeleted() {\n const ret = wasm.lorotext_isDeleted(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Subscribe to the changes of the text.\n *\n * The events will be emitted after a transaction is committed. A transaction is committed when:\n *\n * - `doc.commit()` is called.\n * - `doc.export(mode)` is called.\n * - `doc.import(data)` is called.\n * - `doc.checkout(version)` is called.\n *\n * returns a subscription callback, which can be used to unsubscribe.\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_subscribe(retptr, this.__wbg_ptr, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert the text to a string\n * @returns {string}\n */\n toString() {\n let deferred1_0;\n let deferred1_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_toString(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n deferred1_0 = r0;\n deferred1_1 = r1;\n return getStringFromWasm0(r0, r1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n }\n /**\n * Convert this attached container and all descendants to an independent tree.\n * Text format applies recursively. Does not commit; throws for detached\n * containers, unsupported types, invalid options, or nesting above 256.\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerNode}\n */\n toContainerTree(opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_toContainerTree(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst LoroTreeFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_lorotree_free(ptr >>> 0, 1));\n/**\n * The handler of a tree(forest) container.\n *\n * Learn more at https://loro.dev/docs/tutorial/tree\n */\nexport class LoroTree {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroTree.prototype);\n obj.__wbg_ptr = ptr;\n LoroTreeFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroTreeFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_lorotree_free(ptr, 0);\n }\n /**\n * Create a new tree node as the child of parent and return a `LoroTreeNode` instance.\n * If the parent is undefined, the tree node will be a root node.\n *\n * If the index is not provided, the new node will be appended to the end.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * const node = tree.createNode(undefined, 0);\n *\n * // undefined\n * // / \\\n * // node root\n * ```\n * @param {TreeID | undefined} parent\n * @param {number | null} [index]\n * @returns {LoroTreeNode}\n */\n createNode(parent, index) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_createNode(retptr, this.__wbg_ptr, addBorrowedObject(parent), isLikeNone(index) ? 0x100000001 : (index) >>> 0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroTreeNode.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Whether the container is attached to a document.\n *\n * If it's detached, the operations on the container will not be persisted.\n * @returns {boolean}\n */\n isAttached() {\n const ret = wasm.lorotree_isAttached(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the attached container associated with this.\n *\n * Returns an attached `Container` that equals to this or created by this, otherwise `undefined`.\n * @returns {LoroTree | undefined}\n */\n getAttached() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_getAttached(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get LoroTreeNode by the TreeID.\n * @param {TreeID} target\n * @returns {LoroTreeNode | undefined}\n */\n getNodeByID(target) {\n try {\n const ret = wasm.lorotree_getNodeByID(this.__wbg_ptr, addBorrowedObject(target));\n return ret === 0 ? undefined : LoroTreeNode.__wrap(ret);\n } finally {\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Return `None` if the node is not exist, otherwise return `Some(true)` if the node is deleted.\n * @param {TreeID} target\n * @returns {boolean}\n */\n isNodeDeleted(target) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_isNodeDeleted(retptr, this.__wbg_ptr, addBorrowedObject(target));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 !== 0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get the shallow value of the tree.\n *\n * Unlike `toJSON()` which recursively resolves nested containers to their values,\n * `getShallowValue()` returns container IDs as strings for any nested containers.\n *\n * @example\n * ```ts\n * const doc = new LoroDoc();\n * doc.setPeerId(\"1\");\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * root.data.set(\"name\", \"root\");\n * const text = root.data.setContainer(\"content\", new LoroText());\n * text.insert(0, \"Hello\");\n *\n * console.log(tree.getShallowValue());\n * // [{\n * // id: \"0@1\",\n * // parent: null,\n * // index: 0,\n * // fractional_index: \"80\",\n * // meta: \"cid:0@1:Map\",\n * // children: []\n * // }]\n *\n * console.log(tree.toJSON());\n * // [{\n * // id: \"0@1\",\n * // parent: null,\n * // index: 0,\n * // fractional_index: \"80\",\n * // meta: {\n * // name: \"root\",\n * // content: \"Hello\"\n * // },\n * // children: []\n * // }]\n * ```\n * @returns {TreeNodeShallowValue[]}\n */\n getShallowValue() {\n const ret = wasm.lorotree_getShallowValue(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the deep value of the tree with its container id.\n *\n * The result is a `{ cid, value }` object, where `cid` is the container id\n * string (the same as `tree.id`) and `value` is the deep value of the\n * tree (each node's `meta` is the deep value of its associated metadata\n * map). This is the same node shape that `LoroDoc.getDeepValueWithID()`\n * emits for every container.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * root.data.set(\"color\", \"red\");\n * console.log(tree.getDeepValueWithID());\n * // { cid: \"cid:root-tree:Tree\",\n * // value: [ { id: '0@1', parent: null, ..., meta: { color: 'red' }, children: [] } ] }\n * ```\n * @returns {any}\n */\n getDeepValueWithID() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_getDeepValueWithID(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Set whether to generate a fractional index for moving and creating.\n *\n * A fractional index can be used to determine the position of tree nodes among their siblings.\n *\n * The jitter is used to avoid conflicts when multiple users are creating a node at the same position.\n * A value of 0 is the default, which means no jitter; any value larger than 0 will enable jitter.\n *\n * Generally speaking, higher jitter value will increase the size of the operation\n * [Read more about it](https://www.loro.dev/blog/movable-tree#implementation-and-encoding-size)\n * @param {number} jitter\n */\n enableFractionalIndex(jitter) {\n wasm.lorotree_enableFractionalIndex(this.__wbg_ptr, jitter);\n }\n /**\n * Disable the fractional index generation when you don't need the Tree's siblings to be sorted.\n * The fractional index will always be set to the same default value 0.\n *\n * After calling this, you cannot use `tree.moveTo()`, `tree.moveBefore()`, `tree.moveAfter()`,\n * and `tree.createAt()`.\n */\n disableFractionalIndex() {\n wasm.lorotree_disableFractionalIndex(this.__wbg_ptr);\n }\n /**\n * Whether the tree enables the fractional index generation.\n * @returns {boolean}\n */\n isFractionalIndexEnabled() {\n const ret = wasm.lorotree_isFractionalIndexEnabled(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the id of the container.\n * @returns {ContainerID}\n */\n get id() {\n const ret = wasm.lorotree_id(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Move the target tree node to be a child of the parent.\n * It's not allowed that the target is an ancestor of the parent\n * or the target and the parent are the same node.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * const node = root.createNode();\n * const node2 = node.createNode();\n * tree.move(node2.id, root.id);\n * // Error will be thrown if move operation creates a cycle\n * // tree.move(root.id, node.id);\n * ```\n * @param {TreeID} target\n * @param {TreeID | undefined} parent\n * @param {number | null} [index]\n */\n move(target, parent, index) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_move(retptr, this.__wbg_ptr, addBorrowedObject(target), addBorrowedObject(parent), isLikeNone(index) ? 0x100000001 : (index) >>> 0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Create a new detached LoroTree (not attached to any LoroDoc).\n *\n * The edits on a detached container will not be persisted.\n * To attach the container to the document, please insert it into an attached container.\n */\n constructor() {\n const ret = wasm.lorotree_new();\n this.__wbg_ptr = ret >>> 0;\n LoroTreeFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * \"Tree\"\n * @returns {'Tree'}\n */\n kind() {\n const ret = wasm.lorotree_kind(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get all tree nodes of the forest, including deleted nodes.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * const node = root.createNode();\n * const node2 = node.createNode();\n * console.log(tree.nodes());\n * ```\n * @returns {LoroTreeNode[]}\n */\n nodes() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_nodes(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the root nodes of the forest.\n * @returns {LoroTreeNode[]}\n */\n roots() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_roots(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Delete a tree node from the forest.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * const node = root.createNode();\n * tree.delete(node.id);\n * ```\n * @param {TreeID} target\n */\n delete(target) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_delete(retptr, this.__wbg_ptr, addBorrowedObject(target));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get the parent container of the tree container.\n *\n * - The parent container of the root tree is `undefined`.\n * - The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n * @returns {Container | undefined}\n */\n parent() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_parent(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the hierarchy array with metadata of the forest.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * root.data.set(\"color\", \"red\");\n * // [ { id: '0@F2462C4159C4C8D1', parent: null, meta: { color: 'red' }, children: [] } ]\n * console.log(tree.toJSON());\n * ```\n * @returns {any}\n */\n toJSON() {\n const ret = wasm.lorotree_toJSON(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Return `true` if the tree contains the TreeID, include deleted node.\n * @param {TreeID} target\n * @returns {boolean}\n */\n has(target) {\n try {\n const ret = wasm.lorotree_has(this.__wbg_ptr, addBorrowedObject(target));\n return ret !== 0;\n } finally {\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get the hierarchy array of the forest.\n *\n * Note: the metadata will be not resolved. So if you don't only care about hierarchy\n * but also the metadata, you should use `toJson()`.\n * @returns {Array}\n */\n toArray() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_toArray(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the flat array of the forest. If `with_deleted` is true, the deleted nodes will be included.\n * @param {{ withDeleted: boolean }} options\n * @returns {Array}\n */\n getNodes(options) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_getNodes(retptr, this.__wbg_ptr, addHeapObject(options));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Check if the container is deleted\n * @returns {boolean}\n */\n isDeleted() {\n const ret = wasm.lorotree_isDeleted(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Subscribe to the changes of the tree.\n *\n * Returns a subscription callback, which can be used to unsubscribe.\n *\n * Trees have three types of events: `create`, `delete`, and `move`.\n * - `create`: Creates a new node with its `target` TreeID. If `parent` is undefined,\n * a root node is created; otherwise, a child node of `parent` is created.\n * If the node being created was previously deleted and has archived child nodes,\n * create events for these child nodes will also be received.\n * - `delete`: Deletes the target node. The structure and state of the target node and\n * its child nodes are archived, and delete events for the child nodes will not be received.\n * - `move`: Moves the target node. If `parent` is undefined, the target node becomes a root node;\n * otherwise, it becomes a child node of `parent`.\n *\n * If a tree container is subscribed, the event of metadata changes will also be received as a MapDiff.\n * And event's `path` will end with `TreeID`.\n *\n * The events will be emitted after a transaction is committed. A transaction is committed when:\n *\n * - `doc.commit()` is called.\n * - `doc.export(mode)` is called.\n * - `doc.import(data)` is called.\n * - `doc.checkout(version)` is called.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * tree.subscribe((event)=>{\n * // event.type: \"create\" | \"delete\" | \"move\"\n * });\n * const root = tree.createNode();\n * const node = root.createNode();\n * doc.commit();\n * ```\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_subscribe(retptr, this.__wbg_ptr, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert this attached container and all descendants to an independent tree.\n * Text format applies recursively. Does not commit; throws for detached\n * containers, unsupported types, invalid options, or nesting above 256.\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerNode}\n */\n toContainerTree(opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_toContainerTree(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst LoroTreeNodeFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_lorotreenode_free(ptr >>> 0, 1));\n/**\n * The handler of a tree node.\n */\nexport class LoroTreeNode {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroTreeNode.prototype);\n obj.__wbg_ptr = ptr;\n LoroTreeNodeFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroTreeNodeFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_lorotreenode_free(ptr, 0);\n }\n /**\n * @returns {string}\n */\n __getClassname() {\n let deferred1_0;\n let deferred1_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode___getClassname(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n deferred1_0 = r0;\n deferred1_1 = r1;\n return getStringFromWasm0(r0, r1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n }\n /**\n * Get the creation id of this node.\n * @returns {{ peer: PeerID, counter: number }}\n */\n creationId() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_creationId(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Check if the node is deleted.\n * @returns {boolean}\n */\n isDeleted() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_isDeleted(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 !== 0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Move the tree node to be before the target node.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * const node = root.createNode();\n * const node2 = root.createNode();\n * node2.moveBefore(node);\n * // root\n * // / \\\n * // node2 node\n * ```\n * @param {LoroTreeNode} target\n */\n moveBefore(target) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n _assertClass(target, LoroTreeNode);\n wasm.lorotreenode_moveBefore(retptr, this.__wbg_ptr, target.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Create a new node as the child of the current node and\n * return an instance of `LoroTreeNode`.\n *\n * If the index is not provided, the new node will be appended to the end.\n *\n * @example\n * ```typescript\n * import { LoroDoc } from \"loro-crdt\";\n *\n * let doc = new LoroDoc();\n * let tree = doc.getTree(\"tree\");\n * let root = tree.createNode();\n * let node = root.createNode();\n * let node2 = root.createNode(0);\n * // root\n * // / \\\n * // node2 node\n * ```\n * @param {number | null} [index]\n * @returns {LoroTreeNode}\n */\n createNode(index) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_createNode(retptr, this.__wbg_ptr, isLikeNone(index) ? 0x100000001 : (index) >>> 0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroTreeNode.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the last mover of this node.\n * @returns {{ peer: PeerID, counter: number } | undefined}\n */\n getLastMoveId() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_getLastMoveId(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @returns {any}\n */\n toJSON() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_toJSON(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the `Fractional Index` of the node.\n *\n * Note: the tree container must be attached to the document.\n * @returns {string | undefined}\n */\n fractionalIndex() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_fractionalIndex(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * The TreeID of the node.\n * @returns {TreeID}\n */\n get id() {\n const ret = wasm.lorotreenode_id(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * @param {LoroTreeNode | undefined} parent\n * @param {number | null} [index]\n */\n move(parent, index) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_move(retptr, this.__wbg_ptr, addBorrowedObject(parent), isLikeNone(index) ? 0x100000001 : (index) >>> 0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get the associated metadata map container of a tree node.\n * @returns {LoroMap}\n */\n get data() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_data(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroMap.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the index of the node in the parent's children.\n * @returns {number | undefined}\n */\n index() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_index(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getFloat64(retptr + 8 * 0, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n return r0 === 0x100000001 ? undefined : r0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @returns {LoroTreeNode | undefined}\n */\n parent() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_parent(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 === 0 ? undefined : LoroTreeNode.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the creator of this node.\n * @returns {PeerID}\n */\n creator() {\n const ret = wasm.lorotreenode_creator(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the children of this node.\n *\n * The objects returned are new js objects each time because they need to cross\n * the WASM boundary.\n * @returns {any}\n */\n children() {\n const ret = wasm.lorotreenode_children(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Move the tree node to be after the target node.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * const node = root.createNode();\n * const node2 = root.createNode();\n * node2.moveAfter(node);\n * // root\n * // / \\\n * // node node2\n * ```\n * @param {LoroTreeNode} target\n */\n moveAfter(target) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n _assertClass(target, LoroTreeNode);\n wasm.lorotreenode_moveAfter(retptr, this.__wbg_ptr, target.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst UndoManagerFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_undomanager_free(ptr >>> 0, 1));\n/**\n * `UndoManager` is responsible for handling undo and redo operations.\n *\n * By default, the maxUndoSteps is set to 100, mergeInterval is set to 1000 ms.\n *\n * Each commit made by the current peer is recorded as an undo step in the `UndoManager`.\n * Undo steps can be merged if they occur within a specified merge interval.\n *\n * Note that undo operations are local and cannot revert changes made by other peers.\n * To undo changes made by other peers, consider using the time travel feature.\n *\n * Once the `peerId` is bound to the `UndoManager` in the document, it cannot be changed.\n * Otherwise, the `UndoManager` may not function correctly.\n */\nexport class UndoManager {\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n UndoManagerFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_undomanager_free(ptr, 0);\n }\n groupStart() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.undomanager_groupStart(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the value associated with the top redo stack item, if any.\n * Returns `undefined` if there is no redo item.\n * @returns {Value | undefined}\n */\n topRedoValue() {\n const ret = wasm.undomanager_topRedoValue(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the value associated with the top undo stack item, if any.\n * Returns `undefined` if there is no undo item.\n * @returns {Value | undefined}\n */\n topUndoValue() {\n const ret = wasm.undomanager_topUndoValue(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * The number of max undo steps.\n * If the number of undo steps exceeds this number, the oldest undo step will be removed.\n * @param {number} steps\n */\n setMaxUndoSteps(steps) {\n wasm.undomanager_setMaxUndoSteps(this.__wbg_ptr, steps);\n }\n /**\n * Set the merge interval (in ms).\n *\n * If the interval is set to 0, the undo steps will not be merged.\n * Otherwise, the undo steps will be merged if the interval between the two steps is less than the given interval.\n * @param {number} interval\n */\n setMergeInterval(interval) {\n wasm.undomanager_setMergeInterval(this.__wbg_ptr, interval);\n }\n /**\n * If a local event's origin matches the given prefix, it will not be recorded in the\n * undo stack.\n * @param {string} prefix\n */\n addExcludeOriginPrefix(prefix) {\n const ptr0 = passStringToWasm0(prefix, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.undomanager_addExcludeOriginPrefix(this.__wbg_ptr, ptr0, len0);\n }\n /**\n * `UndoManager` is responsible for handling undo and redo operations.\n *\n * PeerID cannot be changed during the lifetime of the UndoManager.\n *\n * Note that undo operations are local and cannot revert changes made by other peers.\n * To undo changes made by other peers, consider using the time travel feature.\n *\n * Each commit made by the current peer is recorded as an undo step in the `UndoManager`.\n * Undo steps can be merged if they occur within a specified merge interval.\n *\n * ## Config\n *\n * - `mergeInterval`: Optional. The interval in milliseconds within which undo steps can be merged. Default is 1000 ms.\n * - `maxUndoSteps`: Optional. The maximum number of undo steps to retain. Default is 100.\n * - `excludeOriginPrefixes`: Optional. An array of string prefixes. Events with origins matching these prefixes will be excluded from undo steps.\n * - `onPush`: Optional. A callback function that is called when an undo/redo step is pushed.\n * The function can return a meta data value that will be attached to the given stack item.\n * - `onPop`: Optional. A callback function that is called when an undo/redo step is popped.\n * The function will have a meta data value that was attached to the given stack item when\n * `onPush` was called.\n * @param {LoroDoc} doc\n * @param {UndoConfig} config\n */\n constructor(doc, config) {\n _assertClass(doc, LoroDoc);\n const ret = wasm.undomanager_new(doc.__wbg_ptr, addHeapObject(config));\n this.__wbg_ptr = ret >>> 0;\n UndoManagerFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * Get the peer id of the undo manager.\n * @returns {PeerID}\n */\n peer() {\n const ret = wasm.undomanager_peer(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Redo the last undone operation.\n *\n * Consumes at most one history item, including a no-op. Returns whether\n * local operations were generated. A false result does not imply that the\n * redo stack is empty; use `canRedo()` to check for remaining history.\n *\n * Throws like `undo` on steps that would recreate a container of an\n * unknown type.\n * @returns {boolean}\n */\n redo() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.undomanager_redo(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 !== 0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Undo the last operation.\n *\n * Consumes at most one history item, as defined by grouping and the merge\n * interval. Returns whether local operations were generated. A no-op item\n * is consumed and returns false without undoing earlier items. Use\n * `canUndo()` to check whether history remains.\n *\n * Throws without changing the doc if the step would have to recreate a\n * container of a type unknown to this version (created by a newer\n * loro-crdt). That step, with every edit merged into it, is dropped and its\n * edits stay; the next call undoes the step before it, rebased over the\n * dropped step's edits like over a remote peer's.\n * @returns {boolean}\n */\n undo() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.undomanager_undo(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 !== 0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n clear() {\n wasm.undomanager_clear(this.__wbg_ptr);\n }\n /**\n * Pause the UndoManager so that local edits and checkout events are ignored.\n *\n * While paused, local edits are not recorded as undo steps and checkout\n * events do not clear the stacks. Import events (remote changes) are still\n * processed so that the stacks remain correctly transformed against\n * concurrent edits.\n *\n * Use this before temporary checkouts (e.g. read-only history preview) that\n * should not disturb undo/redo history. Close any open group before pausing.\n *\n * Call `resume()` after returning the document to its original state.\n */\n pause() {\n wasm.undomanager_pause(this.__wbg_ptr);\n }\n /**\n * Resume the UndoManager after a `pause()`.\n */\n resume() {\n wasm.undomanager_resume(this.__wbg_ptr);\n }\n /**\n * Can redo the last operation.\n * @returns {boolean}\n */\n canRedo() {\n const ret = wasm.undomanager_canRedo(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Can undo the last operation.\n * @returns {boolean}\n */\n canUndo() {\n const ret = wasm.undomanager_canUndo(this.__wbg_ptr);\n return ret !== 0;\n }\n groupEnd() {\n wasm.undomanager_groupEnd(this.__wbg_ptr);\n }\n /**\n * Returns whether the UndoManager is currently paused.\n * @returns {boolean}\n */\n isPaused() {\n const ret = wasm.undomanager_isPaused(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Set the on pop event listener.\n *\n * Every time an undo step or redo step is popped, the on pop event listener will be called.\n * @param {any} on_pop\n */\n setOnPop(on_pop) {\n wasm.undomanager_setOnPop(this.__wbg_ptr, addHeapObject(on_pop));\n }\n /**\n * Clear only the redo stack, preserving the undo stack.\n *\n * This is useful when coordinating undo/redo across multiple participants\n * (e.g., multiple editors) where a new edit in one participant should\n * invalidate redo in all other participants.\n */\n clearRedo() {\n wasm.undomanager_clearRedo(this.__wbg_ptr);\n }\n /**\n * Clear only the undo stack, preserving the redo stack.\n */\n clearUndo() {\n wasm.undomanager_clearUndo(this.__wbg_ptr);\n }\n /**\n * Set the on push event listener.\n *\n * Every time an undo step or redo step is pushed, the on push event listener will be called.\n * @param {any} on_push\n */\n setOnPush(on_push) {\n wasm.undomanager_setOnPush(this.__wbg_ptr, addHeapObject(on_push));\n }\n}\n\nconst VersionVectorFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_versionvector_free(ptr >>> 0, 1));\n/**\n * [VersionVector](https://en.wikipedia.org/wiki/Version_vector)\n * is a map from [PeerID] to [Counter]. Its a right-open interval.\n *\n * i.e. a [VersionVector] of `{A: 1, B: 2}` means that A has 1 atomic op and B has 2 atomic ops,\n * thus ID of `{client: A, counter: 1}` is out of the range.\n */\nexport class VersionVector {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(VersionVector.prototype);\n obj.__wbg_ptr = ptr;\n VersionVectorFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n VersionVectorFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_versionvector_free(ptr, 0);\n }\n /**\n * Get the counter of a peer.\n * @param {number | bigint | `${number}`} peer_id\n * @returns {number | undefined}\n */\n get(peer_id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.versionvector_get(retptr, this.__wbg_ptr, addHeapObject(peer_id));\n var r0 = getDataViewMemory0().getFloat64(retptr + 8 * 0, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n return r0 === 0x100000001 ? undefined : r0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Create a new version vector.\n * @param {Map | Uint8Array | VersionVector | undefined | null} value\n */\n constructor(value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.versionvector_new(retptr, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n this.__wbg_ptr = r0 >>> 0;\n VersionVectorFinalization.register(this, this.__wbg_ptr, this);\n return this;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Decode the version vector from a Uint8Array.\n * @param {Uint8Array} bytes\n * @returns {VersionVector}\n */\n static decode(bytes) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.versionvector_decode(retptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return VersionVector.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Encode the version vector into a Uint8Array.\n * @returns {Uint8Array}\n */\n encode() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.versionvector_encode(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @returns {number}\n */\n length() {\n const ret = wasm.versionvector_length(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * @param {PeerID} peer\n */\n remove(peer) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.versionvector_remove(retptr, this.__wbg_ptr, addHeapObject(peer));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * set the exclusive ending point. target id will NOT be included by self\n * @param {{ peer: PeerID, counter: number }} id\n */\n setEnd(id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.versionvector_setEnd(retptr, this.__wbg_ptr, addHeapObject(id));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Compare the version vector with another version vector.\n *\n * If they are concurrent, return undefined.\n * @param {VersionVector} other\n * @returns {number | undefined}\n */\n compare(other) {\n _assertClass(other, VersionVector);\n const ret = wasm.versionvector_compare(this.__wbg_ptr, other.__wbg_ptr);\n return ret === 0x100000001 ? undefined : ret;\n }\n /**\n * set the inclusive ending point. target id will be included\n * @param {{ peer: PeerID, counter: number }} id\n */\n setLast(id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.versionvector_setLast(retptr, this.__wbg_ptr, addHeapObject(id));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert the version vector to a Map\n * @returns {Map}\n */\n toJSON() {\n const ret = wasm.versionvector_toJSON(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Create a new version vector from a Map.\n * @param {Map} version\n * @returns {VersionVector}\n */\n static parseJSON(version) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.versionvector_parseJSON(retptr, addHeapObject(version));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return VersionVector.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nasync function __wbg_load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n\n } catch (e) {\n if (module.headers.get('Content-Type') != 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else {\n throw e;\n }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n\n } else {\n return instance;\n }\n }\n}\n\nfunction __wbg_get_imports() {\n const imports = {};\n imports.wbg = {};\n imports.wbg.__wbg_String_8f0eb39a4a4c2f66 = function(arg0, arg1) {\n const ret = String(getObject(arg1));\n const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len1 = WASM_VECTOR_LEN;\n getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);\n };\n imports.wbg.__wbg_apply_36be6a55257c99bf = function() { return handleError(function (arg0, arg1, arg2) {\n const ret = getObject(arg0).apply(getObject(arg1), getObject(arg2));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_apply_eb9e9b97497f91e4 = function() { return handleError(function (arg0, arg1, arg2) {\n const ret = Reflect.apply(getObject(arg0), getObject(arg1), getObject(arg2));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_buffer_609cc3eee51ed158 = function(arg0) {\n const ret = getObject(arg0).buffer;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_call_672a4d21634d4a24 = function() { return handleError(function (arg0, arg1) {\n const ret = getObject(arg0).call(getObject(arg1));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_call_7cccdd69e0791ae2 = function() { return handleError(function (arg0, arg1, arg2) {\n const ret = getObject(arg0).call(getObject(arg1), getObject(arg2));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_call_833bed5770ea2041 = function() { return handleError(function (arg0, arg1, arg2, arg3) {\n const ret = getObject(arg0).call(getObject(arg1), getObject(arg2), getObject(arg3));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_call_b8adc8b1d0a0d8eb = function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) {\n const ret = getObject(arg0).call(getObject(arg1), getObject(arg2), getObject(arg3), getObject(arg4));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_changemodifier_new = function(arg0) {\n const ret = ChangeModifier.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_crypto_574e78ad8b13b65f = function(arg0) {\n const ret = getObject(arg0).crypto;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_cursor_new = function(arg0) {\n const ret = Cursor.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_done_769e5ede4b31c67b = function(arg0) {\n const ret = getObject(arg0).done;\n return ret;\n };\n imports.wbg.__wbg_entries_3265d4158b33e5dc = function(arg0) {\n const ret = Object.entries(getObject(arg0));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_entries_c8a90a7ed73e84ce = function(arg0) {\n const ret = getObject(arg0).entries();\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_error_428bae4e36b351e3 = function(arg0, arg1) {\n console.error(getStringFromWasm0(arg0, arg1));\n };\n imports.wbg.__wbg_from_2a5d3e218e67aa85 = function(arg0) {\n const ret = Array.from(getObject(arg0));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_getOwnPropertySymbols_97eebed6fe6e08be = function(arg0) {\n const ret = Object.getOwnPropertySymbols(getObject(arg0));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_getRandomValues_b8f5dbd5f3995a9e = function() { return handleError(function (arg0, arg1) {\n getObject(arg0).getRandomValues(getObject(arg1));\n }, arguments) };\n imports.wbg.__wbg_get_67b2ba62fc30de12 = function() { return handleError(function (arg0, arg1) {\n const ret = Reflect.get(getObject(arg0), getObject(arg1));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_get_b9b93047fe3cf45b = function(arg0, arg1) {\n const ret = getObject(arg0)[arg1 >>> 0];\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_getindex_5b00c274b05714aa = function(arg0, arg1) {\n const ret = getObject(arg0)[arg1 >>> 0];\n return ret;\n };\n imports.wbg.__wbg_getwithrefkey_1dc361bd10053bfe = function(arg0, arg1) {\n const ret = getObject(arg0)[getObject(arg1)];\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_instanceof_ArrayBuffer_e14585432e3737fc = function(arg0) {\n let result;\n try {\n result = getObject(arg0) instanceof ArrayBuffer;\n } catch (_) {\n result = false;\n }\n const ret = result;\n return ret;\n };\n imports.wbg.__wbg_instanceof_Map_f3469ce2244d2430 = function(arg0) {\n let result;\n try {\n result = getObject(arg0) instanceof Map;\n } catch (_) {\n result = false;\n }\n const ret = result;\n return ret;\n };\n imports.wbg.__wbg_instanceof_Object_7f2dcef8f78644a4 = function(arg0) {\n let result;\n try {\n result = getObject(arg0) instanceof Object;\n } catch (_) {\n result = false;\n }\n const ret = result;\n return ret;\n };\n imports.wbg.__wbg_instanceof_Uint8Array_17156bcf118086a9 = function(arg0) {\n let result;\n try {\n result = getObject(arg0) instanceof Uint8Array;\n } catch (_) {\n result = false;\n }\n const ret = result;\n return ret;\n };\n imports.wbg.__wbg_isArray_a1eab7e0d067391b = function(arg0) {\n const ret = Array.isArray(getObject(arg0));\n return ret;\n };\n imports.wbg.__wbg_isSafeInteger_343e2beeeece1bb0 = function(arg0) {\n const ret = Number.isSafeInteger(getObject(arg0));\n return ret;\n };\n imports.wbg.__wbg_iterator_9a24c88df860dc65 = function() {\n const ret = Symbol.iterator;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_length_a446193dc22c12f8 = function(arg0) {\n const ret = getObject(arg0).length;\n return ret;\n };\n imports.wbg.__wbg_length_e2d2a49132c1b256 = function(arg0) {\n const ret = getObject(arg0).length;\n return ret;\n };\n imports.wbg.__wbg_log_0cc1b7768397bcfe = function(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {\n let deferred0_0;\n let deferred0_1;\n try {\n deferred0_0 = arg0;\n deferred0_1 = arg1;\n console.log(getStringFromWasm0(arg0, arg1), getStringFromWasm0(arg2, arg3), getStringFromWasm0(arg4, arg5), getStringFromWasm0(arg6, arg7));\n } finally {\n wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);\n }\n };\n imports.wbg.__wbg_log_882f657276590a29 = function(arg0, arg1) {\n console.log(getStringFromWasm0(arg0, arg1));\n };\n imports.wbg.__wbg_log_cb9e190acc5753fb = function(arg0, arg1) {\n let deferred0_0;\n let deferred0_1;\n try {\n deferred0_0 = arg0;\n deferred0_1 = arg1;\n console.log(getStringFromWasm0(arg0, arg1));\n } finally {\n wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);\n }\n };\n imports.wbg.__wbg_lorocounter_new = function(arg0) {\n const ret = LoroCounter.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_lorolist_new = function(arg0) {\n const ret = LoroList.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_loromap_new = function(arg0) {\n const ret = LoroMap.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_loromovablelist_new = function(arg0) {\n const ret = LoroMovableList.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_lorotext_new = function(arg0) {\n const ret = LoroText.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_lorotree_new = function(arg0) {\n const ret = LoroTree.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_lorotreenode_new = function(arg0) {\n const ret = LoroTreeNode.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_mark_7438147ce31e9d4b = function(arg0, arg1) {\n performance.mark(getStringFromWasm0(arg0, arg1));\n };\n imports.wbg.__wbg_measure_fb7825c11612c823 = function() { return handleError(function (arg0, arg1, arg2, arg3) {\n let deferred0_0;\n let deferred0_1;\n let deferred1_0;\n let deferred1_1;\n try {\n deferred0_0 = arg0;\n deferred0_1 = arg1;\n deferred1_0 = arg2;\n deferred1_1 = arg3;\n performance.measure(getStringFromWasm0(arg0, arg1), getStringFromWasm0(arg2, arg3));\n } finally {\n wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n }, arguments) };\n imports.wbg.__wbg_msCrypto_a61aeb35a24c1329 = function(arg0) {\n const ret = getObject(arg0).msCrypto;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_new_405e22f390576ce2 = function() {\n const ret = new Object();\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_new_5e0be73521bc8c17 = function() {\n const ret = new Map();\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_new_78feb108b6472713 = function() {\n const ret = new Array();\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_new_a12002a7f91c75be = function(arg0) {\n const ret = new Uint8Array(getObject(arg0));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_new_c68d7209be747379 = function(arg0, arg1) {\n const ret = new Error(getStringFromWasm0(arg0, arg1));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_newnoargs_105ed471475aaf50 = function(arg0, arg1) {\n const ret = new Function(getStringFromWasm0(arg0, arg1));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_newwithbyteoffsetandlength_d97e637ebe145a9a = function(arg0, arg1, arg2) {\n const ret = new Uint8Array(getObject(arg0), arg1 >>> 0, arg2 >>> 0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_newwithlength_a381634e90c276d4 = function(arg0) {\n const ret = new Uint8Array(arg0 >>> 0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_newwithlength_c4c419ef0bc8a1f8 = function(arg0) {\n const ret = new Array(arg0 >>> 0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_next_25feadfc0913fea9 = function(arg0) {\n const ret = getObject(arg0).next;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_next_6574e1a8a62d1055 = function() { return handleError(function (arg0) {\n const ret = getObject(arg0).next();\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_node_905d3e251edff8a2 = function(arg0) {\n const ret = getObject(arg0).node;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_now_2b509d5c9d429404 = function() {\n const ret = Date.now();\n return ret;\n };\n imports.wbg.__wbg_ownKeys_3930041068756f1f = function() { return handleError(function (arg0) {\n const ret = Reflect.ownKeys(getObject(arg0));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_process_dc0fbacc7c1c06f7 = function(arg0) {\n const ret = getObject(arg0).process;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_push_737cfc8c1432c2c6 = function(arg0, arg1) {\n const ret = getObject(arg0).push(getObject(arg1));\n return ret;\n };\n imports.wbg.__wbg_randomFillSync_ac0988aba3254290 = function() { return handleError(function (arg0, arg1) {\n getObject(arg0).randomFillSync(takeObject(arg1));\n }, arguments) };\n imports.wbg.__wbg_require_60cc747a6bc5215a = function() { return handleError(function () {\n const ret = module.require;\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_resolve_4851785c9c5f573d = function(arg0) {\n const ret = Promise.resolve(getObject(arg0));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_set_37837023f3d740e8 = function(arg0, arg1, arg2) {\n getObject(arg0)[arg1 >>> 0] = takeObject(arg2);\n };\n imports.wbg.__wbg_set_3f1d0b984ed272ed = function(arg0, arg1, arg2) {\n getObject(arg0)[takeObject(arg1)] = takeObject(arg2);\n };\n imports.wbg.__wbg_set_65595bdd868b3009 = function(arg0, arg1, arg2) {\n getObject(arg0).set(getObject(arg1), arg2 >>> 0);\n };\n imports.wbg.__wbg_set_8fc6bf8a5b1071d1 = function(arg0, arg1, arg2) {\n const ret = getObject(arg0).set(getObject(arg1), getObject(arg2));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_set_bb8cecf6a62b9f46 = function() { return handleError(function (arg0, arg1, arg2) {\n const ret = Reflect.set(getObject(arg0), getObject(arg1), getObject(arg2));\n return ret;\n }, arguments) };\n imports.wbg.__wbg_stateBinary_bcc49261f5205b9f = function(arg0, arg1) {\n const ret = stateBinary(getArrayU8FromWasm0(arg0, arg1));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_stateCid_ddf7fe40691e2c8f = function(arg0, arg1, arg2) {\n const ret = stateCid(getObject(arg0), arg1, arg2);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_stateContainer_8b73508686ecac7f = function(arg0, arg1, arg2) {\n const ret = stateContainer(arg0, getObject(arg1), takeObject(arg2));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_stateIndex_985e23155ddc5679 = function() { return handleError(function (arg0, arg1, arg2) {\n stateIndex(getObject(arg0), arg1 >>> 0, getObject(arg2));\n }, arguments) };\n imports.wbg.__wbg_stateOptions_234376ac96321e68 = function() { return handleError(function (arg0, arg1) {\n const ret = stateOptions(takeObject(arg0), arg1 !== 0);\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_stateRootCid_92a320b321ddff0a = function(arg0, arg1, arg2) {\n const ret = stateRootCid(getStringFromWasm0(arg0, arg1), arg2);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_stateSet_9c75457bd566f749 = function() { return handleError(function (arg0, arg1, arg2) {\n stateSet(getObject(arg0), getObject(arg1), getObject(arg2));\n }, arguments) };\n imports.wbg.__wbg_stateSlice_4573448d6dfd609f = function(arg0, arg1, arg2) {\n const ret = stateSlice(takeObject(arg0), arg1 >>> 0, arg2 >>> 0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_stateValue_32a9721f28b53795 = function(arg0) {\n const ret = stateValue(takeObject(arg0));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_static_accessor_GLOBAL_88a902d13a557d07 = function() {\n const ret = typeof global === 'undefined' ? null : global;\n return isLikeNone(ret) ? 0 : addHeapObject(ret);\n };\n imports.wbg.__wbg_static_accessor_GLOBAL_THIS_56578be7e9f832b0 = function() {\n const ret = typeof globalThis === 'undefined' ? null : globalThis;\n return isLikeNone(ret) ? 0 : addHeapObject(ret);\n };\n imports.wbg.__wbg_static_accessor_SELF_37c5d418e4bf5819 = function() {\n const ret = typeof self === 'undefined' ? null : self;\n return isLikeNone(ret) ? 0 : addHeapObject(ret);\n };\n imports.wbg.__wbg_static_accessor_WINDOW_5de37043a91a9c40 = function() {\n const ret = typeof window === 'undefined' ? null : window;\n return isLikeNone(ret) ? 0 : addHeapObject(ret);\n };\n imports.wbg.__wbg_subarray_aa9065fa9dc5df96 = function(arg0, arg1, arg2) {\n const ret = getObject(arg0).subarray(arg1 >>> 0, arg2 >>> 0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_then_44b73946d2fb3e7d = function(arg0, arg1) {\n const ret = getObject(arg0).then(getObject(arg1));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_value_cd1ffa7b1ab794f1 = function(arg0) {\n const ret = getObject(arg0).value;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_versions_c01dfd4722a88165 = function(arg0) {\n const ret = getObject(arg0).versions;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_versionvector_new = function(arg0) {\n const ret = VersionVector.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_warn_5d1fd3858772ca54 = function(arg0, arg1) {\n console.warn(getStringFromWasm0(arg0, arg1));\n };\n imports.wbg.__wbindgen_as_number = function(arg0) {\n const ret = +getObject(arg0);\n return ret;\n };\n imports.wbg.__wbindgen_bigint_from_i64 = function(arg0) {\n const ret = arg0;\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_bigint_from_u64 = function(arg0) {\n const ret = BigInt.asUintN(64, arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_bigint_get_as_i64 = function(arg0, arg1) {\n const v = getObject(arg1);\n const ret = typeof(v) === 'bigint' ? v : undefined;\n getDataViewMemory0().setBigInt64(arg0 + 8 * 1, isLikeNone(ret) ? BigInt(0) : ret, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);\n };\n imports.wbg.__wbindgen_boolean_get = function(arg0) {\n const v = getObject(arg0);\n const ret = typeof(v) === 'boolean' ? (v ? 1 : 0) : 2;\n return ret;\n };\n imports.wbg.__wbindgen_cb_drop = function(arg0) {\n const obj = takeObject(arg0).original;\n if (obj.cnt-- == 1) {\n obj.a = 0;\n return true;\n }\n const ret = false;\n return ret;\n };\n imports.wbg.__wbindgen_closure_wrapper295 = function(arg0, arg1, arg2) {\n const ret = makeMutClosure(arg0, arg1, 16, __wbg_adapter_58);\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_closure_wrapper551 = function(arg0, arg1, arg2) {\n const ret = makeMutClosure(arg0, arg1, 16, __wbg_adapter_61);\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_debug_string = function(arg0, arg1) {\n const ret = debugString(getObject(arg1));\n const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len1 = WASM_VECTOR_LEN;\n getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);\n };\n imports.wbg.__wbindgen_error_new = function(arg0, arg1) {\n const ret = new Error(getStringFromWasm0(arg0, arg1));\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_in = function(arg0, arg1) {\n const ret = getObject(arg0) in getObject(arg1);\n return ret;\n };\n imports.wbg.__wbindgen_is_array = function(arg0) {\n const ret = Array.isArray(getObject(arg0));\n return ret;\n };\n imports.wbg.__wbindgen_is_bigint = function(arg0) {\n const ret = typeof(getObject(arg0)) === 'bigint';\n return ret;\n };\n imports.wbg.__wbindgen_is_function = function(arg0) {\n const ret = typeof(getObject(arg0)) === 'function';\n return ret;\n };\n imports.wbg.__wbindgen_is_null = function(arg0) {\n const ret = getObject(arg0) === null;\n return ret;\n };\n imports.wbg.__wbindgen_is_object = function(arg0) {\n const val = getObject(arg0);\n const ret = typeof(val) === 'object' && val !== null;\n return ret;\n };\n imports.wbg.__wbindgen_is_string = function(arg0) {\n const ret = typeof(getObject(arg0)) === 'string';\n return ret;\n };\n imports.wbg.__wbindgen_is_undefined = function(arg0) {\n const ret = getObject(arg0) === undefined;\n return ret;\n };\n imports.wbg.__wbindgen_jsval_eq = function(arg0, arg1) {\n const ret = getObject(arg0) === getObject(arg1);\n return ret;\n };\n imports.wbg.__wbindgen_jsval_loose_eq = function(arg0, arg1) {\n const ret = getObject(arg0) == getObject(arg1);\n return ret;\n };\n imports.wbg.__wbindgen_memory = function() {\n const ret = wasm.memory;\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_number_get = function(arg0, arg1) {\n const obj = getObject(arg1);\n const ret = typeof(obj) === 'number' ? obj : undefined;\n getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);\n };\n imports.wbg.__wbindgen_number_new = function(arg0) {\n const ret = arg0;\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_object_clone_ref = function(arg0) {\n const ret = getObject(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_object_drop_ref = function(arg0) {\n takeObject(arg0);\n };\n imports.wbg.__wbindgen_rethrow = function(arg0) {\n throw takeObject(arg0);\n };\n imports.wbg.__wbindgen_string_get = function(arg0, arg1) {\n const obj = getObject(arg1);\n const ret = typeof(obj) === 'string' ? obj : undefined;\n var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n var len1 = WASM_VECTOR_LEN;\n getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);\n };\n imports.wbg.__wbindgen_string_new = function(arg0, arg1) {\n const ret = getStringFromWasm0(arg0, arg1);\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_throw = function(arg0, arg1) {\n throw new Error(getStringFromWasm0(arg0, arg1));\n };\n imports.wbg.__wbindgen_typeof = function(arg0) {\n const ret = typeof getObject(arg0);\n return addHeapObject(ret);\n };\n\n return imports;\n}\n\nfunction __wbg_init_memory(imports, memory) {\n\n}\n\nfunction __wbg_finalize_init(instance, module) {\n wasm = instance.exports;\n __wbg_init.__wbindgen_wasm_module = module;\n cachedDataViewMemory0 = null;\n cachedUint8ArrayMemory0 = null;\n\n\n wasm.__wbindgen_start();\n return wasm;\n}\n\nfunction initSync(module) {\n if (wasm !== undefined) return wasm;\n\n\n if (typeof module !== 'undefined') {\n if (Object.getPrototypeOf(module) === Object.prototype) {\n ({module} = module)\n } else {\n console.warn('using deprecated parameters for `initSync()`; pass a single object instead')\n }\n }\n\n const imports = __wbg_get_imports();\n\n __wbg_init_memory(imports);\n\n if (!(module instanceof WebAssembly.Module)) {\n module = new WebAssembly.Module(module);\n }\n\n const instance = new WebAssembly.Instance(module, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nasync function __wbg_init(module_or_path) {\n if (wasm !== undefined) return wasm;\n\n\n if (typeof module_or_path !== 'undefined') {\n if (Object.getPrototypeOf(module_or_path) === Object.prototype) {\n ({module_or_path} = module_or_path)\n } else {\n console.warn('using deprecated parameters for the initialization function; pass a single object instead')\n }\n }\n\n if (typeof module_or_path === 'undefined') {\n module_or_path = new URL('loro_wasm_bg.wasm', import.meta.url);\n }\n const imports = __wbg_get_imports();\n\n if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {\n module_or_path = fetch(module_or_path);\n }\n\n __wbg_init_memory(imports);\n\n const { instance, module } = await __wbg_load(await module_or_path, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nexport { initSync };\nexport default __wbg_init;\n\n// A container handler never changes identity during one JS wrapper's lifetime.\n// Attaching a detached handler returns a different wrapper, and getAttached()\n// also returns a new wrapper. Cache on the wrapper, not by container id.\nconst __loroContainerIdCache = Symbol(\"loroContainerId\");\n\nfunction __loroCacheContainerIdGetter(ContainerClass) {\n const prototype = ContainerClass.prototype;\n const idDescriptor = Object.getOwnPropertyDescriptor(prototype, \"id\");\n const getId = idDescriptor && idDescriptor.get;\n const destroyDescriptor = Object.getOwnPropertyDescriptor(\n prototype,\n \"__destroy_into_raw\",\n );\n const destroy = destroyDescriptor && destroyDescriptor.value;\n\n if (!getId || !destroyDescriptor || !destroy) {\n throw new Error(\"Unexpected wasm-bindgen container wrapper shape\");\n }\n\n Object.defineProperty(prototype, \"id\", {\n ...idDescriptor,\n get() {\n // Preserve wasm-bindgen's post-free error instead of returning stale data.\n if (this.__wbg_ptr === 0) {\n return getId.call(this);\n }\n\n const cached = this[__loroContainerIdCache];\n if (cached !== undefined) {\n return cached;\n }\n\n const id = getId.call(this);\n try {\n Object.defineProperty(this, __loroContainerIdCache, {\n configurable: true,\n value: id,\n });\n } catch {\n // Caching must not make a non-extensible wrapper's id unreadable.\n }\n return id;\n },\n });\n\n Object.defineProperty(prototype, \"__destroy_into_raw\", {\n ...destroyDescriptor,\n value() {\n try {\n delete this[__loroContainerIdCache];\n } catch {\n // Cache cleanup must not replace wasm-bindgen's free behavior.\n }\n return destroy.call(this);\n },\n });\n}\n\n// `kind()` returns a constant string per container class and never depends on\n// instance state, so one module-level memo per class is enough. Repeated reads\n// (e.g. loro-mirror's traversal) must not cross into WASM again.\nfunction __loroCacheKindMethod(ContainerClass) {\n const prototype = ContainerClass.prototype;\n const kindDescriptor = Object.getOwnPropertyDescriptor(prototype, \"kind\");\n const kind = kindDescriptor && kindDescriptor.value;\n\n if (typeof kind !== \"function\") {\n throw new Error(\"Unexpected wasm-bindgen container wrapper shape\");\n }\n\n let cached;\n Object.defineProperty(prototype, \"kind\", {\n ...kindDescriptor,\n value() {\n // Preserve wasm-bindgen's post-free error instead of returning stale data.\n if (this.__wbg_ptr === 0) {\n return kind.call(this);\n }\n\n if (cached === undefined) {\n cached = kind.call(this);\n }\n return cached;\n },\n });\n}\n\nfor (const ContainerClass of [\n LoroMap,\n LoroText,\n LoroList,\n LoroTree,\n LoroMovableList,\n LoroCounter,\n]) {\n __loroCacheContainerIdGetter(ContainerClass);\n __loroCacheKindMethod(ContainerClass);\n}\n", + "export { default } from \"./loro_wasm.js\";\nimport { LoroDoc, EphemeralStoreWasm, UndoManager, isValidContainerId, AwarenessWasm, callPendingEvents } from \"./loro_wasm.js\";\nexport * from \"./loro_wasm.js\";\n\n/**\n * @deprecated Please use LoroDoc\n */\nclass Loro extends LoroDoc {\n}\nconst CONTAINER_TYPES = [\n \"Map\",\n \"Text\",\n \"List\",\n \"Tree\",\n \"MovableList\",\n \"Counter\",\n];\nfunction isContainerId(s) {\n return isValidContainerId(s);\n}\n/** Whether the value is a container.\n *\n * # Example\n *\n * ```ts\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * const list = doc.getList(\"list\");\n * const text = doc.getText(\"text\");\n * isContainer(map); // true\n * isContainer(list); // true\n * isContainer(text); // true\n * isContainer(123); // false\n * isContainer(\"123\"); // false\n * isContainer({}); // false\n * ```\n */\nfunction isContainer(value) {\n if (typeof value !== \"object\" || value == null) {\n return false;\n }\n const p = Object.getPrototypeOf(value);\n if (p == null || typeof p !== \"object\" || typeof p[\"kind\"] !== \"function\") {\n return false;\n }\n return CONTAINER_TYPES.includes(value.kind());\n}\n/** Get the type of a value that may be a container.\n *\n * # Example\n *\n * ```ts\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * const list = doc.getList(\"list\");\n * const text = doc.getText(\"text\");\n * getType(map); // \"Map\"\n * getType(list); // \"List\"\n * getType(text); // \"Text\"\n * getType(123); // \"Json\"\n * getType(\"123\"); // \"Json\"\n * getType({}); // \"Json\"\n * ```\n */\nfunction getType(value) {\n if (isContainer(value)) {\n return value.kind();\n }\n return \"Json\";\n}\nfunction newContainerID(id, type) {\n return `cid:${id.counter}@${id.peer}:${type}`;\n}\nfunction newRootContainerID(name, type) {\n return `cid:root-${name}:${type}`;\n}\n/**\n * @deprecated Please use `EphemeralStore` instead.\n *\n * Awareness is a structure that allows to track the ephemeral state of the peers.\n *\n * If we don't receive a state update from a peer within the timeout, we will remove their state.\n * The timeout is in milliseconds. This can be used to handle the offline state of a peer.\n */\nclass Awareness {\n constructor(peer, timeout = 30000) {\n this.listeners = new Set();\n this.inner = new AwarenessWasm(peer, timeout);\n this.peer = peer;\n this.timeout = timeout;\n }\n apply(bytes, origin = \"remote\") {\n const { updated, added } = this.inner.apply(bytes);\n this.listeners.forEach((listener) => {\n listener({ updated, added, removed: [] }, origin);\n });\n this.startTimerIfNotEmpty();\n }\n setLocalState(state) {\n const wasEmpty = this.inner.getState(this.peer) == null;\n this.inner.setLocalState(state);\n if (wasEmpty) {\n this.listeners.forEach((listener) => {\n listener({ updated: [], added: [this.inner.peer()], removed: [] }, \"local\");\n });\n }\n else {\n this.listeners.forEach((listener) => {\n listener({ updated: [this.inner.peer()], added: [], removed: [] }, \"local\");\n });\n }\n this.startTimerIfNotEmpty();\n }\n getLocalState() {\n return this.inner.getState(this.peer);\n }\n getAllStates() {\n return this.inner.getAllStates();\n }\n encode(peers) {\n return this.inner.encode(peers);\n }\n encodeAll() {\n return this.inner.encodeAll();\n }\n addListener(listener) {\n this.listeners.add(listener);\n }\n removeListener(listener) {\n this.listeners.delete(listener);\n }\n peers() {\n return this.inner.peers();\n }\n destroy() {\n clearInterval(this.timer);\n this.listeners.clear();\n }\n startTimerIfNotEmpty() {\n if (this.inner.isEmpty() || this.timer != null) {\n return;\n }\n this.timer = setInterval(() => {\n const removed = this.inner.removeOutdated();\n if (removed.length > 0) {\n this.listeners.forEach((listener) => {\n listener({ updated: [], added: [], removed }, \"timeout\");\n });\n }\n if (this.inner.isEmpty()) {\n clearInterval(this.timer);\n this.timer = undefined;\n }\n }, this.timeout / 2);\n }\n}\n/**\n * EphemeralStore tracks ephemeral key-value state across peers.\n *\n * - Use it for lightweight presence/state like cursors, selections, and UI hints.\n * - Conflict resolution is timestamp-based LWW (Last-Write-Wins) per key.\n * - Timeout unit: milliseconds.\n * - After timeout: keys are considered expired. They are omitted from\n * `encode(key)`, `encodeAll()` and `getAllStates()`. A periodic cleanup runs\n * while the store is non-empty and removes expired keys; when removals happen\n * subscribers receive an event with `by: \"timeout\"` and the `removed` keys.\n *\n * See: https://loro.dev/docs/tutorial/ephemeral\n *\n * @param timeout Inactivity timeout in milliseconds (default: 30000). If a key\n * doesn't receive updates within this duration, it will expire and be removed\n * on the next cleanup tick.\n *\n * @example\n * ```ts\n * const store = new EphemeralStore();\n * const store2 = new EphemeralStore();\n * // Subscribe to local updates and forward over the wire\n * store.subscribeLocalUpdates((data) => {\n * store2.apply(data);\n * });\n * // Subscribe to all updates (including removals by timeout)\n * store2.subscribe((event) => {\n * console.log(\"event:\", event);\n * });\n * // Set a value\n * store.set(\"key\", \"value\");\n * // Encode the value\n * const encoded = store.encode(\"key\");\n * // Apply the encoded value\n * store2.apply(encoded);\n * ```\n */\nclass EphemeralStore {\n constructor(timeout = 30000) {\n this.inner = new EphemeralStoreWasm(timeout);\n this.timeout = timeout;\n }\n apply(bytes) {\n this.inner.apply(bytes);\n this.startTimerIfNotEmpty();\n }\n set(key, value) {\n this.inner.set(key, value);\n this.startTimerIfNotEmpty();\n }\n delete(key) {\n this.inner.delete(key);\n }\n get(key) {\n return this.inner.get(key);\n }\n getAllStates() {\n return this.inner.getAllStates();\n }\n encode(key) {\n return this.inner.encode(key);\n }\n encodeAll() {\n return this.inner.encodeAll();\n }\n keys() {\n return this.inner.keys();\n }\n destroy() {\n clearInterval(this.timer);\n }\n subscribe(listener) {\n return this.inner.subscribe(listener);\n }\n subscribeLocalUpdates(listener) {\n return this.inner.subscribeLocalUpdates(listener);\n }\n startTimerIfNotEmpty() {\n if (this.inner.isEmpty() || this.timer != null) {\n return;\n }\n this.timer = setInterval(() => {\n this.inner.removeOutdated();\n if (this.inner.isEmpty()) {\n clearInterval(this.timer);\n this.timer = undefined;\n }\n }, this.timeout / 2);\n }\n}\nLoroDoc.prototype.toJsonWithReplacer = function (replacer) {\n const processed = new Set();\n const doc = this;\n const m = (key, value) => {\n if (typeof value === \"string\") {\n if (isContainerId(value) && !processed.has(value)) {\n processed.add(value);\n const container = doc.getContainerById(value);\n if (container == null) {\n throw new Error(`ContainerID not found: ${value}`);\n }\n const ans = replacer(key, container);\n if (ans === container) {\n const ans = container.getShallowValue();\n if (typeof ans === \"object\") {\n return run(ans);\n }\n return ans;\n }\n if (isContainer(ans)) {\n throw new Error(\"Using new container is not allowed in toJsonWithReplacer\");\n }\n if (typeof ans === \"object\" && ans != null) {\n return run(ans);\n }\n return ans;\n }\n }\n if (typeof value === \"object\" && value != null) {\n return run(value);\n }\n const ans = replacer(key, value);\n if (isContainer(ans)) {\n throw new Error(\"Using new container is not allowed in toJsonWithReplacer\");\n }\n return ans;\n };\n const run = (layer) => {\n if (Array.isArray(layer)) {\n return layer\n .map((item, index) => {\n return m(index, item);\n })\n .filter((item) => item !== undefined);\n }\n const result = {};\n for (const [key, value] of Object.entries(layer)) {\n const ans = m(key, value);\n if (ans !== undefined) {\n result[key] = ans;\n }\n }\n return result;\n };\n const layer = doc.getShallowValue();\n return run(layer);\n};\nfunction idStrToId(idStr) {\n const [counter, peer] = idStr.split(\"@\");\n return {\n counter: parseInt(counter),\n peer: peer,\n };\n}\nconst CALL_PENDING_EVENTS_WRAPPED = Symbol(\"loro.callPendingEventsWrapped\");\nfunction decorateMethod(prototype, method) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, method);\n if (!descriptor || typeof descriptor.value !== \"function\") {\n return;\n }\n const original = descriptor.value;\n if (original[CALL_PENDING_EVENTS_WRAPPED]) {\n return;\n }\n const wrapped = function (...args) {\n let result;\n try {\n result = original.apply(this, args);\n return result;\n }\n finally {\n if (result && typeof result.then === \"function\") {\n result.finally(() => {\n callPendingEvents();\n });\n }\n else {\n callPendingEvents();\n }\n }\n };\n wrapped[CALL_PENDING_EVENTS_WRAPPED] = true;\n Object.defineProperty(prototype, method, {\n ...descriptor,\n value: wrapped,\n });\n}\nfunction decorateMethods(prototype, methods) {\n for (const method of methods) {\n decorateMethod(prototype, method);\n }\n}\ndecorateMethods(LoroDoc.prototype, [\n \"setDetachedEditing\",\n \"attach\",\n \"detach\",\n \"fork\",\n \"forkAt\",\n \"checkoutToLatest\",\n \"checkout\",\n \"commit\",\n \"getCursorPos\",\n \"revertTo\",\n \"export\",\n \"exportJsonUpdates\",\n \"exportJsonInIdSpan\",\n \"importJsonUpdates\",\n \"import\",\n \"importUpdateBatch\",\n \"importBatch\",\n \"travelChangeAncestors\",\n \"getChangedContainersIn\",\n \"diff\",\n \"applyDiff\",\n \"setPeerId\",\n]);\ndecorateMethods(EphemeralStoreWasm.prototype, [\n \"set\",\n \"delete\",\n \"apply\",\n \"removeOutdated\",\n]);\ndecorateMethods(UndoManager.prototype, [\"undo\", \"redo\"]);\n\nexport { Awareness, EphemeralStore, Loro, getType, idStrToId, isContainer, isContainerId, newContainerID, newRootContainerID };\n// loro-explicit-wasm-reexports\nexport {\n AwarenessWasm,\n ChangeModifier,\n Cursor,\n EphemeralStoreWasm,\n LORO_VERSION,\n LoroCounter,\n LoroDoc,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n LoroTreeNode,\n UndoManager,\n VersionVector,\n callPendingEvents,\n decodeFrontiers,\n decodeImportBlobMeta,\n encodeFrontiers,\n initSync,\n isValidContainerId,\n redactJsonUpdates,\n run,\n setDebug,\n} from \"./loro_wasm.js\";\n//# sourceMappingURL=index.js.map\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 // :: () → Object\n // Turn ordered map into a plain object.\n toObject: function() {\n var result = {};\n this.forEach(function(key, value) { result[key] = value; });\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\nexport default OrderedMap;\n", + "import OrderedMap from 'orderedmap';\n\nfunction findDiffStart(a, b, pos) {\n for (let i = 0;; i++) {\n if (i == a.childCount || i == b.childCount)\n return a.childCount == b.childCount ? null : pos;\n let childA = a.child(i), childB = b.child(i);\n if (childA == childB) {\n pos += childA.nodeSize;\n continue;\n }\n if (!childA.sameMarkup(childB))\n return pos;\n if (childA.isText && childA.text != childB.text) {\n let tA = childA.text, tB = childB.text, j = 0;\n for (; tA[j] == tB[j]; j++)\n pos++;\n if (j && j < tA.length && j < tB.length && surrogateHigh(tA.charCodeAt(j - 1)) && surrogateLow(tA.charCodeAt(j)))\n pos--;\n return pos;\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffStart(childA.content, childB.content, pos + 1);\n if (inner != null)\n return inner;\n }\n pos += childA.nodeSize;\n }\n}\nfunction findDiffEnd(a, b, posA, posB) {\n for (let iA = a.childCount, iB = b.childCount;;) {\n if (iA == 0 || iB == 0)\n return iA == iB ? null : { a: posA, b: posB };\n let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;\n if (childA == childB) {\n posA -= size;\n posB -= size;\n continue;\n }\n if (!childA.sameMarkup(childB))\n return { a: posA, b: posB };\n if (childA.isText && childA.text != childB.text) {\n let tA = childA.text, tB = childB.text, iA = tA.length, iB = tB.length;\n while (iA > 0 && iB > 0 && tA[iA - 1] == tB[iB - 1]) {\n iA--;\n iB--;\n posA--;\n posB--;\n }\n if (iA && iB && iA < tA.length && surrogateHigh(tA.charCodeAt(iA - 1)) && surrogateLow(tA.charCodeAt(iA))) {\n posA++;\n posB++;\n }\n return { a: posA, b: posB };\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);\n if (inner)\n return inner;\n }\n posA -= size;\n posB -= size;\n }\n}\nfunction surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }\nfunction surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }\n\n/**\nA fragment represents a node's collection of child nodes.\n\nLike nodes, fragments are persistent data structures, and you\nshould not mutate them or their content. Rather, you create new\ninstances whenever needed. The API tries to make this easy.\n*/\nclass Fragment {\n /**\n @internal\n */\n constructor(\n /**\n The child nodes in this fragment.\n */\n content, size) {\n this.content = content;\n this.size = size || 0;\n if (size == null)\n for (let i = 0; i < content.length; i++)\n this.size += content[i].nodeSize;\n }\n /**\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`.\n */\n nodesBetween(from, to, f, nodeStart = 0, parent) {\n for (let i = 0, pos = 0; pos < to; i++) {\n let child = this.content[i], end = pos + child.nodeSize;\n if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {\n let start = pos + 1;\n child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);\n }\n pos = end;\n }\n }\n /**\n Call the given callback for every descendant node. `pos` will be\n relative to the start of the fragment. The callback may return\n `false` to prevent traversal of a given node's children.\n */\n descendants(f) {\n this.nodesBetween(0, this.size, f);\n }\n /**\n Extract the text between `from` and `to`. See the same method on\n [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).\n */\n textBetween(from, to, blockSeparator, leafText) {\n let text = \"\", first = true;\n this.nodesBetween(from, to, (node, pos) => {\n let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos)\n : !node.isLeaf ? \"\"\n : leafText ? (typeof leafText === \"function\" ? leafText(node) : leafText)\n : node.type.spec.leafText ? node.type.spec.leafText(node)\n : \"\";\n if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {\n if (first)\n first = false;\n else\n text += blockSeparator;\n }\n text += nodeText;\n }, 0);\n return text;\n }\n /**\n Create a new fragment containing the combined content of this\n fragment and the other.\n */\n append(other) {\n if (!other.size)\n return this;\n if (!this.size)\n return other;\n let 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++)\n content.push(other.content[i]);\n return new Fragment(content, this.size + other.size);\n }\n /**\n Cut out the sub-fragment between the two given positions.\n */\n cut(from, to = this.size) {\n if (from == 0 && to == this.size)\n return this;\n let result = [], size = 0;\n if (to > from)\n for (let i = 0, pos = 0; pos < to; i++) {\n let 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 /**\n @internal\n */\n cutByIndex(from, to) {\n if (from == to)\n return Fragment.empty;\n if (from == 0 && to == this.content.length)\n return this;\n return new Fragment(this.content.slice(from, to));\n }\n /**\n Create a new fragment in which the node at the given index is\n replaced by the given node.\n */\n replaceChild(index, node) {\n let current = this.content[index];\n if (current == node)\n return this;\n let copy = this.content.slice();\n let size = this.size + node.nodeSize - current.nodeSize;\n copy[index] = node;\n return new Fragment(copy, size);\n }\n /**\n Create a new fragment by prepending the given node to this\n fragment.\n */\n addToStart(node) {\n return new Fragment([node].concat(this.content), this.size + node.nodeSize);\n }\n /**\n Create a new fragment by appending the given node to this\n fragment.\n */\n addToEnd(node) {\n return new Fragment(this.content.concat(node), this.size + node.nodeSize);\n }\n /**\n Compare this fragment to another one.\n */\n eq(other) {\n if (this.content.length != other.content.length)\n return false;\n for (let i = 0; i < this.content.length; i++)\n if (!this.content[i].eq(other.content[i]))\n return false;\n return true;\n }\n /**\n The first child of the fragment, or `null` if it is empty.\n */\n get firstChild() { return this.content.length ? this.content[0] : null; }\n /**\n The last child of the fragment, or `null` if it is empty.\n */\n get lastChild() { return this.content.length ? this.content[this.content.length - 1] : null; }\n /**\n The number of child nodes in this fragment.\n */\n get childCount() { return this.content.length; }\n /**\n Get the child node at the given index. Raise an error when the\n index is out of range.\n */\n child(index) {\n let found = this.content[index];\n if (!found)\n throw new RangeError(\"Index \" + index + \" out of range for \" + this);\n return found;\n }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) {\n return this.content[index] || null;\n }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) {\n for (let i = 0, p = 0; i < this.content.length; i++) {\n let child = this.content[i];\n f(child, p, i);\n p += child.nodeSize;\n }\n }\n /**\n Find the first position at which this fragment and another\n fragment differ, or `null` if they are the same.\n */\n findDiffStart(other, pos = 0) {\n return findDiffStart(this, other, pos);\n }\n /**\n Find the first position, searching from the end, at which this\n fragment and the given fragment differ, or `null` if they are\n the same. Since this position will not be the same in both\n nodes, an object with two separate positions is returned.\n */\n findDiffEnd(other, pos = this.size, otherPos = other.size) {\n return findDiffEnd(this, other, pos, otherPos);\n }\n /**\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. @internal\n */\n findIndex(pos) {\n if (pos == 0)\n return retIndex(0, pos);\n if (pos == this.size)\n return retIndex(this.content.length, pos);\n if (pos > this.size || pos < 0)\n throw new RangeError(`Position ${pos} outside of fragment (${this})`);\n for (let i = 0, curPos = 0;; i++) {\n let cur = this.child(i), end = curPos + cur.nodeSize;\n if (end >= pos) {\n if (end == pos)\n return retIndex(i + 1, end);\n return retIndex(i, curPos);\n }\n curPos = end;\n }\n }\n /**\n Return a debugging string that describes this fragment.\n */\n toString() { return \"<\" + this.toStringInner() + \">\"; }\n /**\n @internal\n */\n toStringInner() { return this.content.join(\", \"); }\n /**\n Create a JSON-serializeable representation of this fragment.\n */\n toJSON() {\n return this.content.length ? this.content.map(n => n.toJSON()) : null;\n }\n /**\n Deserialize a fragment from its JSON representation.\n */\n static fromJSON(schema, value) {\n if (!value)\n return Fragment.empty;\n if (!Array.isArray(value))\n throw new RangeError(\"Invalid input for Fragment.fromJSON\");\n return Fragment.fromArray(value.map(schema.nodeFromJSON));\n }\n /**\n Build a fragment from an array of nodes. Ensures that adjacent\n text nodes with the same marks are joined together.\n */\n static fromArray(array) {\n if (!array.length)\n return Fragment.empty;\n let joined, size = 0;\n for (let i = 0; i < array.length; i++) {\n let node = array[i];\n size += node.nodeSize;\n if (i && node.isText && array[i - 1].sameMarkup(node)) {\n if (!joined)\n joined = array.slice(0, i);\n joined[joined.length - 1] = node\n .withText(joined[joined.length - 1].text + node.text);\n }\n else if (joined) {\n joined.push(node);\n }\n }\n return new Fragment(joined || array, size);\n }\n /**\n Create a fragment from something that can be interpreted as a\n set 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.\n */\n static from(nodes) {\n if (!nodes)\n return Fragment.empty;\n if (nodes instanceof Fragment)\n return nodes;\n if (Array.isArray(nodes))\n return this.fromArray(nodes);\n if (nodes.attrs)\n 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}\n/**\nAn empty fragment. Intended to be reused whenever a node doesn't\ncontain anything (rather than allocating a new empty fragment for\neach leaf node).\n*/\nFragment.empty = new Fragment([], 0);\nconst found = { index: 0, offset: 0 };\nfunction retIndex(index, offset) {\n found.index = index;\n found.offset = offset;\n return found;\n}\n\nfunction compareDeep(a, b) {\n if (a === b)\n return true;\n if (!(a && typeof a == \"object\") ||\n !(b && typeof b == \"object\"))\n return false;\n let array = Array.isArray(a);\n if (Array.isArray(b) != array)\n return false;\n if (array) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!compareDeep(a[i], b[i]))\n return false;\n }\n else {\n for (let p in a)\n if (!(p in b) || !compareDeep(a[p], b[p]))\n return false;\n for (let p in b)\n if (!(p in a))\n return false;\n }\n return true;\n}\n\n/**\nA mark is a piece of information that can be attached to a node,\nsuch as it being emphasized, in code font, or a link. It has a\ntype and optionally a set of attributes that provide further\ninformation (such as the target of the link). Marks are created\nthrough a `Schema`, which controls which types exist and which\nattributes they have.\n*/\nclass Mark {\n /**\n @internal\n */\n constructor(\n /**\n The type of this mark.\n */\n type, \n /**\n The attributes associated with this mark.\n */\n attrs) {\n this.type = type;\n this.attrs = attrs;\n }\n /**\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](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,\n those are replaced by this one.\n */\n addToSet(set) {\n let copy, placed = false;\n for (let i = 0; i < set.length; i++) {\n let other = set[i];\n if (this.eq(other))\n return set;\n if (this.type.excludes(other.type)) {\n if (!copy)\n copy = set.slice(0, i);\n }\n else if (other.type.excludes(this.type)) {\n return set;\n }\n else {\n if (!placed && other.type.rank > this.type.rank) {\n if (!copy)\n copy = set.slice(0, i);\n copy.push(this);\n placed = true;\n }\n if (copy)\n copy.push(other);\n }\n }\n if (!copy)\n copy = set.slice();\n if (!placed)\n copy.push(this);\n return copy;\n }\n /**\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.\n */\n removeFromSet(set) {\n for (let 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 Test whether this mark is in the given set of marks.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++)\n if (this.eq(set[i]))\n return true;\n return false;\n }\n /**\n Test whether this mark has the same type and attributes as\n another mark.\n */\n eq(other) {\n return this == other ||\n (this.type == other.type && compareDeep(this.attrs, other.attrs));\n }\n /**\n Convert this mark to a JSON-serializeable representation.\n */\n toJSON() {\n let obj = { type: this.type.name };\n for (let _ in this.attrs) {\n obj.attrs = this.attrs;\n break;\n }\n return obj;\n }\n /**\n Deserialize a mark from JSON.\n */\n static fromJSON(schema, json) {\n if (!json)\n throw new RangeError(\"Invalid input for Mark.fromJSON\");\n let type = schema.marks[json.type];\n if (!type)\n throw new RangeError(`There is no mark type ${json.type} in this schema`);\n let mark = type.create(json.attrs);\n return mark;\n }\n /**\n Test whether two sets of marks are identical.\n */\n static sameSet(a, b) {\n if (a == b)\n return true;\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].eq(b[i]))\n return false;\n return true;\n }\n /**\n Create a properly sorted mark set from null, a single mark, or an\n unsorted array of marks.\n */\n static setFrom(marks) {\n if (!marks || Array.isArray(marks) && marks.length == 0)\n return Mark.none;\n if (marks instanceof Mark)\n return [marks];\n let copy = marks.slice();\n copy.sort((a, b) => a.type.rank - b.type.rank);\n return copy;\n }\n}\n/**\nThe empty set of marks.\n*/\nMark.none = [];\n\n/**\nError type raised by [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) when\ngiven an invalid replacement.\n*/\nclass ReplaceError extends Error {\n}\n/**\nA slice represents a piece cut out of a larger document. It\nstores not only a fragment, but also the depth up to which nodes on\nboth side are ‘open’ (cut through).\n*/\nclass Slice {\n /**\n Create a slice. When specifying a non-zero open depth, you must\n make sure that there are nodes of at least that depth at the\n appropriate side of the fragment—i.e. if the fragment is an\n empty paragraph node, `openStart` and `openEnd` can't be greater\n than 1.\n \n It is not necessary for the content of open nodes to conform to\n the schema's content constraints, though it should be a valid\n start/end/middle for such a node, depending on which sides are\n open.\n */\n constructor(\n /**\n The slice's content.\n */\n content, \n /**\n The open depth at the start of the fragment.\n */\n openStart, \n /**\n The open depth at the end.\n */\n openEnd) {\n this.content = content;\n this.openStart = openStart;\n this.openEnd = openEnd;\n }\n /**\n The size this slice would add when inserted into a document.\n */\n get size() {\n return this.content.size - this.openStart - this.openEnd;\n }\n /**\n @internal\n */\n insertAt(pos, fragment) {\n let content = insertInto(this.content, pos + this.openStart, fragment, this.openStart + 1, this.openEnd + 1);\n return content && new Slice(content, this.openStart, this.openEnd);\n }\n /**\n @internal\n */\n removeBetween(from, to) {\n return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);\n }\n /**\n Tests whether this slice is equal to another slice.\n */\n eq(other) {\n return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;\n }\n /**\n @internal\n */\n toString() {\n return this.content + \"(\" + this.openStart + \",\" + this.openEnd + \")\";\n }\n /**\n Convert a slice to a JSON-serializable representation.\n */\n toJSON() {\n if (!this.content.size)\n return null;\n let json = { content: this.content.toJSON() };\n if (this.openStart > 0)\n json.openStart = this.openStart;\n if (this.openEnd > 0)\n json.openEnd = this.openEnd;\n return json;\n }\n /**\n Deserialize a slice from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json)\n return Slice.empty;\n let 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 Create a slice from a fragment by taking the maximum possible\n open value on both side of the fragment.\n */\n static maxOpen(fragment, openIsolating = true) {\n let openStart = 0, openEnd = 0;\n for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)\n openStart++;\n for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)\n openEnd++;\n return new Slice(fragment, openStart, openEnd);\n }\n}\n/**\nThe empty slice.\n*/\nSlice.empty = new Slice(Fragment.empty, 0, 0);\nfunction removeRange(content, from, to) {\n let { index, offset } = content.findIndex(from), child = content.maybeChild(index);\n let { index: indexTo, offset: offsetTo } = content.findIndex(to);\n if (offset == from || child.isText) {\n if (offsetTo != to && !content.child(indexTo).isText)\n throw new RangeError(\"Removing non-flat range\");\n return content.cut(0, from).append(content.cut(to));\n }\n if (index != indexTo)\n throw new RangeError(\"Removing non-flat range\");\n return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));\n}\nfunction insertInto(content, dist, insert, openStart, openEnd, parent) {\n let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);\n if (offset == dist || child.isText) {\n if (parent && openStart <= 0 && openEnd <= 0 && !parent.canReplace(index, index, insert))\n return null;\n return content.cut(0, dist).append(insert).append(content.cut(dist));\n }\n let inner = insertInto(child.content, dist - offset - 1, insert, index == 0 ? openStart - 1 : 0, index == content.childCount - 1 ? openEnd - 1 : 0, child);\n return inner && content.replaceChild(index, child.copy(inner));\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}\nfunction replaceOuter($from, $to, slice, depth) {\n let index = $from.index(depth), node = $from.node(depth);\n if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {\n let inner = replaceOuter($from, $to, slice, depth + 1);\n return node.copy(node.content.replaceChild(index, inner));\n }\n else if (!slice.content.size) {\n return close(node, replaceTwoWay($from, $to, depth));\n }\n else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case\n let parent = $from.parent, content = parent.content;\n return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));\n }\n else {\n let { start, end } = prepareSliceForReplace(slice, $from);\n return close(node, replaceThreeWay($from, start, end, $to, depth));\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}\nfunction joinable($before, $after, depth) {\n let node = $before.node(depth);\n checkJoin(node, $after.node(depth));\n return node;\n}\nfunction addNode(child, target) {\n let 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}\nfunction addRange($start, $end, depth, target) {\n let node = ($end || $start).node(depth);\n let 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 }\n else if ($start.textOffset) {\n addNode($start.nodeAfter, target);\n startIndex++;\n }\n }\n for (let i = startIndex; i < endIndex; i++)\n addNode(node.child(i), target);\n if ($end && $end.depth == depth && $end.textOffset)\n addNode($end.nodeBefore, target);\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}\nfunction replaceThreeWay($from, $start, $end, $to, depth) {\n let openStart = $from.depth > depth && joinable($from, $start, depth + 1);\n let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);\n let 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 }\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}\nfunction replaceTwoWay($from, $to, depth) {\n let content = [];\n addRange(null, $from, depth, content);\n if ($from.depth > depth) {\n let 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}\nfunction prepareSliceForReplace(slice, $along) {\n let extra = $along.depth - slice.openStart, parent = $along.node(extra);\n let node = parent.copy(slice.content);\n for (let 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/**\nYou can [_resolve_](https://prosemirror.net/docs/ref/#model.Node.resolve) a position to get more\ninformation about it. Objects of this class represent such a\nresolved position, providing various pieces of context\ninformation, and some helper methods.\n\nThroughout this interface, methods that take an optional `depth`\nparameter will interpret undefined as `this.depth` and negative\nnumbers as `this.depth + value`.\n*/\nclass ResolvedPos {\n /**\n @internal\n */\n constructor(\n /**\n The position that was resolved.\n */\n pos, \n /**\n @internal\n */\n path, \n /**\n The offset this position has into its parent node.\n */\n parentOffset) {\n this.pos = pos;\n this.path = path;\n this.parentOffset = parentOffset;\n this.depth = path.length / 3 - 1;\n }\n /**\n @internal\n */\n resolveDepth(val) {\n if (val == null)\n return this.depth;\n if (val < 0)\n return this.depth + val;\n return val;\n }\n /**\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.\n */\n get parent() { return this.node(this.depth); }\n /**\n The root node in which the position was resolved.\n */\n get doc() { return this.node(0); }\n /**\n The ancestor node at the given level. `p.node(p.depth)` is the\n same as `p.parent`.\n */\n node(depth) { return this.path[this.resolveDepth(depth) * 3]; }\n /**\n The index into the ancestor at the given level. If this points\n at the 3rd node in the 2nd paragraph on the top level, for\n example, `p.index(0)` is 1 and `p.index(1)` is 2.\n */\n index(depth) { return this.path[this.resolveDepth(depth) * 3 + 1]; }\n /**\n The index pointing after this position into the ancestor at the\n given level.\n */\n indexAfter(depth) {\n depth = this.resolveDepth(depth);\n return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);\n }\n /**\n The (absolute) position at the start of the node at the given\n level.\n */\n start(depth) {\n depth = this.resolveDepth(depth);\n return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n }\n /**\n The (absolute) position at the end of the node at the given\n level.\n */\n end(depth) {\n depth = this.resolveDepth(depth);\n return this.start(depth) + this.node(depth).content.size;\n }\n /**\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.\n */\n before(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n 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 The (absolute) position directly after the wrapping node at the\n given level, or the original position when `depth` is `this.depth + 1`.\n */\n after(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n 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 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.\n */\n get textOffset() { return this.pos - this.path[this.path.length - 1]; }\n /**\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.\n */\n get nodeAfter() {\n let parent = this.parent, index = this.index(this.depth);\n if (index == parent.childCount)\n return null;\n let 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 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.\n */\n get nodeBefore() {\n let index = this.index(this.depth);\n let dOff = this.pos - this.path[this.path.length - 1];\n if (dOff)\n return this.parent.child(index).cut(0, dOff);\n return index == 0 ? null : this.parent.child(index - 1);\n }\n /**\n Get the position at the given index in the parent node at the\n given depth (which defaults to `this.depth`).\n */\n posAtIndex(index, depth) {\n depth = this.resolveDepth(depth);\n let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n for (let i = 0; i < index; i++)\n pos += node.child(i).nodeSize;\n return pos;\n }\n /**\n Get the marks at this position, factoring in the surrounding\n marks' [`inclusive`](https://prosemirror.net/docs/ref/#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.\n */\n marks() {\n let parent = this.parent, index = this.index();\n // In an empty parent, return the empty array\n if (parent.content.size == 0)\n return Mark.none;\n // When inside a text node, just return the text node's marks\n if (this.textOffset)\n return parent.child(index).marks;\n let 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) {\n let tmp = main;\n main = other;\n 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 let 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 return marks;\n }\n /**\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).\n */\n marksAcross($end) {\n let after = this.parent.maybeChild(this.index());\n if (!after || !after.isInline)\n return null;\n let 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 The depth up to which this position and the given (non-resolved)\n position share the same parent nodes.\n */\n sharedDepth(pos) {\n for (let depth = this.depth; depth > 0; depth--)\n if (this.start(depth) <= pos && this.end(depth) >= pos)\n return depth;\n return 0;\n }\n /**\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.\n */\n blockRange(other = this, pred) {\n if (other.pos < this.pos)\n return other.blockRange(this);\n for (let 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 return null;\n }\n /**\n Query whether the given position shares the same parent node.\n */\n sameParent(other) {\n return this.pos - this.parentOffset == other.pos - other.parentOffset;\n }\n /**\n Return the greater of this and the given position.\n */\n max(other) {\n return other.pos > this.pos ? other : this;\n }\n /**\n Return the smaller of this and the given position.\n */\n min(other) {\n return other.pos < this.pos ? other : this;\n }\n /**\n @internal\n */\n toString() {\n let str = \"\";\n for (let 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 /**\n @internal\n */\n static resolve(doc, pos) {\n if (!(pos >= 0 && pos <= doc.content.size))\n throw new RangeError(\"Position \" + pos + \" out of range\");\n let path = [];\n let start = 0, parentOffset = pos;\n for (let node = doc;;) {\n let { index, offset } = node.content.findIndex(parentOffset);\n let rem = parentOffset - offset;\n path.push(node, index, start + offset);\n if (!rem)\n break;\n node = node.child(index);\n if (node.isText)\n break;\n parentOffset = rem - 1;\n start += offset + 1;\n }\n return new ResolvedPos(pos, path, parentOffset);\n }\n /**\n @internal\n */\n static resolveCached(doc, pos) {\n let cache = resolveCache.get(doc);\n if (cache) {\n for (let i = 0; i < cache.elts.length; i++) {\n let elt = cache.elts[i];\n if (elt.pos == pos)\n return elt;\n }\n }\n else {\n resolveCache.set(doc, cache = new ResolveCache);\n }\n let result = cache.elts[cache.i] = ResolvedPos.resolve(doc, pos);\n cache.i = (cache.i + 1) % resolveCacheSize;\n return result;\n }\n}\nclass ResolveCache {\n constructor() {\n this.elts = [];\n this.i = 0;\n }\n}\nconst resolveCacheSize = 12, resolveCache = new WeakMap();\n/**\nRepresents a flat range of content, i.e. one that starts and\nends in the same node.\n*/\nclass NodeRange {\n /**\n Construct a node range. `$from` and `$to` should point into the\n same node until at least the given `depth`, since a node range\n denotes an adjacent set of nodes in a single parent node.\n */\n constructor(\n /**\n A resolved position along the start of the content. May have a\n `depth` greater than this object's `depth` property, since\n these are the positions that were used to compute the range,\n not re-resolved positions directly at its boundaries.\n */\n $from, \n /**\n A position along the end of the content. See\n caveat for [`$from`](https://prosemirror.net/docs/ref/#model.NodeRange.$from).\n */\n $to, \n /**\n The depth of the node that this range points into.\n */\n depth) {\n this.$from = $from;\n this.$to = $to;\n this.depth = depth;\n }\n /**\n The position at the start of the range.\n */\n get start() { return this.$from.before(this.depth + 1); }\n /**\n The position at the end of the range.\n */\n get end() { return this.$to.after(this.depth + 1); }\n /**\n The parent node that the range points into.\n */\n get parent() { return this.$from.node(this.depth); }\n /**\n The start index of the range in the parent node.\n */\n get startIndex() { return this.$from.index(this.depth); }\n /**\n The end index of the range in the parent node.\n */\n get endIndex() { return this.$to.indexAfter(this.depth); }\n}\n\nconst emptyAttrs = Object.create(null);\n/**\nThis class represents a node in the tree that makes up a\nProseMirror document. So a document is an instance of `Node`, with\nchildren that are also instances of `Node`.\n\nNodes are persistent data structures. Instead of changing them, you\ncreate new ones with the content you want. Old ones keep pointing\nat the old document shape. This is made cheaper by sharing\nstructure between the old and new data as much as possible, which a\ntree shape like this (without back pointers) makes easy.\n\n**Do not** directly mutate the properties of a `Node` object. See\n[the guide](https://prosemirror.net/docs/guide/#doc) for more information.\n*/\nclass Node {\n /**\n @internal\n */\n constructor(\n /**\n The type of node that this is.\n */\n type, \n /**\n An object mapping attribute names to values. The kind of\n attributes allowed and required are\n [determined](https://prosemirror.net/docs/ref/#model.NodeSpec.attrs) by the node type.\n */\n attrs, \n // A fragment holding the node's children.\n content, \n /**\n The marks (things like whether it is emphasized or part of a\n link) applied to this node.\n */\n marks = Mark.none) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.content = content || Fragment.empty;\n }\n /**\n The array of this node's child nodes.\n */\n get children() { return this.content.content; }\n /**\n The size of this node, as defined by the integer-based [indexing\n scheme](https://prosemirror.net/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\n start and end token).\n */\n get nodeSize() { return this.isLeaf ? 1 : 2 + this.content.size; }\n /**\n The number of children that the node has.\n */\n get childCount() { return this.content.childCount; }\n /**\n Get the child node at the given index. Raises an error when the\n index is out of range.\n */\n child(index) { return this.content.child(index); }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) { return this.content.maybeChild(index); }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) { this.content.forEach(f); }\n /**\n Invoke a callback for all descendant nodes recursively overlapping\n the given two positions that are relative to start of this\n node's content. This includes all ancestors of the nodes\n containing the two positions. The callback is invoked with the\n node, its position relative to the original node (method receiver),\n its parent node, and its child index. When the callback returns\n false for a given node, that node's children will not be\n recursed over. The last parameter can be used to specify a\n starting position to count from.\n */\n nodesBetween(from, to, f, startPos = 0) {\n this.content.nodesBetween(from, to, f, startPos, this);\n }\n /**\n Call the given callback for every descendant node. Doesn't\n descend into a node when the callback returns `false`.\n */\n descendants(f) {\n this.nodesBetween(0, this.content.size, f);\n }\n /**\n Concatenates all the text nodes found in this fragment and its\n children.\n */\n get textContent() {\n return (this.isLeaf && this.type.spec.leafText)\n ? this.type.spec.leafText(this)\n : this.textBetween(0, this.content.size, \"\");\n }\n /**\n Get all text between positions `from` and `to`. When\n `blockSeparator` is given, it will be inserted to separate text\n from different block nodes. If `leafText` is given, it'll be\n inserted for every non-text leaf node encountered, otherwise\n [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used.\n */\n textBetween(from, to, blockSeparator, leafText) {\n return this.content.textBetween(from, to, blockSeparator, leafText);\n }\n /**\n Returns this node's first child, or `null` if there are no\n children.\n */\n get firstChild() { return this.content.firstChild; }\n /**\n Returns this node's last child, or `null` if there are no\n children.\n */\n get lastChild() { return this.content.lastChild; }\n /**\n Test whether two nodes represent the same piece of document.\n */\n eq(other) {\n return this == other || (this.sameMarkup(other) && this.content.eq(other.content));\n }\n /**\n Compare the markup (type, attributes, and marks) of this node to\n those of another. Returns `true` if both have the same markup.\n */\n sameMarkup(other) {\n return this.hasMarkup(other.type, other.attrs, other.marks);\n }\n /**\n Check whether this node's markup correspond to the given type,\n attributes, and marks.\n */\n 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 Create a new node with the same markup as this node, containing\n the given content (or empty, if no content is given).\n */\n copy(content = null) {\n if (content == this.content)\n return this;\n return new Node(this.type, this.attrs, content, this.marks);\n }\n /**\n Create a copy of this node, with the given set of marks instead\n of the node's own marks.\n */\n mark(marks) {\n return marks == this.marks ? this : new Node(this.type, this.attrs, this.content, marks);\n }\n /**\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.\n */\n cut(from, to = this.content.size) {\n if (from == 0 && to == this.content.size)\n return this;\n return this.copy(this.content.cut(from, to));\n }\n /**\n Cut out the part of the document between the given positions, and\n return it as a `Slice` object.\n */\n slice(from, to = this.content.size, includeParents = false) {\n if (from == to)\n return Slice.empty;\n let $from = this.resolve(from), $to = this.resolve(to);\n let depth = includeParents ? 0 : $from.sharedDepth(to);\n let start = $from.start(depth), node = $from.node(depth);\n let content = node.content.cut($from.pos - start, $to.pos - start);\n return new Slice(content, $from.depth - depth, $to.depth - depth);\n }\n /**\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`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.\n */\n replace(from, to, slice) {\n return replace(this.resolve(from), this.resolve(to), slice);\n }\n /**\n Find the node directly after the given position.\n */\n nodeAt(pos) {\n for (let node = this;;) {\n let { index, offset } = node.content.findIndex(pos);\n node = node.maybeChild(index);\n if (!node)\n return null;\n if (offset == pos || node.isText)\n return node;\n pos -= offset + 1;\n }\n }\n /**\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.\n */\n childAfter(pos) {\n let { index, offset } = this.content.findIndex(pos);\n return { node: this.content.maybeChild(index), index, offset };\n }\n /**\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.\n */\n childBefore(pos) {\n if (pos == 0)\n return { node: null, index: 0, offset: 0 };\n let { index, offset } = this.content.findIndex(pos);\n if (offset < pos)\n return { node: this.content.child(index), index, offset };\n let node = this.content.child(index - 1);\n return { node, index: index - 1, offset: offset - node.nodeSize };\n }\n /**\n Resolve the given position in the document, returning an\n [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.\n */\n resolve(pos) { return ResolvedPos.resolveCached(this, pos); }\n /**\n @internal\n */\n resolveNoCache(pos) { return ResolvedPos.resolve(this, pos); }\n /**\n Test whether a given mark or mark type occurs in this document\n between the two given positions.\n */\n rangeHasMark(from, to, type) {\n let found = false;\n if (to > from)\n this.nodesBetween(from, to, node => {\n if (type.isInSet(node.marks))\n found = true;\n return !found;\n });\n return found;\n }\n /**\n True when this is a block (non-inline node)\n */\n get isBlock() { return this.type.isBlock; }\n /**\n True when this is a textblock node, a block node with inline\n content.\n */\n get isTextblock() { return this.type.isTextblock; }\n /**\n True when this node allows inline content.\n */\n get inlineContent() { return this.type.inlineContent; }\n /**\n True when this is an inline node (a text node or a node that can\n appear among text).\n */\n get isInline() { return this.type.isInline; }\n /**\n True when this is a text node.\n */\n get isText() { return this.type.isText; }\n /**\n True when this is a leaf node.\n */\n get isLeaf() { return this.type.isLeaf; }\n /**\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](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)\n on a node's spec (typically used when the node is displayed as\n an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).\n */\n get isAtom() { return this.type.isAtom; }\n /**\n Return a string representation of this node for debugging\n purposes.\n */\n toString() {\n if (this.type.spec.toDebugString)\n return this.type.spec.toDebugString(this);\n let name = this.type.name;\n if (this.content.size)\n name += \"(\" + this.content.toStringInner() + \")\";\n return wrapMarks(this.marks, name);\n }\n /**\n Get the content match in this node at the given index.\n */\n contentMatchAt(index) {\n let match = this.type.contentMatch.matchFragment(this.content, 0, index);\n if (!match)\n throw new Error(\"Called contentMatchAt on a node with invalid content\");\n return match;\n }\n /**\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.\n */\n canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {\n let one = this.contentMatchAt(from).matchFragment(replacement, start, end);\n let two = one && one.matchFragment(this.content, to);\n if (!two || !two.validEnd)\n return false;\n for (let i = start; i < end; i++)\n if (!this.type.allowsMarks(replacement.child(i).marks))\n return false;\n return true;\n }\n /**\n Test whether replacing the range `from` to `to` (by index) with\n a node of the given type would leave the node's content valid.\n */\n canReplaceWith(from, to, type, marks) {\n if (marks && !this.type.allowsMarks(marks))\n return false;\n let start = this.contentMatchAt(from).matchType(type);\n let end = start && start.matchFragment(this.content, to);\n return end ? end.validEnd : false;\n }\n /**\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).\n */\n canAppend(other) {\n if (other.content.size)\n return this.canReplace(this.childCount, this.childCount, other.content);\n else\n return this.type.compatibleContent(other.type);\n }\n /**\n Check whether this node and its descendants conform to the\n schema, and raise an exception when they do not.\n */\n check() {\n this.type.checkContent(this.content);\n checkAttrs(this.type.attrs, this.attrs, \"node\", this.type.name);\n let copy = Mark.none;\n for (let i = 0; i < this.marks.length; i++) {\n let mark = this.marks[i];\n checkAttrs(mark.type.attrs, mark.attrs, \"mark\", mark.type.name);\n copy = mark.addToSet(copy);\n }\n if (!Mark.sameSet(copy, this.marks))\n throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(m => m.type.name)}`);\n this.content.forEach(node => node.check());\n }\n /**\n Return a JSON-serializeable representation of this node.\n */\n toJSON() {\n let obj = { type: this.type.name };\n for (let _ 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(n => n.toJSON());\n return obj;\n }\n /**\n Deserialize a node from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json)\n throw new RangeError(\"Invalid input for Node.fromJSON\");\n let marks = undefined;\n if (json.marks) {\n if (!Array.isArray(json.marks))\n 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\")\n throw new RangeError(\"Invalid text node in JSON\");\n return schema.text(json.text, marks);\n }\n let content = Fragment.fromJSON(schema, json.content);\n let node = schema.nodeType(json.type).create(json.attrs, content, marks);\n return node;\n }\n}\nNode.prototype.text = undefined;\nclass TextNode extends Node {\n /**\n @internal\n */\n constructor(type, attrs, content, marks) {\n super(type, attrs, null, marks);\n if (!content)\n throw new RangeError(\"Empty text nodes are not allowed\");\n this.text = content;\n }\n toString() {\n if (this.type.spec.toDebugString)\n return this.type.spec.toDebugString(this);\n return wrapMarks(this.marks, JSON.stringify(this.text));\n }\n get textContent() { return this.text; }\n textBetween(from, to) { return this.text.slice(from, to); }\n get nodeSize() { return this.text.length; }\n mark(marks) {\n return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks);\n }\n withText(text) {\n if (text == this.text)\n return this;\n return new TextNode(this.type, this.attrs, text, this.marks);\n }\n cut(from = 0, to = this.text.length) {\n if (from == 0 && to == this.text.length)\n return this;\n return this.withText(this.text.slice(from, to));\n }\n eq(other) {\n return this.sameMarkup(other) && this.text == other.text;\n }\n toJSON() {\n let base = super.toJSON();\n base.text = this.text;\n return base;\n }\n}\nfunction wrapMarks(marks, str) {\n for (let i = marks.length - 1; i >= 0; i--)\n str = marks[i].type.name + \"(\" + str + \")\";\n return str;\n}\nfunction checkAttrs(attrs, values, type, name) {\n for (let attr in values)\n if (!(attr in attrs))\n throw new RangeError(`Unsupported attribute ${attr} for ${type} of type ${name}`);\n for (let attr in attrs) {\n if (attrs[attr].validate)\n attrs[attr].validate(values[attr]);\n }\n}\n\n/**\nInstances of this class represent a match state of a node type's\n[content expression](https://prosemirror.net/docs/ref/#model.NodeSpec.content), and can be used to\nfind out whether further content matches here, and whether a given\nposition is a valid end of the node.\n*/\nclass ContentMatch {\n /**\n @internal\n */\n constructor(\n /**\n True when this match state represents a valid end of the node.\n */\n validEnd) {\n this.validEnd = validEnd;\n /**\n @internal\n */\n this.next = [];\n /**\n @internal\n */\n this.wrapCache = [];\n }\n /**\n @internal\n */\n static parse(string, nodeTypes) {\n let stream = new TokenStream(string, nodeTypes);\n if (stream.next == null)\n return ContentMatch.empty;\n let expr = parseExpr(stream);\n if (stream.next)\n stream.err(\"Unexpected trailing text\");\n let match = dfa(nfa(expr));\n checkForDeadEnds(match, stream);\n return match;\n }\n /**\n Match a node type, returning a match after that node if\n successful.\n */\n matchType(type) {\n for (let i = 0; i < this.next.length; i++)\n if (this.next[i].type == type)\n return this.next[i].next;\n return null;\n }\n /**\n Try to match a fragment. Returns the resulting match when\n successful.\n */\n matchFragment(frag, start = 0, end = frag.childCount) {\n let cur = this;\n for (let i = start; cur && i < end; i++)\n cur = cur.matchType(frag.child(i).type);\n return cur;\n }\n /**\n @internal\n */\n get inlineContent() {\n return this.next.length != 0 && this.next[0].type.isInline;\n }\n /**\n Get the first matching node type at this match position that can\n be generated.\n */\n get defaultType() {\n for (let i = 0; i < this.next.length; i++) {\n let { type } = this.next[i];\n if (!(type.isText || type.hasRequiredAttrs()))\n return type;\n }\n return null;\n }\n /**\n @internal\n */\n compatible(other) {\n for (let i = 0; i < this.next.length; i++)\n for (let j = 0; j < other.next.length; j++)\n if (this.next[i].type == other.next[j].type)\n return true;\n return false;\n }\n /**\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.\n */\n fillBefore(after, toEnd = false, startIndex = 0) {\n let seen = [this];\n function search(match, types) {\n let finished = match.matchFragment(after, startIndex);\n if (finished && (!toEnd || finished.validEnd))\n return Fragment.from(types.map(tp => tp.createAndFill()));\n for (let i = 0; i < match.next.length; i++) {\n let { type, next } = match.next[i];\n if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {\n seen.push(next);\n let found = search(next, types.concat(type));\n if (found)\n return found;\n }\n }\n return null;\n }\n return search(this, []);\n }\n /**\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.\n */\n findWrapping(target) {\n for (let i = 0; i < this.wrapCache.length; i += 2)\n if (this.wrapCache[i] == target)\n return this.wrapCache[i + 1];\n let computed = this.computeWrapping(target);\n this.wrapCache.push(target, computed);\n return computed;\n }\n /**\n @internal\n */\n computeWrapping(target) {\n let seen = Object.create(null), active = [{ match: this, type: null, via: null }];\n while (active.length) {\n let current = active.shift(), match = current.match;\n if (match.matchType(target)) {\n let result = [];\n for (let obj = current; obj.type; obj = obj.via)\n result.push(obj.type);\n return result.reverse();\n }\n for (let i = 0; i < match.next.length; i++) {\n let { type, next } = match.next[i];\n if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {\n active.push({ match: type.contentMatch, type, via: current });\n seen[type.name] = true;\n }\n }\n }\n return null;\n }\n /**\n The number of outgoing edges this node has in the finite\n automaton that describes the content expression.\n */\n get edgeCount() {\n return this.next.length;\n }\n /**\n Get the _n_​th outgoing edge from this node in the finite\n automaton that describes the content expression.\n */\n edge(n) {\n if (n >= this.next.length)\n throw new RangeError(`There's no ${n}th edge in this content match`);\n return this.next[n];\n }\n /**\n @internal\n */\n toString() {\n let seen = [];\n function scan(m) {\n seen.push(m);\n for (let i = 0; i < m.next.length; i++)\n if (seen.indexOf(m.next[i].next) == -1)\n scan(m.next[i].next);\n }\n scan(this);\n return seen.map((m, i) => {\n let out = i + (m.validEnd ? \"*\" : \" \") + \" \";\n for (let i = 0; i < m.next.length; i++)\n out += (i ? \", \" : \"\") + m.next[i].type.name + \"->\" + seen.indexOf(m.next[i].next);\n return out;\n }).join(\"\\n\");\n }\n}\n/**\n@internal\n*/\nContentMatch.empty = new ContentMatch(true);\nclass TokenStream {\n constructor(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] == \"\")\n this.tokens.pop();\n if (this.tokens[0] == \"\")\n this.tokens.shift();\n }\n get next() { return this.tokens[this.pos]; }\n eat(tok) { return this.next == tok && (this.pos++ || true); }\n err(str) { throw new SyntaxError(str + \" (in content expression '\" + this.string + \"')\"); }\n}\nfunction parseExpr(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSeq(stream));\n } while (stream.eat(\"|\"));\n return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n}\nfunction parseExprSeq(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSubscript(stream));\n } while (stream.next && stream.next != \")\" && stream.next != \"|\");\n return exprs.length == 1 ? exprs[0] : { type: \"seq\", exprs };\n}\nfunction parseExprSubscript(stream) {\n let expr = parseExprAtom(stream);\n for (;;) {\n if (stream.eat(\"+\"))\n expr = { type: \"plus\", expr };\n else if (stream.eat(\"*\"))\n expr = { type: \"star\", expr };\n else if (stream.eat(\"?\"))\n expr = { type: \"opt\", expr };\n else if (stream.eat(\"{\"))\n expr = parseExprRange(stream, expr);\n else\n break;\n }\n return expr;\n}\nfunction parseNum(stream) {\n if (/\\D/.test(stream.next))\n stream.err(\"Expected number, got '\" + stream.next + \"'\");\n let result = Number(stream.next);\n stream.pos++;\n return result;\n}\nfunction parseExprRange(stream, expr) {\n let min = parseNum(stream), max = min;\n if (stream.eat(\",\")) {\n if (stream.next != \"}\")\n max = parseNum(stream);\n else\n max = -1;\n }\n if (!stream.eat(\"}\"))\n stream.err(\"Unclosed braced range\");\n return { type: \"range\", min, max, expr };\n}\nfunction resolveName(stream, name) {\n let types = stream.nodeTypes, type = types[name];\n if (type)\n return [type];\n let result = [];\n for (let typeName in types) {\n let type = types[typeName];\n if (type.isInGroup(name))\n result.push(type);\n }\n if (result.length == 0)\n stream.err(\"No node type or group '\" + name + \"' found\");\n return result;\n}\nfunction parseExprAtom(stream) {\n if (stream.eat(\"(\")) {\n let expr = parseExpr(stream);\n if (!stream.eat(\")\"))\n stream.err(\"Missing closing paren\");\n return expr;\n }\n else if (!/\\W/.test(stream.next)) {\n let exprs = resolveName(stream, stream.next).map(type => {\n if (stream.inline == null)\n stream.inline = type.isInline;\n else if (stream.inline != type.isInline)\n 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 };\n }\n else {\n stream.err(\"Unexpected token '\" + stream.next + \"'\");\n }\n}\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 let nfa = [[]];\n connect(compile(expr, 0), node());\n return nfa;\n function node() { return nfa.push([]) - 1; }\n function edge(from, to, term) {\n let edge = { term, to };\n nfa[from].push(edge);\n return edge;\n }\n function connect(edges, to) {\n edges.forEach(edge => edge.to = to);\n }\n function compile(expr, from) {\n if (expr.type == \"choice\") {\n return expr.exprs.reduce((out, expr) => out.concat(compile(expr, from)), []);\n }\n else if (expr.type == \"seq\") {\n for (let i = 0;; i++) {\n let next = compile(expr.exprs[i], from);\n if (i == expr.exprs.length - 1)\n return next;\n connect(next, from = node());\n }\n }\n else if (expr.type == \"star\") {\n let loop = node();\n edge(from, loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n }\n else if (expr.type == \"plus\") {\n let loop = node();\n connect(compile(expr.expr, from), loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n }\n else if (expr.type == \"opt\") {\n return [edge(from)].concat(compile(expr.expr, from));\n }\n else if (expr.type == \"range\") {\n let cur = from;\n for (let i = 0; i < expr.min; i++) {\n let next = node();\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n if (expr.max == -1) {\n connect(compile(expr.expr, cur), cur);\n }\n else {\n for (let i = expr.min; i < expr.max; i++) {\n let next = node();\n edge(cur, next);\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n }\n return [edge(cur)];\n }\n else if (expr.type == \"name\") {\n return [edge(from, undefined, expr.value)];\n }\n else {\n throw new Error(\"Unknown expr type\");\n }\n }\n}\nfunction cmp(a, b) { return b - a; }\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 let result = [];\n scan(node);\n return result.sort(cmp);\n function scan(node) {\n let edges = nfa[node];\n if (edges.length == 1 && !edges[0].term)\n return scan(edges[0].to);\n result.push(node);\n for (let i = 0; i < edges.length; i++) {\n let { term, to } = edges[i];\n if (!term && result.indexOf(to) == -1)\n scan(to);\n }\n }\n}\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 let labeled = Object.create(null);\n return explore(nullFrom(nfa, 0));\n function explore(states) {\n let out = [];\n states.forEach(node => {\n nfa[node].forEach(({ term, to }) => {\n if (!term)\n return;\n let set;\n for (let i = 0; i < out.length; i++)\n if (out[i][0] == term)\n set = out[i][1];\n nullFrom(nfa, to).forEach(node => {\n if (!set)\n out.push([term, set = []]);\n if (set.indexOf(node) == -1)\n set.push(node);\n });\n });\n });\n let state = labeled[states.join(\",\")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1);\n for (let i = 0; i < out.length; i++) {\n let states = out[i][1].sort(cmp);\n state.next.push({ type: out[i][0], next: labeled[states.join(\",\")] || explore(states) });\n }\n return state;\n }\n}\nfunction checkForDeadEnds(match, stream) {\n for (let i = 0, work = [match]; i < work.length; i++) {\n let state = work[i], dead = !state.validEnd, nodes = [];\n for (let j = 0; j < state.next.length; j++) {\n let { type, next } = state.next[j];\n nodes.push(type.name);\n if (dead && !(type.isText || type.hasRequiredAttrs()))\n dead = false;\n if (work.indexOf(next) == -1)\n work.push(next);\n }\n if (dead)\n 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 let defaults = Object.create(null);\n for (let attrName in attrs) {\n let attr = attrs[attrName];\n if (!attr.hasDefault)\n return null;\n defaults[attrName] = attr.default;\n }\n return defaults;\n}\nfunction computeAttrs(attrs, value) {\n let built = Object.create(null);\n for (let name in attrs) {\n let attr = attrs[name];\n let given = value && value[name];\n if (given === undefined) {\n if (attr.hasDefault)\n given = attr.default;\n else\n throw new RangeError(\"No value supplied for attribute \" + name);\n }\n else if (attr.validate) {\n attr.validate(given);\n }\n built[name] = given;\n }\n return built;\n}\nfunction initAttrs(typeName, attrs) {\n let result = Object.create(null);\n if (attrs)\n for (let name in attrs)\n result[name] = new Attribute(typeName, name, attrs[name]);\n return result;\n}\n/**\nNode types are objects allocated once per `Schema` and used to\n[tag](https://prosemirror.net/docs/ref/#model.Node.type) `Node` instances. They contain information\nabout the node type, such as its name and what kind of node it\nrepresents.\n*/\nclass NodeType {\n /**\n @internal\n */\n constructor(\n /**\n The name the node type has in this schema.\n */\n name, \n /**\n A link back to the `Schema` the node type belongs to.\n */\n schema, \n /**\n The spec that this type is based on\n */\n spec) {\n this.name = name;\n this.schema = schema;\n this.spec = spec;\n /**\n The set of marks allowed in this node. `null` means all marks\n are allowed.\n */\n this.markSet = null;\n this.groups = spec.group ? spec.group.split(\" \") : [];\n this.attrs = initAttrs(name, spec.attrs);\n this.defaultAttrs = defaultAttrs(this.attrs);\n this.contentMatch = null;\n this.inlineContent = null;\n this.isBlock = !(spec.inline || name == \"text\");\n this.isText = name == \"text\";\n }\n /**\n True if this is an inline type.\n */\n get isInline() { return !this.isBlock; }\n /**\n True if this is a textblock type, a block that contains inline\n content.\n */\n get isTextblock() { return this.isBlock && this.inlineContent; }\n /**\n True for node types that allow no content.\n */\n get isLeaf() { return this.contentMatch == ContentMatch.empty; }\n /**\n True when this node is an atom, i.e. when it does not have\n directly editable content.\n */\n get isAtom() { return this.isLeaf || !!this.spec.atom; }\n /**\n Return true when this node type is part of the given\n [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).\n */\n isInGroup(group) {\n return this.groups.indexOf(group) > -1;\n }\n /**\n The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.\n */\n get whitespace() {\n return this.spec.whitespace || (this.spec.code ? \"pre\" : \"normal\");\n }\n /**\n Tells you whether this node type has any required attributes.\n */\n hasRequiredAttrs() {\n for (let n in this.attrs)\n if (this.attrs[n].isRequired)\n return true;\n return false;\n }\n /**\n Indicates whether this node allows some of the same content as\n the given node type.\n */\n compatibleContent(other) {\n return this == other || this.contentMatch.compatible(other.contentMatch);\n }\n /**\n @internal\n */\n computeAttrs(attrs) {\n if (!attrs && this.defaultAttrs)\n return this.defaultAttrs;\n else\n return computeAttrs(this.attrs, attrs);\n }\n /**\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.\n */\n create(attrs = null, content, marks) {\n if (this.isText)\n 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 Like [`create`](https://prosemirror.net/docs/ref/#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.\n */\n createChecked(attrs = null, content, marks) {\n content = Fragment.from(content);\n this.checkContent(content);\n return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));\n }\n /**\n Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is\n necessary to add nodes to the start or end of the given fragment\n to make it fit the node. If no fitting wrapping can be found,\n return null. Note that, due to the fact that required nodes can\n always be created, this will always succeed if you pass null or\n `Fragment.empty` as content.\n */\n createAndFill(attrs = null, content, marks) {\n attrs = this.computeAttrs(attrs);\n content = Fragment.from(content);\n if (content.size) {\n let before = this.contentMatch.fillBefore(content);\n if (!before)\n return null;\n content = before.append(content);\n }\n let matched = this.contentMatch.matchFragment(content);\n let after = matched && matched.fillBefore(Fragment.empty, true);\n if (!after)\n return null;\n return new Node(this, attrs, content.append(after), Mark.setFrom(marks));\n }\n /**\n Returns true if the given fragment is valid content for this node\n type.\n */\n validContent(content) {\n let result = this.contentMatch.matchFragment(content);\n if (!result || !result.validEnd)\n return false;\n for (let i = 0; i < content.childCount; i++)\n if (!this.allowsMarks(content.child(i).marks))\n return false;\n return true;\n }\n /**\n Throws a RangeError if the given fragment is not valid content for this\n node type.\n @internal\n */\n checkContent(content) {\n if (!this.validContent(content))\n throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);\n }\n /**\n @internal no longer useful, but called by old prosemirror-view versions\n */\n checkAttrs(attrs) { }\n /**\n Check whether the given mark type is allowed in this node.\n */\n allowsMarkType(markType) {\n return this.markSet == null || this.markSet.indexOf(markType) > -1;\n }\n /**\n Test whether the given set of marks are allowed in this node.\n */\n allowsMarks(marks) {\n if (this.markSet == null)\n return true;\n for (let i = 0; i < marks.length; i++)\n if (!this.allowsMarkType(marks[i].type))\n return false;\n return true;\n }\n /**\n Removes the marks that are not allowed in this node from the given set.\n */\n allowedMarks(marks) {\n if (this.markSet == null)\n return marks;\n let copy;\n for (let i = 0; i < marks.length; i++) {\n if (!this.allowsMarkType(marks[i].type)) {\n if (!copy)\n copy = marks.slice(0, i);\n }\n else if (copy) {\n copy.push(marks[i]);\n }\n }\n return !copy ? marks : copy.length ? copy : Mark.none;\n }\n /**\n @internal\n */\n static compile(nodes, schema) {\n let result = Object.create(null);\n nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec));\n let topType = schema.spec.topNode || \"doc\";\n if (!result[topType])\n throw new RangeError(\"Schema is missing its top node type ('\" + topType + \"')\");\n if (!result.text)\n throw new RangeError(\"Every schema needs a 'text' type\");\n for (let _ in result.text.attrs)\n throw new RangeError(\"The text node type should not have attributes\");\n return result;\n }\n}\nfunction validateType(typeName, attrName, type) {\n let types = type.split(\"|\");\n return (value) => {\n let name = value === null ? \"null\" : typeof value;\n if (types.indexOf(name) < 0)\n throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);\n };\n}\n// Attribute descriptors\nclass Attribute {\n constructor(typeName, attrName, options) {\n this.hasDefault = Object.prototype.hasOwnProperty.call(options, \"default\");\n this.default = options.default;\n this.validate = typeof options.validate == \"string\" ? validateType(typeName, attrName, options.validate) : options.validate;\n }\n get isRequired() {\n return !this.hasDefault;\n }\n}\n// Marks\n/**\nLike nodes, marks (which are associated with nodes to signify\nthings like emphasis or being part of a link) are\n[tagged](https://prosemirror.net/docs/ref/#model.Mark.type) with type objects, which are\ninstantiated once per `Schema`.\n*/\nclass MarkType {\n /**\n @internal\n */\n constructor(\n /**\n The name of the mark type.\n */\n name, \n /**\n @internal\n */\n rank, \n /**\n The schema that this mark type instance is part of.\n */\n schema, \n /**\n The spec on which the type is based.\n */\n spec) {\n this.name = name;\n this.rank = rank;\n this.schema = schema;\n this.spec = spec;\n this.attrs = initAttrs(name, spec.attrs);\n this.excluded = null;\n let defaults = defaultAttrs(this.attrs);\n this.instance = defaults ? new Mark(this, defaults) : null;\n }\n /**\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.\n */\n create(attrs = null) {\n if (!attrs && this.instance)\n return this.instance;\n return new Mark(this, computeAttrs(this.attrs, attrs));\n }\n /**\n @internal\n */\n static compile(marks, schema) {\n let result = Object.create(null), rank = 0;\n marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec));\n return result;\n }\n /**\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.\n */\n removeFromSet(set) {\n for (var i = 0; i < set.length; i++)\n if (set[i].type == this) {\n set = set.slice(0, i).concat(set.slice(i + 1));\n i--;\n }\n return set;\n }\n /**\n Tests whether there is a mark of this type in the given set.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++)\n if (set[i].type == this)\n return set[i];\n }\n /**\n Queries whether a given mark type is\n [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.\n */\n excludes(other) {\n return this.excluded.indexOf(other) > -1;\n }\n}\n/**\nA document schema. Holds [node](https://prosemirror.net/docs/ref/#model.NodeType) and [mark\ntype](https://prosemirror.net/docs/ref/#model.MarkType) objects for the nodes and marks that may\noccur in conforming documents, and provides functionality for\ncreating and deserializing such documents.\n\nWhen given, the type parameters provide the names of the nodes and\nmarks in this schema.\n*/\nclass Schema {\n /**\n Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).\n */\n constructor(spec) {\n /**\n The [linebreak\n replacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement) node defined\n in this schema, if any.\n */\n this.linebreakReplacement = null;\n /**\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 */\n this.cached = Object.create(null);\n let instanceSpec = this.spec = {};\n for (let prop in spec)\n instanceSpec[prop] = spec[prop];\n instanceSpec.nodes = OrderedMap.from(spec.nodes),\n instanceSpec.marks = OrderedMap.from(spec.marks || {}),\n this.nodes = NodeType.compile(this.spec.nodes, this);\n this.marks = MarkType.compile(this.spec.marks, this);\n let contentExprCache = Object.create(null);\n for (let prop in this.nodes) {\n if (prop in this.marks)\n throw new RangeError(prop + \" can not be both a node and a mark\");\n let type = this.nodes[prop], 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 if (type.spec.linebreakReplacement) {\n if (this.linebreakReplacement)\n throw new RangeError(\"Multiple linebreak nodes defined\");\n if (!type.isInline || !type.isLeaf)\n throw new RangeError(\"Linebreak replacement nodes must be inline leaf nodes\");\n this.linebreakReplacement = type;\n }\n type.markSet = markExpr == \"_\" ? null :\n markExpr ? gatherMarks(this, markExpr.split(\" \")) :\n markExpr == \"\" || !type.inlineContent ? [] : null;\n }\n for (let prop in this.marks) {\n let type = this.marks[prop], excl = type.spec.excludes;\n type.excluded = excl == null ? [type] : excl == \"\" ? [] : gatherMarks(this, excl.split(\" \"));\n }\n this.nodeFromJSON = json => Node.fromJSON(this, json);\n this.markFromJSON = json => Mark.fromJSON(this, json);\n this.topNodeType = this.nodes[this.spec.topNode || \"doc\"];\n this.cached.wrappings = Object.create(null);\n }\n /**\n Create a node in this schema. The `type` may be a string or a\n `NodeType` instance. Attributes will be extended with defaults,\n `content` may be a `Fragment`, `null`, a `Node`, or an array of\n nodes.\n */\n node(type, attrs = null, 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 return type.createChecked(attrs, content, marks);\n }\n /**\n Create a text node in the schema. Empty text nodes are not\n allowed.\n */\n text(text, marks) {\n let type = this.nodes.text;\n return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks));\n }\n /**\n Create a mark with the given type and attributes.\n */\n mark(type, attrs) {\n if (typeof type == \"string\")\n type = this.marks[type];\n return type.create(attrs);\n }\n /**\n @internal\n */\n nodeType(name) {\n let found = this.nodes[name];\n if (!found)\n throw new RangeError(\"Unknown node type: \" + name);\n return found;\n }\n}\nfunction gatherMarks(schema, marks) {\n let found = [];\n for (let i = 0; i < marks.length; i++) {\n let name = marks[i], mark = schema.marks[name], ok = mark;\n if (mark) {\n found.push(mark);\n }\n else {\n for (let prop in schema.marks) {\n let mark = schema.marks[prop];\n if (name == \"_\" || (mark.spec.group && mark.spec.group.split(\" \").indexOf(name) > -1))\n found.push(ok = mark);\n }\n }\n if (!ok)\n throw new SyntaxError(\"Unknown mark type: '\" + marks[i] + \"'\");\n }\n return found;\n}\n\nfunction isTagRule(rule) { return rule.tag != null; }\nfunction isStyleRule(rule) { return rule.style != null; }\n/**\nA DOM parser represents a strategy for parsing DOM content into a\nProseMirror document conforming to a given schema. Its behavior is\ndefined by an array of [rules](https://prosemirror.net/docs/ref/#model.ParseRule).\n*/\nclass DOMParser {\n /**\n Create a parser that targets the given schema, using the given\n parsing rules.\n */\n constructor(\n /**\n The schema into which the parser parses.\n */\n schema, \n /**\n The set of [parse rules](https://prosemirror.net/docs/ref/#model.ParseRule) that the parser\n uses, in order of precedence.\n */\n rules) {\n this.schema = schema;\n this.rules = rules;\n /**\n @internal\n */\n this.tags = [];\n /**\n @internal\n */\n this.styles = [];\n let matchedStyles = this.matchedStyles = [];\n rules.forEach(rule => {\n if (isTagRule(rule)) {\n this.tags.push(rule);\n }\n else if (isStyleRule(rule)) {\n let prop = /[^=]*/.exec(rule.style)[0];\n if (matchedStyles.indexOf(prop) < 0)\n matchedStyles.push(prop);\n this.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(r => {\n if (!/^(ul|ol)\\b/.test(r.tag) || !r.node)\n return false;\n let node = schema.nodes[r.node];\n return node.contentMatch.matchType(node);\n });\n }\n /**\n Parse a document from the content of a DOM node.\n */\n parse(dom, options = {}) {\n let context = new ParseContext(this, options, false);\n context.addAll(dom, Mark.none, options.from, options.to);\n return context.finish();\n }\n /**\n Parses the content of the given DOM node, like\n [`parse`](https://prosemirror.net/docs/ref/#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.\n */\n parseSlice(dom, options = {}) {\n let context = new ParseContext(this, options, true);\n context.addAll(dom, Mark.none, options.from, options.to);\n return Slice.maxOpen(context.finish());\n }\n /**\n @internal\n */\n matchTag(dom, context, after) {\n for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) {\n let 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 let result = rule.getAttrs(dom);\n if (result === false)\n continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n }\n /**\n @internal\n */\n matchStyle(prop, value, context, after) {\n for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) {\n let rule = this.styles[i], style = rule.style;\n if (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 style.length > prop.length &&\n (style.charCodeAt(prop.length) != 61 || style.slice(prop.length + 1) != value))\n continue;\n if (rule.getAttrs) {\n let result = rule.getAttrs(value);\n if (result === false)\n continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n /**\n @internal\n */\n static schemaRules(schema) {\n let result = [];\n function insert(rule) {\n let priority = rule.priority == null ? 50 : rule.priority, i = 0;\n for (; i < result.length; i++) {\n let next = result[i], nextPriority = next.priority == null ? 50 : next.priority;\n if (nextPriority < priority)\n break;\n }\n result.splice(i, 0, rule);\n }\n for (let name in schema.marks) {\n let rules = schema.marks[name].spec.parseDOM;\n if (rules)\n rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.mark || rule.ignore || rule.clearMark))\n rule.mark = name;\n });\n }\n for (let name in schema.nodes) {\n let rules = schema.nodes[name].spec.parseDOM;\n if (rules)\n rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.node || rule.ignore || rule.mark))\n rule.node = name;\n });\n }\n return result;\n }\n /**\n Construct a DOM parser using the parsing rules listed in a\n schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by\n [priority](https://prosemirror.net/docs/ref/#model.GenericParseRule.priority).\n */\n static fromSchema(schema) {\n return schema.cached.domParser ||\n (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema)));\n }\n}\nconst blockTags = {\n address: true, article: true, aside: true, blockquote: true, body: 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};\nconst ignoreTags = {\n head: true, noscript: true, object: true, script: true, style: true, title: true\n};\nconst listTags = { ol: true, ul: true };\n// Using a bitfield for node context options\nconst OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4;\nfunction wsOptionsFor(type, preserveWhitespace, base) {\n if (preserveWhitespace != null)\n return (preserveWhitespace ? OPT_PRESERVE_WS : 0) |\n (preserveWhitespace === \"full\" ? OPT_PRESERVE_WS_FULL : 0);\n return type && type.whitespace == \"pre\" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base & ~OPT_OPEN_LEFT;\n}\nclass NodeContext {\n constructor(type, attrs, marks, solid, match, options) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.solid = solid;\n this.options = options;\n this.content = [];\n // Marks applied to the node's children\n this.activeMarks = Mark.none;\n this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);\n }\n findWrapping(node) {\n if (!this.match) {\n if (!this.type)\n return [];\n let fill = this.type.contentMatch.fillBefore(Fragment.from(node));\n if (fill) {\n this.match = this.type.contentMatch.matchFragment(fill);\n }\n else {\n let start = this.type.contentMatch, wrap;\n if (wrap = start.findWrapping(node.type)) {\n this.match = start;\n return wrap;\n }\n else {\n return null;\n }\n }\n }\n return this.match.findWrapping(node.type);\n }\n finish(openEnd) {\n if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace\n let last = this.content[this.content.length - 1], m;\n if (last && last.isText && (m = /[ \\t\\r\\n\\u000c]+$/.exec(last.text))) {\n let text = last;\n if (last.text.length == m[0].length)\n this.content.pop();\n else\n this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length));\n }\n }\n let 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 inlineContext(node) {\n if (this.type)\n return this.type.inlineContent;\n if (this.content.length)\n return this.content[0].isInline;\n return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());\n }\n}\nclass ParseContext {\n constructor(\n // The parser we are using.\n parser, \n // The options passed to this parse.\n options, isOpen) {\n this.parser = parser;\n this.options = options;\n this.isOpen = isOpen;\n this.open = 0;\n this.localPreserveWS = false;\n let topNode = options.topNode, topContext;\n let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);\n if (topNode)\n topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);\n else if (isOpen)\n topContext = new NodeContext(null, null, Mark.none, true, null, topOptions);\n else\n topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions);\n this.nodes = [topContext];\n this.find = options.findPositions;\n this.needsBlock = false;\n }\n get top() {\n return this.nodes[this.open];\n }\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`.\n addDOM(dom, marks) {\n if (dom.nodeType == 3)\n this.addTextNode(dom, marks);\n else if (dom.nodeType == 1)\n this.addElement(dom, marks);\n }\n addTextNode(dom, marks) {\n let value = dom.nodeValue;\n let top = this.top, preserveWS = (top.options & OPT_PRESERVE_WS_FULL) ? \"full\"\n : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0;\n let { schema } = this.parser;\n if (preserveWS === \"full\" ||\n top.inlineContext(dom) ||\n /[^ \\t\\r\\n\\u000c]/.test(value)) {\n if (!preserveWS) {\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 let nodeBefore = top.content[top.content.length - 1];\n let 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 }\n else if (preserveWS === \"full\") {\n value = value.replace(/\\r\\n?/g, \"\\n\");\n }\n else if (schema.linebreakReplacement && /[\\r\\n]/.test(value) && this.top.findWrapping(schema.linebreakReplacement.create())) {\n let lines = value.split(/\\r?\\n|\\r/);\n for (let i = 0; i < lines.length; i++) {\n if (i)\n this.insertNode(schema.linebreakReplacement.create(), marks, true);\n if (lines[i])\n this.insertNode(schema.text(lines[i]), marks, !/\\S/.test(lines[i]));\n }\n value = \"\";\n }\n else {\n value = value.replace(/\\r?\\n|\\r/g, \" \");\n }\n if (value)\n this.insertNode(schema.text(value), marks, !/\\S/.test(value));\n this.findInText(dom);\n }\n else {\n this.findInside(dom);\n }\n }\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.\n addElement(dom, marks, matchAfter) {\n let outerWS = this.localPreserveWS, top = this.top;\n if (dom.tagName == \"PRE\" || /pre/.test(dom.style && dom.style.whiteSpace))\n this.localPreserveWS = true;\n let name = dom.nodeName.toLowerCase(), ruleID;\n if (listTags.hasOwnProperty(name) && this.parser.normalizeLists)\n normalizeList(dom);\n let rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) ||\n (ruleID = this.parser.matchTag(dom, this, matchAfter));\n out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {\n this.findInside(dom);\n this.ignoreFallback(dom, marks);\n }\n else if (!rule || rule.skip || rule.closeParent) {\n if (rule && rule.closeParent)\n this.open = Math.max(0, this.open - 1);\n else if (rule && rule.skip.nodeType)\n dom = rule.skip;\n let sync, oldNeedsBlock = this.needsBlock;\n if (blockTags.hasOwnProperty(name)) {\n if (top.content.length && top.content[0].isInline && this.open) {\n this.open--;\n top = this.top;\n }\n sync = true;\n if (!top.type)\n this.needsBlock = true;\n }\n else if (!dom.firstChild) {\n this.leafFallback(dom, marks);\n break out;\n }\n let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);\n if (innerMarks)\n this.addAll(dom, innerMarks);\n if (sync)\n this.sync(top);\n this.needsBlock = oldNeedsBlock;\n }\n else {\n let innerMarks = this.readStyles(dom, marks);\n if (innerMarks)\n this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : undefined);\n }\n this.localPreserveWS = outerWS;\n }\n // Called for leaf DOM nodes that would otherwise be ignored\n leafFallback(dom, marks) {\n if (dom.nodeName == \"BR\" && this.top.type && this.top.type.inlineContent)\n this.addTextNode(dom.ownerDocument.createTextNode(\"\\n\"), marks);\n }\n // Called for ignored nodes\n ignoreFallback(dom, marks) {\n // Ignored BR nodes should at least create an inline context\n if (dom.nodeName == \"BR\" && (!this.top.type || !this.top.type.inlineContent))\n this.findPlace(this.parser.schema.text(\"-\"), marks, true);\n }\n // Run any style parser associated with the node's styles. Either\n // return an updated array of marks, or null to indicate some of the\n // styles had a rule with `ignore` set.\n readStyles(dom, marks) {\n let styles = dom.style;\n // Because many properties will only show up in 'normalized' form\n // in `style.item` (i.e. text-decoration becomes\n // text-decoration-line, text-decoration-color, etc), we directly\n // query the styles mentioned in our rules instead of iterating\n // over the items.\n if (styles && styles.length)\n for (let i = 0; i < this.parser.matchedStyles.length; i++) {\n let name = this.parser.matchedStyles[i], value = styles.getPropertyValue(name);\n if (value)\n for (let after = undefined;;) {\n let rule = this.parser.matchStyle(name, value, this, after);\n if (!rule)\n break;\n if (rule.ignore)\n return null;\n if (rule.clearMark)\n marks = marks.filter(m => !rule.clearMark(m));\n else\n marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));\n if (rule.consuming === false)\n after = rule;\n else\n break;\n }\n }\n return marks;\n }\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.\n addElementByRule(dom, rule, marks, continueAfter) {\n let sync, nodeType;\n if (rule.node) {\n nodeType = this.parser.schema.nodes[rule.node];\n if (!nodeType.isLeaf) {\n let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);\n if (inner) {\n sync = true;\n marks = inner;\n }\n }\n else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == \"BR\")) {\n this.leafFallback(dom, marks);\n }\n }\n else {\n let markType = this.parser.schema.marks[rule.mark];\n marks = marks.concat(markType.create(rule.attrs));\n }\n let startIn = this.top;\n if (nodeType && nodeType.isLeaf) {\n this.findInside(dom);\n }\n else if (continueAfter) {\n this.addElement(dom, marks, continueAfter);\n }\n else if (rule.getContent) {\n this.findInside(dom);\n rule.getContent(dom, this.parser.schema).forEach(node => this.insertNode(node, marks, false));\n }\n else {\n let contentDOM = dom;\n if (typeof rule.contentElement == \"string\")\n contentDOM = dom.querySelector(rule.contentElement);\n else if (typeof rule.contentElement == \"function\")\n contentDOM = rule.contentElement(dom);\n else if (rule.contentElement)\n contentDOM = rule.contentElement;\n this.findAround(dom, contentDOM, true);\n this.addAll(contentDOM, marks);\n this.findAround(dom, contentDOM, false);\n }\n if (sync && this.sync(startIn))\n this.open--;\n }\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.\n addAll(parent, marks, startIndex, endIndex) {\n let index = startIndex || 0;\n for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {\n this.findAtPoint(parent, index);\n this.addDOM(dom, marks);\n }\n this.findAtPoint(parent, index);\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.\n findPlace(node, marks, cautious) {\n let route, sync;\n for (let depth = this.open, penalty = 0; depth >= 0; depth--) {\n let cx = this.nodes[depth];\n let found = cx.findWrapping(node);\n if (found && (!route || route.length > found.length + penalty)) {\n route = found;\n sync = cx;\n if (!found.length)\n break;\n }\n if (cx.solid) {\n if (cautious)\n break;\n penalty += 2;\n }\n }\n if (!route)\n return null;\n this.sync(sync);\n for (let i = 0; i < route.length; i++)\n marks = this.enterInner(route[i], null, marks, false);\n return marks;\n }\n // Try to insert the given node, adjusting the context when needed.\n insertNode(node, marks, cautious) {\n if (node.isInline && this.needsBlock && !this.top.type) {\n let block = this.textblockFromContext();\n if (block)\n marks = this.enterInner(block, null, marks);\n }\n let innerMarks = this.findPlace(node, marks, cautious);\n if (innerMarks) {\n this.closeExtra();\n let top = this.top;\n if (top.match)\n top.match = top.match.matchType(node.type);\n let nodeMarks = Mark.none;\n for (let m of innerMarks.concat(node.marks))\n if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type))\n nodeMarks = m.addToSet(nodeMarks);\n top.content.push(node.mark(nodeMarks));\n return true;\n }\n return false;\n }\n // Try to start a node of the given type, adjusting the context when\n // necessary.\n enter(type, attrs, marks, preserveWS) {\n let innerMarks = this.findPlace(type.create(attrs), marks, false);\n if (innerMarks)\n innerMarks = this.enterInner(type, attrs, marks, true, preserveWS);\n return innerMarks;\n }\n // Open a node of the given type\n enterInner(type, attrs, marks, solid = false, preserveWS) {\n this.closeExtra();\n let top = this.top;\n top.match = top.match && top.match.matchType(type);\n let options = wsOptionsFor(type, preserveWS, top.options);\n if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0)\n options |= OPT_OPEN_LEFT;\n let applyMarks = Mark.none;\n marks = marks.filter(m => {\n if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) {\n applyMarks = m.addToSet(applyMarks);\n return false;\n }\n return true;\n });\n this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options));\n this.open++;\n return marks;\n }\n // Make sure all nodes above this.open are finished and added to\n // their parents\n closeExtra(openEnd = false) {\n let i = this.nodes.length - 1;\n if (i > this.open) {\n for (; i > this.open; i--)\n this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));\n this.nodes.length = this.open + 1;\n }\n }\n finish() {\n this.open = 0;\n this.closeExtra(this.isOpen);\n return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));\n }\n sync(to) {\n for (let i = this.open; i >= 0; i--) {\n if (this.nodes[i] == to) {\n this.open = i;\n return true;\n }\n else if (this.localPreserveWS) {\n this.nodes[i].options |= OPT_PRESERVE_WS;\n }\n }\n return false;\n }\n get currentPos() {\n this.closeExtra();\n let pos = 0;\n for (let i = this.open; i >= 0; i--) {\n let content = this.nodes[i].content;\n for (let j = content.length - 1; j >= 0; j--)\n pos += content[j].nodeSize;\n if (i)\n pos++;\n }\n return pos;\n }\n findAtPoint(parent, offset) {\n if (this.find)\n for (let 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 findInside(parent) {\n if (this.find)\n for (let 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 findAround(parent, content, before) {\n if (parent != content && this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {\n let pos = content.compareDocumentPosition(this.find[i].node);\n if (pos & (before ? 2 : 4))\n this.find[i].pos = this.currentPos;\n }\n }\n }\n findInText(textNode) {\n if (this.find)\n for (let 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 // Determines whether the given context string matches this context.\n matchesContext(context) {\n if (context.indexOf(\"|\") > -1)\n return context.split(/\\s*\\|\\s*/).some(this.matchesContext, this);\n let parts = context.split(\"/\");\n let option = this.options.context;\n let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);\n let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);\n let match = (i, depth) => {\n for (; i >= 0; i--) {\n let part = parts[i];\n if (part == \"\") {\n if (i == parts.length - 1 || i == 0)\n continue;\n for (; depth >= minDepth; depth--)\n if (match(i - 1, depth))\n return true;\n return false;\n }\n else {\n let next = depth > 0 || (depth == 0 && useRoot) ? this.nodes[depth].type\n : option && depth >= minDepth ? option.node(depth - minDepth).type\n : null;\n if (!next || (next.name != part && !next.isInGroup(part)))\n return false;\n depth--;\n }\n }\n return true;\n };\n return match(parts.length - 1, this.open);\n }\n textblockFromContext() {\n let $context = this.options.context;\n if ($context)\n for (let d = $context.depth; d >= 0; d--) {\n let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;\n if (deflt && deflt.isTextblock && deflt.defaultAttrs)\n return deflt;\n }\n for (let name in this.parser.schema.nodes) {\n let type = this.parser.schema.nodes[name];\n if (type.isTextblock && type.defaultAttrs)\n return type;\n }\n }\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 (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {\n let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;\n if (name && listTags.hasOwnProperty(name) && prevItem) {\n prevItem.appendChild(child);\n child = prevItem;\n }\n else if (name == \"li\") {\n prevItem = child;\n }\n else if (name) {\n prevItem = null;\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}\nfunction copy(obj) {\n let copy = {};\n for (let prop in obj)\n copy[prop] = obj[prop];\n return copy;\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 let nodes = nodeType.schema.nodes;\n for (let name in nodes) {\n let parent = nodes[name];\n if (!parent.allowsMarkType(markType))\n continue;\n let seen = [], scan = (match) => {\n seen.push(match);\n for (let i = 0; i < match.edgeCount; i++) {\n let { type, next } = match.edge(i);\n if (type == nodeType)\n return true;\n if (seen.indexOf(next) < 0 && scan(next))\n return true;\n }\n };\n if (scan(parent.contentMatch))\n return true;\n }\n}\n\n/**\nA DOM serializer knows how to convert ProseMirror nodes and\nmarks of various types to DOM nodes.\n*/\nclass DOMSerializer {\n /**\n Create a serializer. `nodes` should map node names to functions\n that take a node and return a description of the corresponding\n DOM. `marks` does the same for mark names, but also gets an\n argument that tells it whether the mark's content is block or\n inline content (for typical use, it'll always be inline). A mark\n serializer may be `null` to indicate that marks of that type\n should not be serialized.\n */\n constructor(\n /**\n The node serialization functions.\n */\n nodes, \n /**\n The mark serialization functions.\n */\n marks) {\n this.nodes = nodes;\n this.marks = marks;\n }\n /**\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.\n */\n serializeFragment(fragment, options = {}, target) {\n if (!target)\n target = doc(options).createDocumentFragment();\n let top = target, active = [];\n fragment.forEach(node => {\n if (active.length || node.marks.length) {\n let keep = 0, rendered = 0;\n while (keep < active.length && rendered < node.marks.length) {\n let next = node.marks[rendered];\n if (!this.marks[next.type.name]) {\n rendered++;\n continue;\n }\n if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)\n break;\n keep++;\n rendered++;\n }\n while (keep < active.length)\n top = active.pop()[1];\n while (rendered < node.marks.length) {\n let add = node.marks[rendered++];\n let markDOM = this.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.serializeNodeInner(node, options));\n });\n return target;\n }\n /**\n @internal\n */\n serializeNodeInner(node, options) {\n if (node.isText)\n return doc(options).createTextNode(node.text);\n let { dom, contentDOM } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs);\n if (contentDOM) {\n if (node.isLeaf)\n throw new RangeError(\"Content hole not allowed in a leaf node spec\");\n this.serializeFragment(node.content, options, contentDOM);\n }\n return dom;\n }\n /**\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`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on\n its [content](https://prosemirror.net/docs/ref/#model.Node.content).\n */\n serializeNode(node, options = {}) {\n let dom = this.serializeNodeInner(node, options);\n for (let i = node.marks.length - 1; i >= 0; i--) {\n let 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 /**\n @internal\n */\n serializeMark(mark, inline, options = {}) {\n let toDOM = this.marks[mark.type.name];\n return toDOM && renderSpec(doc(options), toDOM(mark, inline), null, mark.attrs);\n }\n static renderSpec(doc, structure, xmlNS = null, blockArraysIn) {\n // Kludge for backwards-compatibility with accidental original behavious\n if (typeof structure == \"string\")\n return { dom: doc.createTextNode(structure) };\n return renderSpec(doc, structure, xmlNS, blockArraysIn);\n }\n /**\n Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)\n properties in a schema's node and mark specs.\n */\n static fromSchema(schema) {\n return schema.cached.domSerializer ||\n (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));\n }\n /**\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.\n */\n static nodesFromSchema(schema) {\n let result = gatherToDOM(schema.nodes);\n if (!result.text)\n result.text = node => node.text;\n return result;\n }\n /**\n Gather the serializers in a schema's mark specs into an object.\n */\n static marksFromSchema(schema) {\n return gatherToDOM(schema.marks);\n }\n}\nfunction gatherToDOM(obj) {\n let result = {};\n for (let name in obj) {\n let toDOM = obj[name].spec.toDOM;\n if (toDOM)\n result[name] = toDOM;\n }\n return result;\n}\nfunction doc(options) {\n return options.document || window.document;\n}\nconst suspiciousAttributeCache = new WeakMap();\nfunction suspiciousAttributes(attrs) {\n let value = suspiciousAttributeCache.get(attrs);\n if (value === undefined)\n suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs));\n return value;\n}\nfunction suspiciousAttributesInner(attrs) {\n let result = null;\n function scan(value) {\n if (value && typeof value == \"object\") {\n if (Array.isArray(value)) {\n if (typeof value[0] == \"string\") {\n if (!result)\n result = [];\n result.push(value);\n }\n else {\n for (let i = 0; i < value.length; i++)\n scan(value[i]);\n }\n }\n else {\n for (let prop in value)\n scan(value[prop]);\n }\n }\n }\n scan(attrs);\n return result;\n}\nfunction renderSpec(doc, structure, xmlNS, blockArraysIn) {\n if (structure.nodeType == 1)\n return { dom: structure };\n if (structure.dom && structure.dom.nodeType == 1)\n return structure;\n let tagName = structure[0], suspicious;\n if (typeof tagName != \"string\")\n throw new RangeError(\"Invalid array passed to renderSpec\");\n if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) &&\n suspicious.indexOf(structure) > -1)\n throw new RangeError(\"Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.\");\n let space = tagName.indexOf(\" \");\n if (space > 0) {\n xmlNS = tagName.slice(0, space);\n tagName = tagName.slice(space + 1);\n }\n let contentDOM;\n let dom = (xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName));\n let attrs = structure[1], start = 1;\n if (attrs && typeof attrs == \"object\" && attrs.nodeType == null && !Array.isArray(attrs)) {\n start = 2;\n for (let name in attrs)\n if (attrs[name] != null) {\n let space = name.indexOf(\" \");\n if (space > 0)\n dom.setAttributeNS(name.slice(0, space), name.slice(space + 1), attrs[name]);\n else if (name == \"style\" && dom.style)\n dom.style.cssText = attrs[name];\n else\n dom.setAttribute(name, attrs[name]);\n }\n }\n for (let i = start; i < structure.length; i++) {\n let 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, contentDOM: dom };\n }\n else if (typeof child == \"string\") {\n dom.appendChild(doc.createTextNode(child));\n }\n else {\n let { dom: inner, contentDOM: innerContent } = renderSpec(doc, child, xmlNS, blockArraysIn);\n dom.appendChild(inner);\n if (innerContent) {\n if (contentDOM)\n throw new RangeError(\"Multiple content holes\");\n contentDOM = innerContent;\n }\n }\n }\n return { dom, contentDOM };\n}\n\nexport { ContentMatch, DOMParser, DOMSerializer, Fragment, Mark, MarkType, Node, NodeRange, NodeType, ReplaceError, ResolvedPos, Schema, Slice };\n", + "import { ReplaceError, Slice, Mark, Fragment, MarkType } from 'prosemirror-model';\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.\nconst lower16 = 0xffff;\nconst factor16 = Math.pow(2, 16);\nfunction makeRecover(index, offset) { return index + offset * factor16; }\nfunction recoverIndex(value) { return value & lower16; }\nfunction recoverOffset(value) { return (value - (value & lower16)) / factor16; }\nconst DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8;\n/**\nAn object representing a mapped position with extra\ninformation.\n*/\nclass MapResult {\n /**\n @internal\n */\n constructor(\n /**\n The mapped version of the position.\n */\n pos, \n /**\n @internal\n */\n delInfo, \n /**\n @internal\n */\n recover) {\n this.pos = pos;\n this.delInfo = delInfo;\n this.recover = recover;\n }\n /**\n Tells you whether the position was deleted, that is, whether the\n step removed the token on the side queried (via the `assoc`)\n argument from the document.\n */\n get deleted() { return (this.delInfo & DEL_SIDE) > 0; }\n /**\n Tells you whether the token before the mapped position was deleted.\n */\n get deletedBefore() { return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; }\n /**\n True when the token after the mapped position was deleted.\n */\n get deletedAfter() { return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; }\n /**\n Tells whether any of the steps mapped through deletes across the\n position (including both the token before and after the\n position).\n */\n get deletedAcross() { return (this.delInfo & DEL_ACROSS) > 0; }\n}\n/**\nA map describing the deletions and insertions made by a step, which\ncan be used to find the correspondence between positions in the\npre-step version of a document and the same position in the\npost-step version.\n*/\nclass StepMap {\n /**\n Create a position map. The modifications to the document are\n represented as an array of numbers, in which each group of three\n represents a modified chunk as `[start, oldSize, newSize]`.\n */\n constructor(\n /**\n @internal\n */\n ranges, \n /**\n @internal\n */\n inverted = false) {\n this.ranges = ranges;\n this.inverted = inverted;\n if (!ranges.length && StepMap.empty)\n return StepMap.empty;\n }\n /**\n @internal\n */\n recover(value) {\n let diff = 0, index = recoverIndex(value);\n if (!this.inverted)\n for (let 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 mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n map(pos, assoc = 1) { return this._map(pos, assoc, true); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;\n if (pos <= end) {\n let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;\n let result = start + diff + (side < 0 ? 0 : newSize);\n if (simple)\n return result;\n let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);\n let del = 0;\n if (oldSize) {\n del |= pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;\n if (assoc < 0 ? pos != start : pos != end)\n del |= DEL_SIDE;\n }\n return new MapResult(result, del, recover);\n }\n diff += newSize - oldSize;\n }\n return simple ? pos + diff : new MapResult(pos + diff, 0, null);\n }\n /**\n @internal\n */\n touches(pos, recover) {\n let diff = 0, index = recoverIndex(recover);\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], end = start + oldSize;\n if (pos <= end && i == index * 3)\n return true;\n diff += this.ranges[i + newIndex] - oldSize;\n }\n return false;\n }\n /**\n Calls the given function on each of the changed ranges included in\n this map.\n */\n forEach(f) {\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0, diff = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);\n let 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 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.\n */\n invert() {\n return new StepMap(this.ranges, !this.inverted);\n }\n /**\n @internal\n */\n toString() {\n return (this.inverted ? \"-\" : \"\") + JSON.stringify(this.ranges);\n }\n /**\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.\n */\n static offset(n) {\n return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);\n }\n}\n/**\nA StepMap that contains no changed ranges.\n*/\nStepMap.empty = new StepMap([]);\n/**\nA mapping represents a pipeline of zero or more [step\nmaps](https://prosemirror.net/docs/ref/#transform.StepMap). It has special provisions for losslessly\nhandling mapping positions through a series of steps in which some\nsteps are inverted versions of earlier steps. (This comes up when\n‘[rebasing](https://prosemirror.net/docs/guide/#transform.rebasing)’ steps for\ncollaboration or history management.)\n*/\nclass Mapping {\n /**\n Create a new mapping with the given position maps.\n */\n constructor(maps, \n /**\n @internal\n */\n mirror, \n /**\n The starting position in the `maps` array, used when `map` or\n `mapResult` is called.\n */\n from = 0, \n /**\n The end position in the `maps` array.\n */\n to = maps ? maps.length : 0) {\n this.mirror = mirror;\n this.from = from;\n this.to = to;\n this._maps = maps || [];\n this.ownData = !(maps || mirror);\n }\n /**\n The step maps in this mapping.\n */\n get maps() { return this._maps; }\n /**\n Create a mapping that maps only through a part of this one.\n */\n slice(from = 0, to = this.maps.length) {\n return new Mapping(this._maps, this.mirror, from, to);\n }\n /**\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.\n */\n appendMap(map, mirrors) {\n if (!this.ownData) {\n this._maps = this._maps.slice();\n this.mirror = this.mirror && this.mirror.slice();\n this.ownData = true;\n }\n this.to = this._maps.push(map);\n if (mirrors != null)\n this.setMirror(this._maps.length - 1, mirrors);\n }\n /**\n Add all the step maps in a given mapping to this one (preserving\n mirroring information).\n */\n appendMapping(mapping) {\n for (let i = 0, startSize = this._maps.length; i < mapping._maps.length; i++) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping._maps[i], mirr != null && mirr < i ? startSize + mirr : undefined);\n }\n }\n /**\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`).\n */\n getMirror(n) {\n if (this.mirror)\n for (let i = 0; i < this.mirror.length; i++)\n if (this.mirror[i] == n)\n return this.mirror[i + (i % 2 ? -1 : 1)];\n }\n /**\n @internal\n */\n setMirror(n, m) {\n if (!this.mirror)\n this.mirror = [];\n this.mirror.push(n, m);\n }\n /**\n Append the inverse of the given mapping to this one.\n */\n appendMappingInverted(mapping) {\n for (let i = mapping.maps.length - 1, totalSize = this._maps.length + mapping._maps.length; i >= 0; i--) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping._maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : undefined);\n }\n }\n /**\n Create an inverted version of this mapping.\n */\n invert() {\n let inverse = new Mapping;\n inverse.appendMappingInverted(this);\n return inverse;\n }\n /**\n Map a position through this mapping.\n */\n map(pos, assoc = 1) {\n if (this.mirror)\n return this._map(pos, assoc, true);\n for (let i = this.from; i < this.to; i++)\n pos = this._maps[i].map(pos, assoc);\n return pos;\n }\n /**\n Map a position through this mapping, returning a mapping\n result.\n */\n mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let delInfo = 0;\n for (let i = this.from; i < this.to; i++) {\n let map = this._maps[i], result = map.mapResult(pos, assoc);\n if (result.recover != null) {\n let 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 delInfo |= result.delInfo;\n pos = result.pos;\n }\n return simple ? pos : new MapResult(pos, delInfo, null);\n }\n}\n\nconst stepsByID = Object.create(null);\n/**\nA step object represents an atomic change. It generally applies\nonly to the document it was created for, since the positions\nstored in it will only make sense for that document.\n\nNew steps are defined by creating classes that extend `Step`,\noverriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`\nmethods, and registering your class with a unique\nJSON-serialization identifier using\n[`Step.jsonID`](https://prosemirror.net/docs/ref/#transform.Step^jsonID).\n*/\nclass Step {\n /**\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.\n */\n getMap() { return StepMap.empty; }\n /**\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.\n */\n merge(other) { return null; }\n /**\n Deserialize a step from its JSON representation. Will call\n through to the step class' own implementation of this method.\n */\n static fromJSON(schema, json) {\n if (!json || !json.stepType)\n throw new RangeError(\"Invalid input for Step.fromJSON\");\n let type = stepsByID[json.stepType];\n if (!type)\n throw new RangeError(`No step type ${json.stepType} defined`);\n return type.fromJSON(schema, json);\n }\n /**\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.\n */\n static jsonID(id, stepClass) {\n if (id in stepsByID)\n 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/**\nThe result of [applying](https://prosemirror.net/docs/ref/#transform.Step.apply) a step. Contains either a\nnew document or a failure value.\n*/\nclass StepResult {\n /**\n @internal\n */\n constructor(\n /**\n The transformed document, if successful.\n */\n doc, \n /**\n The failure message, if unsuccessful.\n */\n failed) {\n this.doc = doc;\n this.failed = failed;\n }\n /**\n Create a successful step result.\n */\n static ok(doc) { return new StepResult(doc, null); }\n /**\n Create a failed step result.\n */\n static fail(message) { return new StepResult(null, message); }\n /**\n Call [`Node.replace`](https://prosemirror.net/docs/ref/#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`.\n */\n static fromReplace(doc, from, to, slice) {\n try {\n return StepResult.ok(doc.replace(from, to, slice));\n }\n catch (e) {\n if (e instanceof ReplaceError)\n return StepResult.fail(e.message);\n throw e;\n }\n }\n}\n\nfunction mapFragment(fragment, f, parent) {\n let mapped = [];\n for (let i = 0; i < fragment.childCount; i++) {\n let child = fragment.child(i);\n if (child.content.size)\n child = child.copy(mapFragment(child.content, f, child));\n if (child.isInline)\n child = f(child, parent, i);\n mapped.push(child);\n }\n return Fragment.fromArray(mapped);\n}\n/**\nAdd a mark to all inline content between two positions.\n*/\nclass AddMarkStep extends Step {\n /**\n Create a mark step.\n */\n constructor(\n /**\n The start of the marked range.\n */\n from, \n /**\n The end of the marked range.\n */\n to, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from);\n let parent = $from.node($from.sharedDepth(this.to));\n let slice = new Slice(mapFragment(oldSlice.content, (node, parent) => {\n if (!node.isAtom || !parent.type.allowsMarkType(this.mark.type))\n return node;\n return node.mark(this.mark.addToSet(node.marks));\n }, parent), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert(doc) {\n let steps = [];\n doc.nodesBetween(this.from, this.to, (node, pos) => {\n if (node.isInline && node.isAtom) {\n let added = this.mark.addToSet(node.marks);\n if (!Mark.sameSet(added, node.marks)) {\n let from = Math.max(this.from, pos), to = Math.min(this.to, pos + node.nodeSize);\n pushMarkStep(RemoveMarkStep, from, to, this.mark, steps);\n for (let mark of node.marks)\n if (!mark.isInSet(added))\n pushMarkStep(AddMarkStep, from, to, mark, steps);\n }\n }\n });\n return steps.length == 1 ? steps[0] : new MarkSetStep(steps);\n }\n map(mapping) {\n let from = mapping.map(this.from, 1), to = mapping.map(this.to, -1);\n if (from >= to)\n return null;\n return new AddMarkStep(from, to, this.mark);\n }\n 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), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"addMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static 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}\nStep.jsonID(\"addMark\", AddMarkStep);\n/**\nRemove a mark from all inline content between two positions.\n*/\nclass RemoveMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The start of the unmarked range.\n */\n from, \n /**\n The end of the unmarked range.\n */\n to, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to);\n let slice = new Slice(mapFragment(oldSlice.content, node => {\n return node.mark(this.mark.removeFromSet(node.marks));\n }, doc), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert(doc) {\n let steps = [];\n doc.nodesBetween(this.from, this.to, (node, pos) => {\n if (node.isInline && node.isAtom && this.mark.isInSet(node.marks))\n pushMarkStep(AddMarkStep, Math.max(this.from, pos), Math.min(this.to, pos + node.nodeSize), this.mark, steps);\n });\n return steps.length == 1 ? steps[0] : new MarkSetStep(steps);\n }\n map(mapping) {\n let from = mapping.map(this.from, 1), to = mapping.map(this.to, -1);\n if (from >= to)\n return null;\n return new RemoveMarkStep(from, to, this.mark);\n }\n 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), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"removeMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static 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}\nStep.jsonID(\"removeMark\", RemoveMarkStep);\nfunction pushMarkStep(cls, from, to, mark, target) {\n let last = target.length ? target[target.length - 1] : null;\n if (last && last instanceof cls && last.to == from && last.mark.eq(mark)) {\n target[target.length - 1] = new cls(last.from, to, mark);\n }\n else {\n target.push(new cls(from, to, mark));\n }\n}\nclass MarkSetStep extends Step {\n constructor(steps) {\n super();\n this.steps = steps;\n }\n apply(doc) {\n for (let step of this.steps) {\n let result = step.apply(doc);\n if (!result.doc)\n return result;\n doc = result.doc;\n }\n return new StepResult(doc, null);\n }\n invert(doc) {\n return new MarkSetStep(this.steps.map(s => s.invert(doc)));\n }\n map(mapping) {\n let result = [];\n for (let step of this.steps) {\n let mapped = step.map(mapping);\n if (mapped)\n result.push(mapped);\n }\n return result.length ? new MarkSetStep(result) : null;\n }\n toJSON() {\n return { stepType: \"markSet\", steps: this.steps.map(s => s.toJSON()) };\n }\n static fromJSON(schema, json) {\n if (!Array.isArray(json.steps) || !json.steps.every((s) => s.stepType == \"addMark\" || s.stepType == \"removeMark\"))\n throw new RangeError(\"Invalid JSON for MarkSetStep\");\n return new MarkSetStep(json.steps.map((s) => Step.fromJSON(schema, s)));\n }\n}\nStep.jsonID(\"markSet\", MarkSetStep);\n/**\nAdd a mark to a specific node.\n*/\nclass AddNodeMarkStep extends Step {\n /**\n Create a node mark step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (node) {\n let newSet = this.mark.addToSet(node.marks);\n if (newSet.length == node.marks.length) {\n for (let i = 0; i < node.marks.length; i++)\n if (!node.marks[i].isInSet(newSet))\n return new AddNodeMarkStep(this.pos, node.marks[i]);\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n }\n return new RemoveNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"addNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for AddNodeMarkStep.fromJSON\");\n return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addNodeMark\", AddNodeMarkStep);\n/**\nRemove a mark from a specific node.\n*/\nclass RemoveNodeMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node || !this.mark.isInSet(node.marks))\n return this;\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"removeNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for RemoveNodeMarkStep.fromJSON\");\n return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeNodeMark\", RemoveNodeMarkStep);\n\n/**\nReplace a part of the document with a slice of new content.\n*/\nclass ReplaceStep extends Step {\n /**\n The given `slice` should fit the 'gap' between `from` and\n `to`—the depths must line up, and the surrounding nodes must be\n able to be joined with the open sides of the slice. When\n `structure` is true, the step will fail if the content between\n from and to is not just a sequence of closing and then opening\n tokens (this is to guard against rebased replace steps\n overwriting something they weren't supposed to).\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The slice to insert.\n */\n slice, \n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.slice = slice;\n this.structure = structure;\n }\n 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 getMap() {\n return new StepMap([this.from, this.to - this.from, this.slice.size]);\n }\n invert(doc) {\n return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to));\n }\n map(mapping) {\n let to = mapping.mapResult(this.to, -1);\n let from = this.from == this.to && ReplaceStep.MAP_BIAS < 0 ? to : mapping.mapResult(this.from, 1);\n if (from.deletedAcross && to.deletedAcross)\n return null;\n return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice, this.structure);\n }\n merge(other) {\n if (!(other instanceof ReplaceStep) || other.structure || this.structure)\n return null;\n if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {\n let 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 }\n else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {\n let slice = 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, this.structure);\n }\n else {\n return null;\n }\n }\n toJSON() {\n let json = { stepType: \"replace\", from: this.from, to: this.to };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static 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/**\nBy default, for backwards compatibility, an inserting step\nmapped over an insertion at that same position fill move after\nthe inserted content. In a collaborative editing situation, that\ncan make redone insertions appear in unexpected places. You can\nset this to -1 to make such mapping keep the step before the\ninsertion instead.\n*/\nReplaceStep.MAP_BIAS = 1;\nStep.jsonID(\"replace\", ReplaceStep);\n/**\nReplace a part of the document with a slice of content, but\npreserve a range of the replaced content by moving it into the\nslice.\n*/\nclass ReplaceAroundStep extends Step {\n /**\n Create a replace-around step with the given range and gap.\n `insert` should be the point in the slice into which the content\n of the gap should be moved. `structure` has the same meaning as\n it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The start of preserved range.\n */\n gapFrom, \n /**\n The end of preserved range.\n */\n gapTo, \n /**\n The slice to insert.\n */\n slice, \n /**\n The position in the slice where the preserved range should be\n inserted.\n */\n insert, \n /**\n @internal\n */\n structure = false) {\n super();\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 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 let gap = doc.slice(this.gapFrom, this.gapTo);\n if (gap.openStart || gap.openEnd)\n return StepResult.fail(\"Gap is not a flat range\");\n let inserted = this.slice.insertAt(this.insert, gap.content);\n if (!inserted)\n return StepResult.fail(\"Content does not fit in gap\");\n return StepResult.fromReplace(doc, this.from, this.to, inserted);\n }\n 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 invert(doc) {\n let gap = this.gapTo - this.gapFrom;\n 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);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n let gapFrom = this.from == this.gapFrom ? from.pos : mapping.map(this.gapFrom, -1);\n let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);\n if ((from.deletedAcross && to.deletedAcross) || gapFrom < from.pos || gapTo > to.pos)\n return null;\n return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);\n }\n toJSON() {\n let json = { stepType: \"replaceAround\", from: this.from, to: this.to,\n gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static 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, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);\n }\n}\nStep.jsonID(\"replaceAround\", ReplaceAroundStep);\nfunction contentBetween(doc, from, to) {\n let $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 let next = $from.node(depth).maybeChild($from.indexAfter(depth));\n while (dist > 0) {\n if (!next || next.isLeaf)\n return true;\n next = next.firstChild;\n dist--;\n }\n }\n return false;\n}\n\nfunction addMark(tr, from, to, mark) {\n let added = [];\n tr.doc.nodesBetween(from, to, (node, pos, parent) => {\n if (!node.isInline)\n return;\n let marks = node.marks;\n if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {\n let start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to);\n pushMarkStep(AddMarkStep, start, end, mark, added);\n }\n });\n added.forEach(s => tr.step(s));\n}\nfunction removeMark(tr, from, to, mark) {\n let matched = [], step = 0;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isInline || !node.isAtom)\n return;\n step++;\n let toRemove = null;\n if (mark instanceof MarkType) {\n let set = node.marks, found;\n while (found = mark.isInSet(set)) {\n (toRemove || (toRemove = [])).push(found);\n set = found.removeFromSet(set);\n }\n }\n else if (mark) {\n if (mark.isInSet(node.marks))\n toRemove = [mark];\n }\n else {\n toRemove = node.marks;\n }\n if (toRemove && toRemove.length) {\n let end = Math.min(pos + node.nodeSize, to);\n for (let i = 0; i < toRemove.length; i++) {\n let style = toRemove[i], found;\n for (let j = 0; j < matched.length; j++) {\n let m = matched[j];\n if (m.step == step - 1 && style.eq(matched[j].style))\n found = m;\n }\n if (found) {\n found.to = end;\n found.step = step;\n }\n else {\n matched.push({ style, from: Math.max(pos, from), to: end, step });\n }\n }\n }\n });\n matched.forEach(m => tr.step(new RemoveMarkStep(m.from, m.to, m.style)));\n}\nfunction clearIncompatible(tr, pos, parentType, match = parentType.contentMatch, clearNewlines = true) {\n let node = tr.doc.nodeAt(pos);\n let replSteps = [], cur = pos + 1;\n for (let i = 0; i < node.childCount; i++) {\n let child = node.child(i), end = cur + child.nodeSize;\n let allowed = match.matchType(child.type);\n if (!allowed) {\n replSteps.push(new ReplaceStep(cur, end, Slice.empty));\n }\n else {\n match = allowed;\n for (let j = 0; j < child.marks.length; j++)\n if (!parentType.allowsMarkType(child.marks[j].type))\n tr.step(new RemoveMarkStep(cur, end, child.marks[j]));\n if (clearNewlines && child.isText && parentType.whitespace != \"pre\") {\n let m, newline = /\\r?\\n|\\r/g, slice;\n while (m = newline.exec(child.text)) {\n if (!slice)\n slice = new Slice(Fragment.from(parentType.schema.text(\" \", parentType.allowedMarks(child.marks))), 0, 0);\n replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice));\n }\n }\n }\n cur = end;\n }\n if (!match.validEnd) {\n let fill = match.fillBefore(Fragment.empty, true);\n tr.replace(cur, cur, new Slice(fill, 0, 0));\n }\n for (let i = replSteps.length - 1; i >= 0; i--)\n tr.step(replSteps[i]);\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/**\nTry to find a target depth to which the content in the given range\ncan be lifted. Will not go across\n[isolating](https://prosemirror.net/docs/ref/#model.NodeSpec.isolating) parent nodes.\n*/\nfunction liftTarget(range) {\n let parent = range.parent;\n let content = parent.content.cutByIndex(range.startIndex, range.endIndex);\n for (let depth = range.depth, contentBefore = 0, contentAfter = 0;; --depth) {\n let node = range.$from.node(depth);\n let index = range.$from.index(depth) + contentBefore, endIndex = range.$to.indexAfter(depth) - contentAfter;\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))\n break;\n if (index)\n contentBefore = 1;\n if (endIndex < node.childCount)\n contentAfter = 1;\n }\n return null;\n}\nfunction lift(tr, range, target) {\n let { $from, $to, depth } = range;\n let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);\n let start = gapStart, end = gapEnd;\n let before = Fragment.empty, openStart = 0;\n for (let 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 }\n else {\n start--;\n }\n let after = Fragment.empty, openEnd = 0;\n for (let d = depth, splitting = false; d > target; d--)\n if (splitting || $to.after(d + 1) < $to.end(d)) {\n splitting = true;\n after = Fragment.from($to.node(d).copy(after));\n openEnd++;\n }\n else {\n end++;\n }\n tr.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));\n}\n/**\nTry to find a valid way to wrap the content in the given range in a\nnode of the given type. May introduce extra nodes around and inside\nthe wrapper node, if necessary. Returns null if no valid wrapping\ncould be found. When `innerRange` is given, that range's content is\nused as the content to fit into the wrapping, instead of the\ncontent of `range`.\n*/\nfunction findWrapping(range, nodeType, attrs = null, innerRange = range) {\n let around = findWrappingOutside(range, nodeType);\n let inner = around && findWrappingInside(innerRange, nodeType);\n if (!inner)\n return null;\n return around.map(withAttrs)\n .concat({ type: nodeType, attrs }).concat(inner.map(withAttrs));\n}\nfunction withAttrs(type) { return { type, attrs: null }; }\nfunction findWrappingOutside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let around = parent.contentMatchAt(startIndex).findWrapping(type);\n if (!around)\n return null;\n let outer = around.length ? around[0] : type;\n return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;\n}\nfunction findWrappingInside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let inner = parent.child(startIndex);\n let inside = type.contentMatch.findWrapping(inner.type);\n if (!inside)\n return null;\n let lastType = inside.length ? inside[inside.length - 1] : type;\n let innerMatch = lastType.contentMatch;\n for (let i = startIndex; innerMatch && i < endIndex; i++)\n innerMatch = innerMatch.matchType(parent.child(i).type);\n if (!innerMatch || !innerMatch.validEnd)\n return null;\n return inside;\n}\nfunction wrap(tr, range, wrappers) {\n let content = Fragment.empty;\n for (let i = wrappers.length - 1; i >= 0; i--) {\n if (content.size) {\n let match = wrappers[i].type.contentMatch.matchFragment(content);\n if (!match || !match.validEnd)\n throw new RangeError(\"Wrapper type given to Transform.wrap does not form valid content of its parent wrapper\");\n }\n content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n }\n let start = range.start, end = range.end;\n tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));\n}\nfunction setBlockType(tr, from, to, type, attrs) {\n if (!type.isTextblock)\n throw new RangeError(\"Type given to setBlockType should be a textblock\");\n let mapFrom = tr.steps.length;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n let attrsHere = typeof attrs == \"function\" ? attrs(node) : attrs;\n if (node.isTextblock && !node.hasMarkup(type, attrsHere) &&\n canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) {\n let convertNewlines = null;\n if (type.schema.linebreakReplacement) {\n let pre = type.whitespace == \"pre\", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n // Ensure all markup that isn't allowed in the new node type is cleared\n if (convertNewlines === false)\n replaceLinebreaks(tr, node, pos, mapFrom);\n clearIncompatible(tr, tr.mapping.slice(mapFrom).map(pos, 1), type, undefined, convertNewlines === null);\n let mapping = tr.mapping.slice(mapFrom);\n let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);\n tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true));\n if (convertNewlines === true)\n replaceNewlines(tr, node, pos, mapFrom);\n return false;\n }\n });\n}\nfunction replaceNewlines(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.isText) {\n let m, newline = /\\r?\\n|\\r/g;\n while (m = newline.exec(child.text)) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset + m.index);\n tr.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create());\n }\n }\n });\n}\nfunction replaceLinebreaks(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.type == child.type.schema.linebreakReplacement) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset);\n tr.replaceWith(start, start + 1, node.type.schema.text(\"\\n\"));\n }\n });\n}\nfunction canChangeType(doc, pos, type) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return $pos.parent.canReplaceWith(index, index + 1, type);\n}\n/**\nChange the type, attributes, and/or marks of the node at `pos`.\nWhen `type` isn't given, the existing node type is preserved,\n*/\nfunction setNodeMarkup(tr, pos, type, attrs, marks) {\n let node = tr.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at given position\");\n if (!type)\n type = node.type;\n let newNode = type.create(attrs, null, marks || node.marks);\n if (node.isLeaf)\n return tr.replaceWith(pos, pos + node.nodeSize, newNode);\n if (!type.validContent(node.content))\n throw new RangeError(\"Invalid content for node type \" + type.name);\n tr.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));\n}\n/**\nCheck whether splitting at the given position is allowed.\n*/\nfunction canSplit(doc, pos, depth = 1, typesAfter) {\n let $pos = doc.resolve(pos), base = $pos.depth - depth;\n let 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 (let d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {\n let node = $pos.node(d), index = $pos.index(d);\n if (node.type.spec.isolating)\n return false;\n let rest = node.content.cutByIndex(index, node.childCount);\n let overrideChild = typesAfter && typesAfter[i + 1];\n if (overrideChild)\n rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));\n let after = (typesAfter && typesAfter[i]) || node;\n if (!node.canReplace(index + 1, node.childCount) || !after.type.validContent(rest))\n return false;\n }\n let index = $pos.indexAfter(base);\n let baseType = typesAfter && typesAfter[0];\n return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type);\n}\nfunction split(tr, pos, depth = 1, typesAfter) {\n let $pos = tr.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;\n for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {\n before = Fragment.from($pos.node(d).copy(before));\n let typeAfter = typesAfter && typesAfter[i];\n after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));\n }\n tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));\n}\n/**\nTest whether the blocks before and after a given position can be\njoined.\n*/\nfunction canJoin(doc, pos) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return joinable($pos.nodeBefore, $pos.nodeAfter) &&\n $pos.parent.canReplace(index, index + 1);\n}\nfunction canAppendWithSubstitutedLinebreaks(a, b) {\n if (!b.content.size)\n a.type.compatibleContent(b.type);\n let match = a.contentMatchAt(a.childCount);\n let { linebreakReplacement } = a.type.schema;\n for (let i = 0; i < b.childCount; i++) {\n let child = b.child(i);\n let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type;\n match = match.matchType(type);\n if (!match)\n return false;\n if (!a.type.allowsMarks(child.marks))\n return false;\n }\n return match.validEnd;\n}\nfunction joinable(a, b) {\n return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b));\n}\n/**\nFind an ancestor of the given position that can be joined to the\nblock before (or after if `dir` is positive). Returns the joinable\npoint, if any.\n*/\nfunction joinPoint(doc, pos, dir = -1) {\n let $pos = doc.resolve(pos);\n for (let d = $pos.depth;; d--) {\n let before, after, index = $pos.index(d);\n if (d == $pos.depth) {\n before = $pos.nodeBefore;\n after = $pos.nodeAfter;\n }\n else if (dir > 0) {\n before = $pos.node(d + 1);\n index++;\n after = $pos.node(d).maybeChild(index);\n }\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))\n return pos;\n if (d == 0)\n break;\n pos = dir < 0 ? $pos.before(d) : $pos.after(d);\n }\n}\nfunction join(tr, pos, depth) {\n let convertNewlines = null;\n let { linebreakReplacement } = tr.doc.type.schema;\n let $before = tr.doc.resolve(pos - depth), beforeType = $before.node().type;\n if (linebreakReplacement && beforeType.inlineContent) {\n let pre = beforeType.whitespace == \"pre\";\n let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n let mapFrom = tr.steps.length;\n if (convertNewlines === false) {\n let $after = tr.doc.resolve(pos + depth);\n replaceLinebreaks(tr, $after.node(), $after.before(), mapFrom);\n }\n if (beforeType.inlineContent)\n clearIncompatible(tr, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null);\n let mapping = tr.mapping.slice(mapFrom), start = mapping.map(pos - depth);\n tr.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true));\n if (convertNewlines === true) {\n let $full = tr.doc.resolve(start);\n replaceNewlines(tr, $full.node(), $full.before(), tr.steps.length);\n }\n return tr;\n}\n/**\nTry to find a point where a node of the given type can be inserted\nnear `pos`, by searching up the node hierarchy when `pos` itself\nisn't a valid place but is at the start or end of a node. Return\nnull if no position was found.\n*/\nfunction insertPoint(doc, pos, nodeType) {\n let $pos = doc.resolve(pos);\n if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))\n return pos;\n if ($pos.parentOffset == 0)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.index(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.before(d + 1);\n if (index > 0)\n return null;\n }\n if ($pos.parentOffset == $pos.parent.content.size)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.indexAfter(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.after(d + 1);\n if (index < $pos.node(d).childCount)\n return null;\n }\n return null;\n}\n/**\nFinds a position at or around the given position where the given\nslice can be inserted. Will look at parent nodes' nearest boundary\nand try there, even if the original position wasn't directly at the\nstart or end of that node. Returns null when no position was found.\n*/\nfunction dropPoint(doc, pos, slice) {\n let $pos = doc.resolve(pos);\n if (!slice.content.size)\n return pos;\n let content = slice.content;\n for (let i = 0; i < slice.openStart; i++)\n content = content.firstChild.content;\n for (let pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {\n for (let d = $pos.depth; d >= 0; d--) {\n let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;\n let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);\n let parent = $pos.node(d), fits = false;\n if (pass == 1) {\n fits = parent.canReplace(insertPos, insertPos, content);\n }\n else {\n let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type);\n fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);\n }\n if (fits)\n return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);\n }\n }\n return null;\n}\n\n/**\n‘Fit’ a slice into a given position in the document, producing a\n[step](https://prosemirror.net/docs/ref/#transform.Step) that inserts it. Will return null if\nthere's no meaningful way to insert the slice here, or inserting it\nwould be a no-op (an empty slice over an empty range).\n*/\nfunction replaceStep(doc, from, to = from, slice = Slice.empty) {\n if (from == to && !slice.size)\n return null;\n let $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))\n return new ReplaceStep(from, to, slice);\n return new Fitter($from, $to, slice).fit();\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// 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`.\nclass Fitter {\n constructor($from, $to, unplaced) {\n this.$from = $from;\n this.$to = $to;\n this.unplaced = unplaced;\n this.frontier = [];\n this.placed = Fragment.empty;\n for (let i = 0; i <= $from.depth; i++) {\n let node = $from.node(i);\n this.frontier.push({\n type: node.type,\n match: node.contentMatchAt($from.indexAfter(i))\n });\n }\n for (let i = $from.depth; i > 0; i--)\n this.placed = Fragment.from($from.node(i).copy(this.placed));\n }\n get depth() { return this.frontier.length - 1; }\n 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 let fit = this.findFittable();\n if (fit)\n this.placeNodes(fit);\n else\n 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 let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;\n let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));\n if (!$to)\n return null;\n // If closing to `$to` succeeded, create a step\n let 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--;\n openEnd--;\n }\n let 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 return null;\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.\n findFittable() {\n let startDepth = this.unplaced.openStart;\n for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) {\n let node = cur.firstChild;\n if (cur.childCount > 1)\n openEnd = 0;\n if (node.type.spec.isolating && openEnd <= d) {\n startDepth = d;\n break;\n }\n cur = node.content;\n }\n // Only try wrapping nodes (pass 2) after finding a place without\n // wrapping failed.\n for (let pass = 1; pass <= 2; pass++) {\n for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {\n let fragment, parent = null;\n if (sliceDepth) {\n parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;\n fragment = parent.content;\n }\n else {\n fragment = this.unplaced.content;\n }\n let first = fragment.firstChild;\n for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {\n let { type, match } = this.frontier[frontierDepth], wrap, inject = null;\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 : parent && type.compatibleContent(parent.type)))\n return { sliceDepth, frontierDepth, parent, 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, frontierDepth, parent, wrap };\n // Don't continue looking further up if the parent node\n // would fit here.\n if (parent && match.matchType(parent.type))\n break;\n }\n }\n }\n }\n openMore() {\n let { content, openStart, openEnd } = this.unplaced;\n if (maxOpen(content, -1) <= openStart)\n return false;\n if (this.unplaced.size > 1 && maxOpen(content, 1) > openEnd)\n openEnd++;\n this.unplaced = new Slice(content, openStart + 1, openEnd);\n return true;\n }\n dropNode() {\n let { content, openStart, openEnd } = this.unplaced;\n let inner = contentAt(content, openStart);\n if (inner.childCount <= 1 && openStart > 0) {\n let openAtEnd = content.size - openStart <= openStart + inner.size;\n this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);\n }\n else {\n this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);\n }\n }\n // Move content from the unplaced slice at `sliceDepth` to the\n // frontier node at `frontierDepth`. Close that frontier node when\n // applicable.\n placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap }) {\n while (this.depth > frontierDepth)\n this.closeFrontierNode();\n if (wrap)\n for (let i = 0; i < wrap.length; i++)\n this.openFrontierNode(wrap[i]);\n let slice = this.unplaced, fragment = parent ? parent.content : slice.content;\n let openStart = slice.openStart - sliceDepth;\n let taken = 0, add = [];\n let { match, type } = this.frontier[frontierDepth];\n if (inject) {\n for (let i = 0; i < inject.childCount; i++)\n add.push(inject.child(i));\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 let 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 let next = fragment.child(taken), matches = match.matchType(next.type);\n if (!matches)\n 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, taken == fragment.childCount ? openEndCount : -1));\n }\n }\n let toEnd = taken == fragment.childCount;\n if (!toEnd)\n openEndCount = -1;\n this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));\n this.frontier[frontierDepth].match = match;\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.frontier.length > 1)\n this.closeFrontierNode();\n // Add new frontier nodes for any open nodes at the end.\n for (let i = 0, cur = fragment; i < openEndCount; i++) {\n let node = cur.lastChild;\n this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) });\n cur = node.content;\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), sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);\n }\n mustMoveInline() {\n if (!this.$to.parent.isTextblock)\n return -1;\n let 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))\n return -1;\n let { depth } = this.$to, after = this.$to.after(depth);\n while (depth > 1 && after == this.$to.end(--depth))\n ++after;\n return after;\n }\n findCloseLevel($to) {\n scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {\n let { match, type } = this.frontier[i];\n let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));\n let fit = contentAfterFits($to, i, type, match, dropInner);\n if (!fit)\n continue;\n for (let d = i - 1; d >= 0; d--) {\n let { match, type } = this.frontier[d];\n let matches = contentAfterFits($to, d, type, match, true);\n if (!matches || matches.childCount)\n continue scan;\n }\n return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to };\n }\n }\n close($to) {\n let close = this.findCloseLevel($to);\n if (!close)\n return null;\n while (this.depth > close.depth)\n this.closeFrontierNode();\n if (close.fit.childCount)\n this.placed = addToFragment(this.placed, close.depth, close.fit);\n $to = close.move;\n for (let d = close.depth + 1; d <= $to.depth; d++) {\n let 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 openFrontierNode(type, attrs = null, content) {\n let 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, match: type.contentMatch });\n }\n closeFrontierNode() {\n let open = this.frontier.pop();\n let add = open.match.fillBefore(Fragment.empty, true);\n if (add.childCount)\n this.placed = addToFragment(this.placed, this.frontier.length, add);\n }\n}\nfunction dropFromFragment(fragment, depth, count) {\n if (depth == 0)\n return fragment.cutByIndex(count, fragment.childCount);\n return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));\n}\nfunction addToFragment(fragment, depth, content) {\n if (depth == 0)\n return fragment.append(content);\n return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));\n}\nfunction contentAt(fragment, depth) {\n for (let i = 0; i < depth; i++)\n fragment = fragment.firstChild.content;\n return fragment;\n}\nfunction closeNodeStart(node, openStart, openEnd) {\n if (openStart <= 0)\n return node;\n let 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)\n frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));\n }\n return node.copy(frag);\n}\nfunction contentAfterFits($to, depth, type, match, open) {\n let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);\n if (index == node.childCount && !type.compatibleContent(node.type))\n return null;\n let fit = match.fillBefore(node.content, true, index);\n return fit && !invalidMarks(type, node.content, index) ? fit : null;\n}\nfunction invalidMarks(type, fragment, start) {\n for (let i = start; i < fragment.childCount; i++)\n if (!type.allowsMarks(fragment.child(i).marks))\n return true;\n return false;\n}\nfunction definesContent(type) {\n return type.spec.defining || type.spec.definingForContent;\n}\nfunction maxOpen(frag, side) {\n for (let count = 0;; count++) {\n let ch = side < 0 ? frag.firstChild : frag.lastChild;\n if (!ch || ch.isAtom)\n return count;\n frag = ch.content;\n }\n}\nfunction replaceRange(tr, from, to, slice) {\n if (!slice.size)\n return tr.deleteRange(from, to);\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n if (fitsTrivially($from, $to, slice))\n return tr.step(new ReplaceStep(from, to, slice));\n let targetDepths = coveredDepths($from, $to);\n // Can't replace the whole document, so remove 0 if it's present\n if (targetDepths[targetDepths.length - 1] == 0)\n 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 let 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 (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {\n let spec = $from.node(d).type.spec;\n if (spec.defining || spec.definingAsContext || spec.isolating)\n break;\n if (targetDepths.indexOf(d) > -1)\n preferredTarget = d;\n else if ($from.before(d) == pos)\n 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 let preferredTargetIndex = targetDepths.indexOf(preferredTarget);\n let leftNodes = [], preferredDepth = slice.openStart;\n for (let content = slice.content, i = 0;; i++) {\n let node = content.firstChild;\n leftNodes.push(node);\n if (i == slice.openStart)\n break;\n content = node.content;\n }\n // Back up preferredDepth to cover defining textblocks directly\n // above it, possibly skipping a non-defining textblock.\n for (let d = preferredDepth - 1; d >= 0; d--) {\n let leftNode = leftNodes[d], def = definesContent(leftNode.type);\n if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))\n preferredDepth = d;\n else if (def || !leftNode.type.isTextblock)\n break;\n }\n for (let j = slice.openStart; j >= 0; j--) {\n let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);\n let insert = leftNodes[openDepth];\n if (!insert)\n continue;\n for (let i = 0; i < targetDepths.length; i++) {\n // Loop over possible expansion levels, starting with the\n // preferred one\n let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true;\n if (targetDepth < 0) {\n expand = false;\n targetDepth = -targetDepth;\n }\n let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);\n if (parent.canReplaceWith(index, index, insert.type, insert.marks))\n return tr.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd));\n }\n }\n let startSteps = tr.steps.length;\n for (let i = targetDepths.length - 1; i >= 0; i--) {\n tr.replace(from, to, slice);\n if (tr.steps.length > startSteps)\n break;\n let depth = targetDepths[i];\n if (depth < 0)\n continue;\n from = $from.before(depth);\n to = $to.after(depth);\n }\n}\nfunction closeFragment(fragment, depth, oldOpen, newOpen, parent) {\n if (depth < oldOpen) {\n let first = fragment.firstChild;\n fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));\n }\n if (depth > newOpen) {\n let match = parent.contentMatchAt(0);\n let start = match.fillBefore(fragment).append(fragment);\n fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));\n }\n return fragment;\n}\nfunction replaceRangeWith(tr, from, to, node) {\n if (!node.isInline && from == to && tr.doc.resolve(from).parent.content.size) {\n let point = insertPoint(tr.doc, from, node.type);\n if (point != null)\n from = to = point;\n }\n tr.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0));\n}\nfunction deleteRange(tr, from, to) {\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n // When the deleted range spans from the start of one textblock to\n // the start of another one, move out of the start of both blocks.\n if ($from.parent.isTextblock && $to.parent.isTextblock && $from.start() != $to.start() &&\n $from.parentOffset == 0 && $to.parentOffset == 0) {\n let shared = $from.sharedDepth(to), isolated = false;\n for (let d = $from.depth; d > shared; d--)\n if ($from.node(d).type.spec.isolating)\n isolated = true;\n for (let d = $to.depth; d > shared; d--)\n if ($to.node(d).type.spec.isolating)\n isolated = true;\n if (!isolated) {\n for (let d = $from.depth; d > 0 && from == $from.start(d); d--)\n from = $from.before(d);\n for (let d = $to.depth; d > 0 && to == $to.start(d); d--)\n to = $to.before(d);\n $from = tr.doc.resolve(from);\n $to = tr.doc.resolve(to);\n }\n }\n let covered = coveredDepths($from, $to);\n for (let i = 0; i < covered.length; i++) {\n let depth = covered[i], last = i == covered.length - 1;\n if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd)\n return tr.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 tr.delete($from.before(depth), $to.after(depth));\n }\n for (let 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 $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1)))\n return tr.delete($from.before(d), to);\n }\n tr.delete(from, to);\n}\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 let result = [], minDepth = Math.min($from.depth, $to.depth);\n for (let d = minDepth; d >= 0; d--) {\n let 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)\n break;\n if (start == $to.start(d) ||\n (d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent &&\n d && $to.start(d - 1) == start - 1))\n result.push(d);\n }\n return result;\n}\n\n/**\nUpdate an attribute in a specific node.\n*/\nclass AttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.pos = pos;\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at attribute step's position\");\n let attrs = Object.create(null);\n for (let name in node.attrs)\n attrs[name] = node.attrs[name];\n attrs[this.attr] = this.value;\n let updated = node.type.create(attrs, null, node.marks);\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new AttrStep(this.pos, this.attr, doc.nodeAt(this.pos).attrs[this.attr]);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value);\n }\n toJSON() {\n return { stepType: \"attr\", pos: this.pos, attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\" || typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for AttrStep.fromJSON\");\n return new AttrStep(json.pos, json.attr, json.value);\n }\n}\nStep.jsonID(\"attr\", AttrStep);\n/**\nUpdate an attribute in the doc node.\n*/\nclass DocAttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let attrs = Object.create(null);\n for (let name in doc.attrs)\n attrs[name] = doc.attrs[name];\n attrs[this.attr] = this.value;\n let updated = doc.type.create(attrs, doc.content, doc.marks);\n return StepResult.ok(updated);\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new DocAttrStep(this.attr, doc.attrs[this.attr]);\n }\n map(mapping) {\n return this;\n }\n toJSON() {\n return { stepType: \"docAttr\", attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for DocAttrStep.fromJSON\");\n return new DocAttrStep(json.attr, json.value);\n }\n}\nStep.jsonID(\"docAttr\", DocAttrStep);\n\n/**\n@internal\n*/\nlet TransformError = class extends Error {\n};\nTransformError = function TransformError(message) {\n let err = Error.call(this, message);\n err.__proto__ = TransformError.prototype;\n return err;\n};\nTransformError.prototype = Object.create(Error.prototype);\nTransformError.prototype.constructor = TransformError;\nTransformError.prototype.name = \"TransformError\";\n/**\nAbstraction to build up and track an array of\n[steps](https://prosemirror.net/docs/ref/#transform.Step) representing a document transformation.\n\nMost transforming methods return the `Transform` object itself, so\nthat they can be chained.\n*/\nclass Transform {\n /**\n Create a transform that starts with the given document.\n */\n constructor(\n /**\n The current document (the result of applying the steps in the\n transform).\n */\n doc) {\n this.doc = doc;\n /**\n The steps in this transform.\n */\n this.steps = [];\n /**\n The documents before each of the steps.\n */\n this.docs = [];\n /**\n A mapping with the maps for each of the steps in this transform.\n */\n this.mapping = new Mapping;\n }\n /**\n The starting document.\n */\n get before() { return this.docs.length ? this.docs[0] : this.doc; }\n /**\n Apply a new step in this transform, saving the result. Throws an\n error when the step fails.\n */\n step(step) {\n let result = this.maybeStep(step);\n if (result.failed)\n throw new TransformError(result.failed);\n return this;\n }\n /**\n Try to apply a step in this transformation, ignoring it if it\n fails. Returns the step result.\n */\n maybeStep(step) {\n let result = step.apply(this.doc);\n if (!result.failed)\n this.addStep(step, result.doc);\n return result;\n }\n /**\n True when the document has been changed (when there are any\n steps).\n */\n get docChanged() {\n return this.steps.length > 0;\n }\n /**\n Return a single range, in post-transform document positions,\n that covers all content changed by this transform. Returns null\n if no replacements are made. Note that this will ignore changes\n that add/remove marks without replacing the underlying content.\n */\n changedRange() {\n let from = 1e9, to = -1e9;\n for (let i = 0; i < this.mapping.maps.length; i++) {\n let map = this.mapping.maps[i];\n if (i) {\n from = map.map(from, 1);\n to = map.map(to, -1);\n }\n map.forEach((_f, _t, fromB, toB) => {\n from = Math.min(from, fromB);\n to = Math.max(to, toB);\n });\n }\n return from == 1e9 ? null : { from, to };\n }\n /**\n @internal\n */\n 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 /**\n Replace the part of the document between `from` and `to` with the\n given `slice`.\n */\n replace(from, to = from, slice = Slice.empty) {\n let step = replaceStep(this.doc, from, to, slice);\n if (step)\n this.step(step);\n return this;\n }\n /**\n Replace the given range with the given content, which may be a\n fragment, node, or array of nodes.\n */\n replaceWith(from, to, content) {\n return this.replace(from, to, new Slice(Fragment.from(content), 0, 0));\n }\n /**\n Delete the content between the given positions.\n */\n delete(from, to) {\n return this.replace(from, to, Slice.empty);\n }\n /**\n Insert the given content at the given position.\n */\n insert(pos, content) {\n return this.replaceWith(pos, pos, content);\n }\n /**\n Replace a range of the document with a given slice, using\n `from`, `to`, and the slice's\n [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather\n than fixed start and end points. This method may grow the\n replaced area or close open nodes in the slice in order to get a\n fit that is more in line with WYSIWYG expectations, by dropping\n fully covered parent nodes of the replaced region when they are\n marked [non-defining as\n context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an\n open parent node from the slice that _is_ marked as [defining\n its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n \n This is the method, for example, to handle paste. The similar\n [`replace`](https://prosemirror.net/docs/ref/#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.\n */\n replaceRange(from, to, slice) {\n replaceRange(this, from, to, slice);\n return this;\n }\n /**\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.\n */\n replaceRangeWith(from, to, node) {\n replaceRangeWith(this, from, to, node);\n return this;\n }\n /**\n Delete the given range, expanding it to cover fully covered\n parent nodes until a valid replace is found.\n */\n deleteRange(from, to) {\n deleteRange(this, from, to);\n return this;\n }\n /**\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`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make\n sure the lift is valid.\n */\n lift(range, target) {\n lift(this, range, target);\n return this;\n }\n /**\n Join the blocks around the given position. If depth is 2, their\n last and first siblings are also joined, and so on.\n */\n join(pos, depth = 1) {\n join(this, pos, depth);\n return this;\n }\n /**\n Wrap the given [range](https://prosemirror.net/docs/ref/#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`](https://prosemirror.net/docs/ref/#transform.findWrapping).\n */\n wrap(range, wrappers) {\n wrap(this, range, wrappers);\n return this;\n }\n /**\n Set the type of all textblocks (partly) between `from` and `to` to\n the given node type with the given attributes.\n */\n setBlockType(from, to = from, type, attrs = null) {\n setBlockType(this, from, to, type, attrs);\n return this;\n }\n /**\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,\n */\n setNodeMarkup(pos, type, attrs = null, marks) {\n setNodeMarkup(this, pos, type, attrs, marks);\n return this;\n }\n /**\n Set a single attribute on a given node to a new value.\n The `pos` addresses the document content. Use `setDocAttribute`\n to set attributes on the document itself.\n */\n setNodeAttribute(pos, attr, value) {\n this.step(new AttrStep(pos, attr, value));\n return this;\n }\n /**\n Set a single attribute on the document to a new value.\n */\n setDocAttribute(attr, value) {\n this.step(new DocAttrStep(attr, value));\n return this;\n }\n /**\n Add a mark to the node at position `pos`.\n */\n addNodeMark(pos, mark) {\n this.step(new AddNodeMarkStep(pos, mark));\n return this;\n }\n /**\n Remove a mark (or all marks of the given type) from the node at\n position `pos`.\n */\n removeNodeMark(pos, mark) {\n let node = this.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at position \" + pos);\n if (mark instanceof Mark) {\n if (mark.isInSet(node.marks))\n this.step(new RemoveNodeMarkStep(pos, mark));\n }\n else {\n let set = node.marks, found, steps = [];\n while (found = mark.isInSet(set)) {\n steps.push(new RemoveNodeMarkStep(pos, found));\n set = found.removeFromSet(set);\n }\n for (let i = steps.length - 1; i >= 0; i--)\n this.step(steps[i]);\n }\n return this;\n }\n /**\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 (with the outermost nodes coming first).\n */\n split(pos, depth = 1, typesAfter) {\n split(this, pos, depth, typesAfter);\n return this;\n }\n /**\n Add the given mark to the inline content between `from` and `to`.\n */\n addMark(from, to, mark) {\n addMark(this, from, to, mark);\n return this;\n }\n /**\n Remove marks from inline nodes between `from` and `to`. When\n `mark` is a single mark, remove precisely that mark. When it is\n a mark type, remove all marks of that type. When it is null,\n remove all marks of any type.\n */\n removeMark(from, to, mark) {\n removeMark(this, from, to, mark);\n return this;\n }\n /**\n Removes all marks and nodes from the content of the node at\n `pos` that don't match the given new parent node type. Accepts\n an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as\n third argument.\n */\n clearIncompatible(pos, parentType, match) {\n clearIncompatible(this, pos, parentType, match);\n return this;\n }\n}\n\nexport { AddMarkStep, AddNodeMarkStep, AttrStep, DocAttrStep, MapResult, Mapping, RemoveMarkStep, RemoveNodeMarkStep, ReplaceAroundStep, ReplaceStep, Step, StepMap, StepResult, Transform, TransformError, canJoin, canSplit, dropPoint, findWrapping, insertPoint, joinPoint, liftTarget, replaceStep };\n", + "import { Slice, Fragment, Mark, Node } from 'prosemirror-model';\nimport { ReplaceStep, ReplaceAroundStep, Transform } from 'prosemirror-transform';\n\nconst classesById = Object.create(null);\n/**\nSuperclass for editor selections. Every selection type should\nextend this. Should not be instantiated directly.\n*/\nclass Selection {\n /**\n Initialize a selection with the head and anchor and ranges. If no\n ranges are given, constructs a single range across `$anchor` and\n `$head`.\n */\n constructor(\n /**\n The resolved anchor of the selection (the side that stays in\n place when the selection is modified).\n */\n $anchor, \n /**\n The resolved head of the selection (the side that moves when\n the selection is modified).\n */\n $head, ranges) {\n this.$anchor = $anchor;\n this.$head = $head;\n this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];\n }\n /**\n The selection's anchor, as an unresolved position.\n */\n get anchor() { return this.$anchor.pos; }\n /**\n The selection's head.\n */\n get head() { return this.$head.pos; }\n /**\n The lower bound of the selection's main range.\n */\n get from() { return this.$from.pos; }\n /**\n The upper bound of the selection's main range.\n */\n get to() { return this.$to.pos; }\n /**\n The resolved lower bound of the selection's main range.\n */\n get $from() {\n return this.ranges[0].$from;\n }\n /**\n The resolved upper bound of the selection's main range.\n */\n get $to() {\n return this.ranges[0].$to;\n }\n /**\n Indicates whether the selection contains any content.\n */\n get empty() {\n let ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++)\n if (ranges[i].$from.pos != ranges[i].$to.pos)\n return false;\n return true;\n }\n /**\n Get the content of this selection as a slice.\n */\n content() {\n return this.$from.doc.slice(this.from, this.to, true);\n }\n /**\n Replace the selection with a slice or, if no slice is given,\n delete the selection. Will append to the given transaction.\n */\n replace(tr, content = Slice.empty) {\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 let lastNode = content.content.lastChild, lastParent = null;\n for (let i = 0; i < content.openEnd; i++) {\n lastParent = lastNode;\n lastNode = lastNode.lastChild;\n }\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);\n if (i == 0)\n selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);\n }\n }\n /**\n Replace the selection with the given node, appending the changes\n to the given transaction.\n */\n replaceWith(tr, node) {\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n let from = mapping.map($from.pos), to = mapping.map($to.pos);\n if (i) {\n tr.deleteRange(from, to);\n }\n else {\n tr.replaceRangeWith(from, to, node);\n selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);\n }\n }\n }\n /**\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.\n */\n static findFrom($pos, dir, textOnly = false) {\n let inner = $pos.parent.inlineContent ? new TextSelection($pos)\n : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);\n if (inner)\n return inner;\n for (let depth = $pos.depth - 1; depth >= 0; depth--) {\n let 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)\n return found;\n }\n return null;\n }\n /**\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.\n */\n static near($pos, bias = 1) {\n return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));\n }\n /**\n Find the cursor or leaf node selection closest to the start of\n the given document. Will return an\n [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position\n exists.\n */\n static atStart(doc) {\n return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc);\n }\n /**\n Find the cursor or leaf node selection closest to the end of the\n given document.\n */\n static atEnd(doc) {\n return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc);\n }\n /**\n Deserialize the JSON representation of a selection. Must be\n implemented for custom classes (as a static class method).\n */\n static fromJSON(doc, json) {\n if (!json || !json.type)\n throw new RangeError(\"Invalid input for Selection.fromJSON\");\n let cls = classesById[json.type];\n if (!cls)\n throw new RangeError(`No selection type ${json.type} defined`);\n return cls.fromJSON(doc, json);\n }\n /**\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.\n */\n static jsonID(id, selectionClass) {\n if (id in classesById)\n 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 Get a [bookmark](https://prosemirror.net/docs/ref/#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.\n */\n getBookmark() {\n return TextSelection.between(this.$anchor, this.$head).getBookmark();\n }\n}\nSelection.prototype.visible = true;\n/**\nRepresents a selected range in a document.\n*/\nclass SelectionRange {\n /**\n Create a range.\n */\n constructor(\n /**\n The lower bound of the range.\n */\n $from, \n /**\n The upper bound of the range.\n */\n $to) {\n this.$from = $from;\n this.$to = $to;\n }\n}\nlet warnedAboutTextSelection = false;\nfunction checkTextSelection($pos) {\n if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {\n warnedAboutTextSelection = true;\n console[\"warn\"](\"TextSelection endpoint not pointing into a node with inline content (\" + $pos.parent.type.name + \")\");\n }\n}\n/**\nA text selection represents a classical editor selection, with a\nhead (the moving side) and anchor (immobile side), both of which\npoint into textblock nodes. It can be empty (a regular cursor\nposition).\n*/\nclass TextSelection extends Selection {\n /**\n Construct a text selection between the given points.\n */\n constructor($anchor, $head = $anchor) {\n checkTextSelection($anchor);\n checkTextSelection($head);\n super($anchor, $head);\n }\n /**\n Returns a resolved position if this is a cursor selection (an\n empty text selection), and null otherwise.\n */\n get $cursor() { return this.$anchor.pos == this.$head.pos ? this.$head : null; }\n map(doc, mapping) {\n let $head = doc.resolve(mapping.map(this.head));\n if (!$head.parent.inlineContent)\n return Selection.near($head);\n let $anchor = doc.resolve(mapping.map(this.anchor));\n return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);\n }\n replace(tr, content = Slice.empty) {\n super.replace(tr, content);\n if (content == Slice.empty) {\n let marks = this.$from.marksAcross(this.$to);\n if (marks)\n tr.ensureMarks(marks);\n }\n }\n eq(other) {\n return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head;\n }\n getBookmark() {\n return new TextBookmark(this.anchor, this.head);\n }\n toJSON() {\n return { type: \"text\", anchor: this.anchor, head: this.head };\n }\n /**\n @internal\n */\n static 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 Create a text selection from non-resolved positions.\n */\n static create(doc, anchor, head = anchor) {\n let $anchor = doc.resolve(anchor);\n return new this($anchor, head == anchor ? $anchor : doc.resolve(head));\n }\n /**\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`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document\n doesn't contain a valid text position.\n */\n static between($anchor, $head, bias) {\n let dPos = $anchor.pos - $head.pos;\n if (!bias || dPos)\n bias = dPos >= 0 ? 1 : -1;\n if (!$head.parent.inlineContent) {\n let found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);\n if (found)\n $head = found.$head;\n else\n return Selection.near($head, bias);\n }\n if (!$anchor.parent.inlineContent) {\n if (dPos == 0) {\n $anchor = $head;\n }\n else {\n $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;\n if (($anchor.pos < $head.pos) != (dPos < 0))\n $anchor = $head;\n }\n }\n return new TextSelection($anchor, $head);\n }\n}\nSelection.jsonID(\"text\", TextSelection);\nclass TextBookmark {\n constructor(anchor, head) {\n this.anchor = anchor;\n this.head = head;\n }\n map(mapping) {\n return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));\n }\n resolve(doc) {\n return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head));\n }\n}\n/**\nA node selection is a selection that points at a single node. All\nnodes marked [selectable](https://prosemirror.net/docs/ref/#model.NodeSpec.selectable) can be the\ntarget of a node selection. In such a selection, `from` and `to`\npoint directly before and after the selected node, `anchor` equals\n`from`, and `head` equals `to`..\n*/\nclass NodeSelection extends Selection {\n /**\n Create a node selection. Does not verify the validity of its\n argument.\n */\n constructor($pos) {\n let node = $pos.nodeAfter;\n let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);\n super($pos, $end);\n this.node = node;\n }\n map(doc, mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n let $pos = doc.resolve(pos);\n if (deleted)\n return Selection.near($pos);\n return new NodeSelection($pos);\n }\n content() {\n return new Slice(Fragment.from(this.node), 0, 0);\n }\n eq(other) {\n return other instanceof NodeSelection && other.anchor == this.anchor;\n }\n toJSON() {\n return { type: \"node\", anchor: this.anchor };\n }\n getBookmark() { return new NodeBookmark(this.anchor); }\n /**\n @internal\n */\n static 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 Create a node selection from non-resolved positions.\n */\n static create(doc, from) {\n return new NodeSelection(doc.resolve(from));\n }\n /**\n Determines whether the given node may be selected as a node\n selection.\n */\n static isSelectable(node) {\n return !node.isText && node.type.spec.selectable !== false;\n }\n}\nNodeSelection.prototype.visible = false;\nSelection.jsonID(\"node\", NodeSelection);\nclass NodeBookmark {\n constructor(anchor) {\n this.anchor = anchor;\n }\n map(mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);\n }\n resolve(doc) {\n let $pos = doc.resolve(this.anchor), node = $pos.nodeAfter;\n if (node && NodeSelection.isSelectable(node))\n return new NodeSelection($pos);\n return Selection.near($pos);\n }\n}\n/**\nA selection type that represents selecting the whole document\n(which can not necessarily be expressed with a text selection, when\nthere are for example leaf block nodes at the start or end of the\ndocument).\n*/\nclass AllSelection extends Selection {\n /**\n Create an all-selection over the given document.\n */\n constructor(doc) {\n super(doc.resolve(0), doc.resolve(doc.content.size));\n }\n replace(tr, content = Slice.empty) {\n if (content == Slice.empty) {\n tr.delete(0, tr.doc.content.size);\n let sel = Selection.atStart(tr.doc);\n if (!sel.eq(tr.selection))\n tr.setSelection(sel);\n }\n else {\n super.replace(tr, content);\n }\n }\n toJSON() { return { type: \"all\" }; }\n /**\n @internal\n */\n static fromJSON(doc) { return new AllSelection(doc); }\n map(doc) { return new AllSelection(doc); }\n eq(other) { return other instanceof AllSelection; }\n getBookmark() { return AllBookmark; }\n}\nSelection.jsonID(\"all\", AllSelection);\nconst AllBookmark = {\n map() { return this; },\n resolve(doc) { return new AllSelection(doc); }\n};\n// FIXME we'll need some awareness of text direction when scanning for selections\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 = false) {\n if (node.inlineContent)\n return TextSelection.create(doc, pos);\n for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {\n let child = node.child(i);\n if (!child.isAtom) {\n let inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);\n if (inner)\n return inner;\n }\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 return null;\n}\nfunction selectionToInsertionEnd(tr, startLen, bias) {\n let last = tr.steps.length - 1;\n if (last < startLen)\n return;\n let step = tr.steps[last];\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))\n return;\n let map = tr.mapping.maps[last], end;\n map.forEach((_from, _to, _newFrom, newTo) => { if (end == null)\n end = newTo; });\n tr.setSelection(Selection.near(tr.doc.resolve(end), bias));\n}\n\nconst UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;\n/**\nAn editor state transaction, which can be applied to a state to\ncreate an updated state. Use\n[`EditorState.tr`](https://prosemirror.net/docs/ref/#state.EditorState.tr) to create an instance.\n\nTransactions track changes to the document (they are a subclass of\n[`Transform`](https://prosemirror.net/docs/ref/#transform.Transform)), but also other state changes,\nlike selection updates and adjustments of the set of [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks). In addition, you can store\nmetadata properties in a transaction, which are extra pieces of\ninformation that client code or plugins can use to describe what a\ntransaction represents, so that they can update their [own\nstate](https://prosemirror.net/docs/ref/#state.StateField) accordingly.\n\nThe [editor view](https://prosemirror.net/docs/ref/#view.EditorView) uses a few metadata\nproperties: it will attach a property `\"pointer\"` with the value\n`true` to selection transactions directly caused by mouse or touch\ninput, a `\"composition\"` property holding an ID identifying the\ncomposition that caused it to transactions caused by composed DOM\ninput, and a `\"uiEvent\"` property of that may be `\"paste\"`,\n`\"cut\"`, or `\"drop\"`.\n*/\nclass Transaction extends Transform {\n /**\n @internal\n */\n constructor(state) {\n super(state.doc);\n // The step count for which the current selection is valid.\n this.curSelectionFor = 0;\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 this.time = Date.now();\n this.curSelection = state.selection;\n this.storedMarks = state.storedMarks;\n }\n /**\n The transaction's current selection. This defaults to the editor\n selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the\n transaction, but can be overwritten with\n [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).\n */\n get selection() {\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 Update the transaction's current selection. Will determine the\n selection that the editor gets when the transaction is applied.\n */\n 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 Whether the selection was explicitly updated by this transaction.\n */\n get selectionSet() {\n return (this.updated & UPDATED_SEL) > 0;\n }\n /**\n Set the current stored marks.\n */\n setStoredMarks(marks) {\n this.storedMarks = marks;\n this.updated |= UPDATED_MARKS;\n return this;\n }\n /**\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 */\n ensureMarks(marks) {\n if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))\n this.setStoredMarks(marks);\n return this;\n }\n /**\n Add a mark to the set of stored marks.\n */\n addStoredMark(mark) {\n return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Remove a mark or mark type from the set of stored marks.\n */\n removeStoredMark(mark) {\n return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Whether the stored marks were explicitly set for this transaction.\n */\n get storedMarksSet() {\n return (this.updated & UPDATED_MARKS) > 0;\n }\n /**\n @internal\n */\n addStep(step, doc) {\n super.addStep(step, doc);\n this.updated = this.updated & ~UPDATED_MARKS;\n this.storedMarks = null;\n }\n /**\n Update the timestamp for the transaction.\n */\n setTime(time) {\n this.time = time;\n return this;\n }\n /**\n Replace the current selection with the given slice.\n */\n replaceSelection(slice) {\n this.selection.replace(this, slice);\n return this;\n }\n /**\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 */\n replaceSelectionWith(node, inheritMarks = true) {\n let selection = this.selection;\n if (inheritMarks)\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 Delete the selection.\n */\n deleteSelection() {\n this.selection.replace(this);\n return this;\n }\n /**\n Replace the given range, or the selection if no range is given,\n with a text node containing the given string.\n */\n insertText(text, from, to) {\n let schema = this.doc.type.schema;\n if (from == null) {\n if (!text)\n return this.deleteSelection();\n return this.replaceSelectionWith(schema.text(text), true);\n }\n else {\n if (to == null)\n to = from;\n if (!text)\n return this.deleteRange(from, to);\n let marks = this.storedMarks;\n if (!marks) {\n let $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.selection.to == from + text.length)\n this.setSelection(Selection.near(this.selection.$to));\n return this;\n }\n }\n /**\n Store a metadata property in this transaction, keyed either by\n name or by plugin.\n */\n setMeta(key, value) {\n this.meta[typeof key == \"string\" ? key : key.key] = value;\n return this;\n }\n /**\n Retrieve a metadata property for a given name or plugin.\n */\n getMeta(key) {\n return this.meta[typeof key == \"string\" ? key : key.key];\n }\n /**\n Returns true if this transaction doesn't contain any metadata,\n and can thus safely be extended.\n */\n get isGeneric() {\n for (let _ in this.meta)\n return false;\n return true;\n }\n /**\n Indicate that the editor should scroll the selection into view\n when updated to the state produced by this transaction.\n */\n scrollIntoView() {\n this.updated |= UPDATED_SCROLL;\n return this;\n }\n /**\n True when this transaction has had `scrollIntoView` called on it.\n */\n get scrolledIntoView() {\n return (this.updated & UPDATED_SCROLL) > 0;\n }\n}\n\nfunction bind(f, self) {\n return !self || !f ? f : f.bind(self);\n}\nclass FieldDesc {\n constructor(name, desc, self) {\n this.name = name;\n this.init = bind(desc.init, self);\n this.apply = bind(desc.apply, self);\n }\n}\nconst baseFields = [\n new FieldDesc(\"doc\", {\n init(config) { return config.doc || config.schema.topNodeType.createAndFill(); },\n apply(tr) { return tr.doc; }\n }),\n new FieldDesc(\"selection\", {\n init(config, instance) { return config.selection || Selection.atStart(instance.doc); },\n apply(tr) { return tr.selection; }\n }),\n new FieldDesc(\"storedMarks\", {\n init(config) { return config.storedMarks || null; },\n apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null; }\n }),\n new FieldDesc(\"scrollToSelection\", {\n init() { return 0; },\n apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev; }\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.\nclass Configuration {\n constructor(schema, plugins) {\n this.schema = schema;\n this.plugins = [];\n this.pluginsByKey = Object.create(null);\n this.fields = baseFields.slice();\n if (plugins)\n plugins.forEach(plugin => {\n if (this.pluginsByKey[plugin.key])\n throw new RangeError(\"Adding different instances of a keyed plugin (\" + plugin.key + \")\");\n this.plugins.push(plugin);\n this.pluginsByKey[plugin.key] = plugin;\n if (plugin.spec.state)\n this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));\n });\n }\n}\n/**\nThe state of a ProseMirror editor is represented by an object of\nthis type. A state is a persistent data structure—it isn't\nupdated, but rather a new state value is computed from an old one\nusing the [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) method.\n\nA state holds a number of built-in fields, and plugins can\n[define](https://prosemirror.net/docs/ref/#state.PluginSpec.state) additional fields.\n*/\nclass EditorState {\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n config) {\n this.config = config;\n }\n /**\n The schema of the state's document.\n */\n get schema() {\n return this.config.schema;\n }\n /**\n The plugins that are active in this state.\n */\n get plugins() {\n return this.config.plugins;\n }\n /**\n Apply the given transaction to produce a new state.\n */\n apply(tr) {\n return this.applyTransaction(tr).state;\n }\n /**\n @internal\n */\n filterTransaction(tr, ignore = -1) {\n for (let i = 0; i < this.config.plugins.length; i++)\n if (i != ignore) {\n let 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 Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that\n returns the precise transactions that were applied (which might\n be influenced by the [transaction\n hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of\n plugins) along with the new state.\n */\n applyTransaction(rootTr) {\n if (!this.filterTransaction(rootTr))\n return { state: this, transactions: [] };\n let 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 let haveNew = false;\n for (let i = 0; i < this.config.plugins.length; i++) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.appendTransaction) {\n let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;\n let 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 (let 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)\n seen[i] = { state: newState, n: trs.length };\n }\n }\n if (!haveNew)\n return { state: newState, transactions: trs };\n }\n }\n /**\n @internal\n */\n applyInner(tr) {\n if (!tr.before.eq(this.doc))\n throw new RangeError(\"Applying a mismatched transaction\");\n let newInstance = new EditorState(this.config), fields = this.config.fields;\n for (let i = 0; i < fields.length; i++) {\n let field = fields[i];\n newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);\n }\n return newInstance;\n }\n /**\n Accessor that constructs and returns a new [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.\n */\n get tr() { return new Transaction(this); }\n /**\n Create a new state.\n */\n static create(config) {\n let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins);\n let instance = new EditorState($config);\n for (let 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 Create a new state based on this one, but with an adjusted set\n of active plugins. State fields that exist in both sets of\n plugins are kept unchanged. Those that no longer exist are\n dropped, and those that are new are initialized using their\n [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new\n configuration object..\n */\n reconfigure(config) {\n let $config = new Configuration(this.schema, config.plugins);\n let fields = $config.fields, instance = new EditorState($config);\n for (let i = 0; i < fields.length; i++) {\n let name = fields[i].name;\n instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);\n }\n return instance;\n }\n /**\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.\n */\n toJSON(pluginFields) {\n let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };\n if (this.storedMarks)\n result.storedMarks = this.storedMarks.map(m => m.toJSON());\n if (pluginFields && typeof pluginFields == 'object')\n for (let prop in pluginFields) {\n if (prop == \"doc\" || prop == \"selection\")\n throw new RangeError(\"The JSON fields `doc` and `selection` are reserved\");\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (state && state.toJSON)\n result[prop] = state.toJSON.call(plugin, this[plugin.key]);\n }\n return result;\n }\n /**\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 static fromJSON(config, json, pluginFields) {\n if (!json)\n throw new RangeError(\"Invalid input for EditorState.fromJSON\");\n if (!config.schema)\n throw new RangeError(\"Required config field 'schema' missing\");\n let $config = new Configuration(config.schema, config.plugins);\n let instance = new EditorState($config);\n $config.fields.forEach(field => {\n if (field.name == \"doc\") {\n instance.doc = Node.fromJSON(config.schema, json.doc);\n }\n else if (field.name == \"selection\") {\n instance.selection = Selection.fromJSON(instance.doc, json.selection);\n }\n else if (field.name == \"storedMarks\") {\n if (json.storedMarks)\n instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);\n }\n else {\n if (pluginFields)\n for (let prop in pluginFields) {\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (plugin.key == field.name && state && state.fromJSON &&\n Object.prototype.hasOwnProperty.call(json, prop)) {\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\nfunction bindProps(obj, self, target) {\n for (let prop in obj) {\n let val = obj[prop];\n if (val instanceof Function)\n val = val.bind(self);\n else if (prop == \"handleDOMEvents\")\n val = bindProps(val, self, {});\n target[prop] = val;\n }\n return target;\n}\n/**\nPlugins bundle functionality that can be added to an editor.\nThey are part of the [editor state](https://prosemirror.net/docs/ref/#state.EditorState) and\nmay influence that state and the view that contains it.\n*/\nclass Plugin {\n /**\n Create a plugin.\n */\n constructor(\n /**\n The plugin's [spec object](https://prosemirror.net/docs/ref/#state.PluginSpec).\n */\n spec) {\n this.spec = spec;\n /**\n The [props](https://prosemirror.net/docs/ref/#view.EditorProps) exported by this plugin.\n */\n this.props = {};\n if (spec.props)\n bindProps(spec.props, this, this.props);\n this.key = spec.key ? spec.key.key : createKey(\"plugin\");\n }\n /**\n Extract the plugin's state field from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\nconst keys = Object.create(null);\nfunction createKey(name) {\n if (name in keys)\n return name + \"$\" + ++keys[name];\n keys[name] = 0;\n return name + \"$\";\n}\n/**\nA key is used to [tag](https://prosemirror.net/docs/ref/#state.PluginSpec.key) plugins in a way\nthat makes it possible to find them, given an editor state.\nAssigning a key does mean only one plugin of that type can be\nactive in a state.\n*/\nclass PluginKey {\n /**\n Create a plugin key.\n */\n constructor(name = \"key\") { this.key = createKey(name); }\n /**\n Get the active plugin with this key, if any, from an editor\n state.\n */\n get(state) { return state.config.pluginsByKey[this.key]; }\n /**\n Get the plugin's state from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\n\nexport { AllSelection, EditorState, NodeSelection, Plugin, PluginKey, Selection, SelectionRange, TextSelection, Transaction };\n", + "import { TextSelection, NodeSelection, Selection, AllSelection } from 'prosemirror-state';\nimport { DOMSerializer, Fragment, Mark, Slice, DOMParser } from 'prosemirror-model';\nimport { dropPoint } from 'prosemirror-transform';\n\nconst domIndex = function (node) {\n for (var index = 0;; index++) {\n node = node.previousSibling;\n if (!node)\n return index;\n }\n};\nconst parentNode = function (node) {\n let parent = node.assignedSlot || node.parentNode;\n return parent && parent.nodeType == 11 ? parent.host : parent;\n};\nlet reusedRange = null;\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.\nconst textRange = function (node, from, to) {\n let 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};\nconst clearReusedRange = function () {\n reusedRange = null;\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)\nconst isEquivalentPosition = function (node, off, targetNode, targetOff) {\n return targetNode && (scanFor(node, off, targetNode, targetOff, -1) ||\n scanFor(node, off, targetNode, targetOff, 1));\n};\nconst atomElements = /^(img|br|input|textarea|hr)$/i;\nfunction scanFor(node, off, targetNode, targetOff, dir) {\n var _a;\n for (;;) {\n if (node == targetNode && off == targetOff)\n return true;\n if (off == (dir < 0 ? 0 : nodeSize(node))) {\n let parent = node.parentNode;\n if (!parent || !isElt(parent) || hasBlockDesc(node) || atomElements.test(node.nodeName) ||\n node.contentEditable == \"false\")\n return false;\n off = domIndex(node) + (dir < 0 ? 0 : 1);\n node = parent;\n }\n else if (isElt(node)) {\n let child = node.childNodes[off + (dir < 0 ? -1 : 0)];\n if (isElt(child) && child.contentEditable == \"false\") {\n if ((_a = child.pmViewDesc) === null || _a === void 0 ? void 0 : _a.ignoreForSelection)\n off += dir;\n else\n return false;\n }\n else {\n node = child;\n off = dir < 0 ? nodeSize(node) : 0;\n }\n }\n else {\n return false;\n }\n }\n}\nfunction nodeSize(node) {\n return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;\n}\nfunction isElt(node) { return node.nodeType == 1; }\nfunction isText(node) { return node.nodeType == 3; }\nfunction contains(parent, child) {\n return child ? parent.contains(isElt(child) ? child : child.parentNode) : false;\n}\nfunction textNodeBefore$1(node, offset) {\n for (;;) {\n if (isText(node) && offset)\n return node;\n if (isElt(node) && offset > 0) {\n if (node.contentEditable == \"false\")\n return null;\n node = node.childNodes[offset - 1];\n offset = nodeSize(node);\n }\n else if (node.parentNode && !hasBlockDesc(node)) {\n offset = domIndex(node);\n node = node.parentNode;\n }\n else {\n return null;\n }\n }\n}\nfunction textNodeAfter$1(node, offset) {\n for (;;) {\n if (isText(node) && offset < node.nodeValue.length)\n return node;\n if (isElt(node) && offset < node.childNodes.length) {\n if (node.contentEditable == \"false\")\n return null;\n node = node.childNodes[offset];\n offset = 0;\n }\n else if (node.parentNode && !hasBlockDesc(node)) {\n offset = domIndex(node) + 1;\n node = node.parentNode;\n }\n else {\n return null;\n }\n }\n}\nfunction isOnEdge(node, offset, parent) {\n for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd;) {\n if (node == parent)\n return true;\n let index = domIndex(node);\n node = node.parentNode;\n if (!node)\n return false;\n atStart = atStart && index == 0;\n atEnd = atEnd && index == nodeSize(node);\n }\n}\nfunction hasBlockDesc(dom) {\n let desc;\n for (let cur = dom; cur; cur = cur.parentNode)\n if (desc = cur.pmViewDesc)\n break;\n return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom);\n}\n// Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523\n// (isCollapsed inappropriately returns true in shadow dom)\nconst selectionCollapsed = function (domSel) {\n return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset);\n};\nfunction keyEvent(keyCode, key) {\n let event = document.createEvent(\"Event\");\n event.initEvent(\"keydown\", true, true);\n event.keyCode = keyCode;\n event.key = event.code = key;\n return event;\n}\nfunction deepActiveElement(doc) {\n let elt = doc.activeElement;\n while (elt && elt.shadowRoot)\n elt = elt.shadowRoot.activeElement;\n return elt;\n}\nfunction caretFromPoint(doc, x, y) {\n if (doc.caretPositionFromPoint) {\n try { // Firefox throws for this call in hard-to-predict circumstances (#994)\n let pos = doc.caretPositionFromPoint(x, y);\n // Clip the offset, because Chrome will return a text offset\n // into nodes, which can't be treated as a regular DOM\n // offset\n if (pos)\n return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) };\n }\n catch (_) { }\n }\n if (doc.caretRangeFromPoint) {\n let range = doc.caretRangeFromPoint(x, y);\n if (range)\n return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) };\n }\n}\n\nconst nav = typeof navigator != \"undefined\" ? navigator : null;\nconst doc = typeof document != \"undefined\" ? document : null;\nconst agent = (nav && nav.userAgent) || \"\";\nconst ie_edge = /Edge\\/(\\d+)/.exec(agent);\nconst ie_upto10 = /MSIE \\d/.exec(agent);\nconst ie_11up = /Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(agent);\nconst ie = !!(ie_upto10 || ie_11up || ie_edge);\nconst ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0;\nconst gecko = !ie && /gecko\\/(\\d+)/i.test(agent);\ngecko && +(/Firefox\\/(\\d+)/.exec(agent) || [0, 0])[1];\nconst _chrome = !ie && /Chrome\\/(\\d+)/.exec(agent);\nconst chrome = !!_chrome;\nconst chrome_version = _chrome ? +_chrome[1] : 0;\nconst safari = !ie && !!nav && /Apple Computer/.test(nav.vendor);\n// Is true for both iOS and iPadOS for convenience\nconst ios = safari && (/Mobile\\/\\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2);\nconst mac = ios || (nav ? /Mac/.test(nav.platform) : false);\nconst windows = nav ? /Win/.test(nav.platform) : false;\nconst android = /Android \\d/.test(agent);\nconst webkit = !!doc && \"webkitFontSmoothing\" in doc.documentElement.style;\nconst webkit_version = webkit ? +(/\\bAppleWebKit\\/(\\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0;\n\nfunction windowRect(doc) {\n let vp = doc.defaultView && doc.defaultView.visualViewport;\n if (vp)\n return {\n left: 0, right: vp.width,\n top: 0, bottom: vp.height\n };\n return { left: 0, right: doc.documentElement.clientWidth,\n top: 0, bottom: doc.documentElement.clientHeight };\n}\nfunction getSide(value, side) {\n return typeof value == \"number\" ? value : value[side];\n}\nfunction clientRect(node) {\n let rect = node.getBoundingClientRect();\n // Adjust for elements with style \"transform: scale()\"\n let scaleX = (rect.width / node.offsetWidth) || 1;\n let scaleY = (rect.height / node.offsetHeight) || 1;\n // Make sure scrollbar width isn't included in the rectangle\n return { left: rect.left, right: rect.left + node.clientWidth * scaleX,\n top: rect.top, bottom: rect.top + node.clientHeight * scaleY };\n}\nfunction scrollRectIntoView(view, rect, startDOM) {\n // Skip empty rects with all sides at 0, for example, when the element has no CSS box (display: none)\n if (!nonZero(rect) && rect.left == 0)\n return;\n let scrollThreshold = view.someProp(\"scrollThreshold\") || 0, scrollMargin = view.someProp(\"scrollMargin\") || 5;\n let doc = view.dom.ownerDocument;\n for (let parent = startDOM || view.dom;;) {\n if (!parent)\n break;\n if (!isElt(parent)) {\n parent = parentNode(parent);\n continue;\n }\n let atTop = parent == doc.body;\n let bounding = atTop ? windowRect(doc) : clientRect(parent);\n let 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 - rect.top > bounding.bottom - bounding.top\n ? rect.top + getSide(scrollMargin, \"top\") - bounding.top\n : 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 }\n else {\n let startX = parent.scrollLeft, startY = parent.scrollTop;\n if (moveY)\n parent.scrollTop += moveY;\n if (moveX)\n parent.scrollLeft += moveX;\n let 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 let pos = atTop ? \"fixed\" : getComputedStyle(parent).position;\n if (/^(fixed|sticky)$/.test(pos))\n break;\n parent = pos == \"absolute\" ? parent.offsetParent : parentNode(parent);\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 let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top);\n let refDOM, refTop;\n for (let x = (rect.left + rect.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect.bottom); y += 5) {\n let dom = view.root.elementFromPoint(x, y);\n if (!dom || dom == view.dom || !view.dom.contains(dom))\n continue;\n let 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}\nfunction scrollStack(dom) {\n let stack = [], doc = dom.ownerDocument;\n for (let cur = dom; cur; cur = parentNode(cur)) {\n stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft });\n if (dom == doc)\n break;\n }\n return stack;\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({ refDOM, refTop, stack }) {\n let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;\n restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);\n}\nfunction restoreScrollStack(stack, dTop) {\n for (let i = 0; i < stack.length; i++) {\n let { dom, top, left } = stack[i];\n if (dom.scrollTop != top + dTop)\n dom.scrollTop = top + dTop;\n if (dom.scrollLeft != left)\n dom.scrollLeft = left;\n }\n}\nlet 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)\n return dom.setActive(); // in IE\n if (preventScrollSupported)\n return dom.focus(preventScrollSupported);\n let 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}\nfunction findOffsetInNode(node, coords) {\n let closest;\n let dxClosest = 2e8, coordsClosest, offset = 0;\n let rowBot = coords.top, rowTop = coords.top;\n let firstBelow, coordsBelow;\n for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {\n let rects;\n if (isElt(child))\n rects = child.getClientRects();\n else if (isText(child))\n rects = textRange(child).getClientRects();\n else\n continue;\n for (let i = 0; i < rects.length; i++) {\n let 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 let 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 && isText(closest) ? {\n left: rect.right < coords.left ? rect.right : rect.left,\n top: coords.top\n } : coords;\n if (isElt(child) && dx)\n offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0);\n continue;\n }\n }\n else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) {\n firstBelow = child;\n coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top };\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 && firstBelow) {\n closest = firstBelow;\n coordsClosest = coordsBelow;\n dxClosest = 0;\n }\n if (closest && isText(closest))\n return findOffsetInText(closest, coordsClosest);\n if (!closest || dxClosest)\n return { node, offset };\n return findOffsetInNode(closest, coordsClosest);\n}\nfunction findOffsetInText(node, coords) {\n let len = node.nodeValue.length;\n let range = document.createRange(), result;\n for (let i = 0; i < len; i++) {\n range.setEnd(node, i + 1);\n range.setStart(node, i);\n let rect = singleRect(range, 1);\n if (rect.top == rect.bottom)\n continue;\n if (inRect(coords, rect)) {\n result = { node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) };\n break;\n }\n }\n range.detach();\n return result || { node, offset: 0 };\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}\nfunction targetKludge(dom, coords) {\n let parent = dom.parentNode;\n if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left)\n return parent;\n return dom;\n}\nfunction posFromElement(view, elt, coords) {\n let { node, offset } = findOffsetInNode(elt, coords), bias = -1;\n if (isElt(node) && !node.firstChild) {\n let 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}\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 let outsideBlock = -1;\n for (let cur = node, sawBlock = false;;) {\n if (cur == view.dom)\n break;\n let desc = view.docView.nearestDesc(cur, true), rect;\n if (!desc)\n return null;\n if (isElt(desc.dom) && (desc.node.isBlock && desc.parent || !desc.contentDOM) &&\n // Ignore elements with zero-size bounding rectangles\n ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) {\n if (desc.node.isBlock && desc.parent && !/^T(R|BODY|HEAD|FOOT)$/.test(desc.dom.nodeName)) {\n // Only apply the horizontal test to the innermost block. Vertical for any parent.\n if (!sawBlock && rect.left > coords.left || rect.top > coords.top)\n outsideBlock = desc.posBefore;\n else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top)\n outsideBlock = desc.posAfter;\n sawBlock = true;\n }\n if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) {\n // If we are inside a leaf, return the side of the leaf closer to the coords\n let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2\n : coords.left < (rect.left + rect.right) / 2;\n return before ? desc.posBefore : desc.posAfter;\n }\n }\n cur = desc.dom.parentNode;\n }\n return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node, offset, -1);\n}\nfunction elementFromPoint(element, coords, box) {\n let len = element.childNodes.length;\n if (len && box.top < box.bottom) {\n for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI;;) {\n let child = element.childNodes[i];\n if (isElt(child)) {\n let rects = child.getClientRects();\n for (let j = 0; j < rects.length; j++) {\n let rect = rects[j];\n if (inRect(coords, rect))\n return elementFromPoint(child, coords, rect);\n }\n }\n if ((i = (i + 1) % len) == startI)\n break;\n }\n }\n return element;\n}\n// Given an x,y position on the editor, get the position in the document.\nfunction posAtCoords(view, coords) {\n let doc = view.dom.ownerDocument, node, offset = 0;\n let caret = caretFromPoint(doc, coords.left, coords.top);\n if (caret)\n ({ node, offset } = caret);\n let elt = (view.root.elementFromPoint ? view.root : doc)\n .elementFromPoint(coords.left, coords.top);\n let pos;\n if (!elt || !view.dom.contains(elt)) {\n let box = view.dom.getBoundingClientRect();\n if (!inRect(coords, box))\n return null;\n elt = elementFromPoint(view.dom, coords, box);\n if (!elt)\n return null;\n }\n // Safari's caretRangeFromPoint returns nonsense when on a draggable element\n if (safari) {\n for (let p = elt; node && p; p = parentNode(p))\n if (p.draggable)\n node = undefined;\n }\n elt = targetKludge(elt, coords);\n if (node) {\n if (gecko && isElt(node)) {\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 let next = node.childNodes[offset], box;\n if (next.nodeName == \"IMG\" && (box = next.getBoundingClientRect()).right <= coords.left &&\n box.bottom > coords.top)\n offset++;\n }\n }\n let prev;\n // When clicking above the right side of an uneditable node, Chrome will report a cursor position after that node.\n if (webkit && offset && isElt(node) && isElt(prev = node.childNodes[offset - 1]) &&\n prev.contentEditable == \"false\" && prev.getBoundingClientRect().top >= coords.top)\n offset--;\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 && isElt(node.lastChild) &&\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 || !isElt(node) || node.childNodes[offset - 1].nodeName != \"BR\")\n pos = posFromCaret(view, node, offset, coords);\n }\n if (pos == null)\n pos = posFromElement(view, elt, coords);\n let desc = view.docView.nearestDesc(elt, true);\n return { pos, inside: desc ? desc.posAtStart - desc.border : -1 };\n}\nfunction nonZero(rect) {\n return rect.top < rect.bottom || rect.left < rect.right;\n}\nfunction singleRect(target, bias) {\n let rects = target.getClientRects();\n if (rects.length) {\n let first = rects[bias < 0 ? 0 : rects.length - 1];\n if (nonZero(first))\n return first;\n }\n return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect();\n}\nconst BIDI = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/;\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 let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1);\n let supportEmptyRange = webkit || gecko;\n if (isText(node)) {\n // These browsers support querying empty text ranges. Prefer that in\n // bidi context or when at the end of a node.\n if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) {\n let 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 (gecko && offset && /\\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) {\n let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1);\n if (rectBefore.top == rect.top) {\n let 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 else {\n let from = offset, to = offset, takeSide = side < 0 ? 1 : -1;\n if (side < 0 && !offset) {\n to++;\n takeSide = -1;\n }\n else if (side >= 0 && offset == node.nodeValue.length) {\n from--;\n takeSide = 1;\n }\n else if (side < 0) {\n from--;\n }\n else {\n to++;\n }\n return flattenV(singleRect(textRange(node, from, to), takeSide), takeSide < 0);\n }\n }\n let $dom = view.state.doc.resolve(pos - (atom || 0));\n // Return a horizontal line in block context\n if (!$dom.parent.inlineContent) {\n if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n let before = node.childNodes[offset - 1];\n if (isElt(before))\n return flattenH(before.getBoundingClientRect(), false);\n }\n if (atom == null && offset < nodeSize(node)) {\n let after = node.childNodes[offset];\n if (isElt(after))\n return flattenH(after.getBoundingClientRect(), true);\n }\n return flattenH(node.getBoundingClientRect(), side >= 0);\n }\n // Inline, not in text node (this is not Bidi-safe)\n if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n let before = node.childNodes[offset - 1];\n let target = isText(before) ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1))\n // BR nodes tend to only return the rectangle before them.\n // Only use them if they are the last element in their parent\n : isElt(before) && (before.nodeName != \"BR\" || !before.nextSibling) ? before : null;\n if (target)\n return flattenV(singleRect(target, 1), false);\n }\n if (atom == null && offset < nodeSize(node)) {\n let after = node.childNodes[offset];\n while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords)\n after = after.nextSibling;\n let target = !after ? null : isText(after) ? textRange(after, 0, (supportEmptyRange ? 0 : 1))\n : isElt(after) ? after : null;\n if (target)\n return flattenV(singleRect(target, -1), true);\n }\n // All else failed, just try to get a rectangle for the target node\n return flattenV(singleRect(isText(node) ? textRange(node) : node, -side), side >= 0);\n}\nfunction flattenV(rect, left) {\n if (rect.width == 0)\n return rect;\n let x = left ? rect.left : rect.right;\n return { top: rect.top, bottom: rect.bottom, left: x, right: x };\n}\nfunction flattenH(rect, top) {\n if (rect.height == 0)\n return rect;\n let y = top ? rect.top : rect.bottom;\n return { top: y, bottom: y, left: rect.left, right: rect.right };\n}\nfunction withFlushedState(view, state, f) {\n let viewState = view.state, active = view.root.activeElement;\n if (viewState != state)\n view.updateState(state);\n if (active != view.dom)\n view.focus();\n try {\n return f();\n }\n finally {\n if (viewState != state)\n view.updateState(viewState);\n if (active != view.dom && active)\n active.focus();\n }\n}\n// Whether vertical position motion in a given direction\n// from a position would leave a text block.\nfunction endOfTextblockVertical(view, state, dir) {\n let sel = state.selection;\n let $pos = dir == \"up\" ? sel.$from : sel.$to;\n return withFlushedState(view, state, () => {\n let { node: dom } = view.docView.domFromPos($pos.pos, dir == \"up\" ? -1 : 1);\n for (;;) {\n let nearest = view.docView.nearestDesc(dom, true);\n if (!nearest)\n break;\n if (nearest.node.isBlock) {\n dom = nearest.contentDOM || nearest.dom;\n break;\n }\n dom = nearest.dom.parentNode;\n }\n let coords = coordsAtPos(view, $pos.pos, 1);\n for (let child = dom.firstChild; child; child = child.nextSibling) {\n let boxes;\n if (isElt(child))\n boxes = child.getClientRects();\n else if (isText(child))\n boxes = textRange(child, 0, child.nodeValue.length).getClientRects();\n else\n continue;\n for (let i = 0; i < boxes.length; i++) {\n let box = boxes[i];\n if (box.bottom > box.top + 1 &&\n (dir == \"up\" ? coords.top - box.top > (box.bottom - coords.top) * 2\n : box.bottom - coords.bottom > (coords.bottom - box.top) * 2))\n return false;\n }\n }\n return true;\n });\n}\nconst maybeRTL = /[\\u0590-\\u08ac]/;\nfunction endOfTextblockHorizontal(view, state, dir) {\n let { $head } = state.selection;\n if (!$head.parent.isTextblock)\n return false;\n let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size;\n let sel = view.domSelection();\n if (!sel)\n return $head.pos == $head.start() || $head.pos == $head.end();\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 return withFlushedState(view, state, () => {\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 let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange();\n let oldBidiLevel = sel.caretBidiLevel // Only for Firefox\n ;\n sel.modify(\"move\", dir, \"character\");\n let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;\n let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange();\n let result = newNode && !contains(parentDOM, newNode) || (oldNode == newNode && oldOff == newOff);\n // Restore the previous selection\n try {\n sel.collapse(anchorNode, anchorOffset);\n if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend)\n sel.extend(oldNode, oldOff);\n }\n catch (_) { }\n if (oldBidiLevel != null)\n sel.caretBidiLevel = oldBidiLevel;\n return result;\n });\n}\nlet cachedState = null;\nlet cachedDir = null;\nlet cachedResult = false;\nfunction endOfTextblock(view, state, dir) {\n if (cachedState == state && cachedDir == dir)\n return cachedResult;\n cachedState = state;\n cachedDir = dir;\n return cachedResult = dir == \"up\" || dir == \"down\"\n ? endOfTextblockVertical(view, state, dir)\n : endOfTextblockHorizontal(view, state, dir);\n}\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`.\nconst NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3;\n// Superclass for the various kinds of descriptions. Defines their\n// basic structure and shared methods.\nclass ViewDesc {\n constructor(parent, children, dom, \n // This is the node that holds the child views. It may be null for\n // descs that don't have children.\n contentDOM) {\n this.parent = parent;\n this.children = children;\n this.dom = dom;\n this.contentDOM = contentDOM;\n this.dirty = NOT_DIRTY;\n // An expando property on the DOM node provides a link back to its\n // description.\n dom.pmViewDesc = this;\n }\n // Used to check whether a given description corresponds to a\n // widget/mark/node.\n matchesWidget(widget) { return false; }\n matchesMark(mark) { return false; }\n matchesNode(node, outerDeco, innerDeco) { return false; }\n matchesHack(nodeName) { return false; }\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.\n parseRule(addedNodes) { return null; }\n // Used by the editor's event handler to ignore events that come\n // from certain descs.\n stopEvent(event) { return false; }\n // The size of the content represented by this desc.\n get size() {\n let size = 0;\n for (let i = 0; i < this.children.length; i++)\n size += this.children[i].size;\n return size;\n }\n // For block nodes, this represents the space taken up by their\n // start/end tokens.\n get border() { return 0; }\n destroy() {\n this.parent = undefined;\n if (this.dom.pmViewDesc == this)\n this.dom.pmViewDesc = undefined;\n for (let i = 0; i < this.children.length; i++)\n this.children[i].destroy();\n }\n posBeforeChild(child) {\n for (let i = 0, pos = this.posAtStart;; i++) {\n let cur = this.children[i];\n if (cur == child)\n return pos;\n pos += cur.size;\n }\n }\n get posBefore() {\n return this.parent.posBeforeChild(this);\n }\n get posAtStart() {\n return this.parent ? this.parent.posBeforeChild(this) + this.border : 0;\n }\n get posAfter() {\n return this.posBefore + this.size;\n }\n get posAtEnd() {\n return this.posAtStart + this.size - 2 * this.border;\n }\n 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 && contains(this.contentDOM, dom)) {\n if (bias < 0) {\n let domBefore, desc;\n if (dom == this.contentDOM) {\n domBefore = dom.childNodes[offset - 1];\n }\n else {\n while (dom.parentNode != this.contentDOM)\n dom = dom.parentNode;\n domBefore = dom.previousSibling;\n }\n while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this))\n domBefore = domBefore.previousSibling;\n return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart;\n }\n else {\n let domAfter, desc;\n if (dom == this.contentDOM) {\n domAfter = dom.childNodes[offset];\n }\n else {\n while (dom.parentNode != this.contentDOM)\n dom = dom.parentNode;\n domAfter = dom.nextSibling;\n }\n while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this))\n domAfter = domAfter.nextSibling;\n return domAfter ? this.posBeforeChild(desc) : 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 let atEnd;\n if (dom == this.dom && this.contentDOM) {\n atEnd = offset > domIndex(this.contentDOM);\n }\n else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {\n let rel = dom.compareDocumentPosition(this.contentDOM);\n if (rel & 16) { // this.contentDOM is inside dom\n atEnd = offset > Array.from(dom.childNodes).findIndex(n => n.contains(this.contentDOM));\n }\n else { // Check if after or before\n atEnd = !(rel & 4);\n }\n }\n else if (this.dom.firstChild) {\n if (offset == 0)\n for (let search = dom;; search = search.parentNode) {\n if (search == this.dom) {\n atEnd = false;\n break;\n }\n if (search.previousSibling)\n break;\n }\n if (atEnd == null && offset == dom.childNodes.length)\n for (let search = dom;; search = search.parentNode) {\n if (search == this.dom) {\n atEnd = true;\n break;\n }\n if (search.nextSibling)\n break;\n }\n }\n return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart;\n }\n nearestDesc(dom, onlyNodes = false) {\n for (let first = true, cur = dom; cur; cur = cur.parentNode) {\n let desc = this.getDesc(cur), nodeDOM;\n if (desc && (!onlyNodes || desc.node)) {\n // If dom is outside of this desc's nodeDOM, don't count it.\n if (first && (nodeDOM = desc.nodeDOM) &&\n !(isElt(nodeDOM) ? contains(nodeDOM, dom) : nodeDOM == dom))\n first = false;\n else\n return desc;\n }\n }\n }\n getDesc(dom) {\n let desc = dom.pmViewDesc;\n for (let cur = desc; cur; cur = cur.parent)\n if (cur == this)\n return desc;\n }\n posFromDOM(dom, offset, bias) {\n for (let scan = dom; scan; scan = scan.parentNode) {\n let desc = this.getDesc(scan);\n if (desc)\n return desc.localPosFromDOM(dom, offset, bias);\n }\n return -1;\n }\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.)\n descAt(pos) {\n for (let i = 0, offset = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (offset == pos && end != offset) {\n while (!child.border && child.children.length) {\n for (let i = 0; i < child.children.length; i++) {\n let inner = child.children[i];\n if (inner.size) {\n child = inner;\n break;\n }\n }\n }\n return child;\n }\n if (pos < end)\n return child.descAt(pos - offset - child.border);\n offset = end;\n }\n }\n domFromPos(pos, side) {\n if (!this.contentDOM)\n return { node: this.dom, offset: 0, atom: pos + 1 };\n // First find the position in the child array\n let i = 0, offset = 0;\n for (let curPos = 0; i < this.children.length; i++) {\n let child = this.children[i], end = curPos + child.size;\n if (end > pos) {\n offset = pos - curPos;\n break;\n }\n curPos = end;\n }\n // If this points into the middle of a child, call through\n if (offset)\n return this.children[i].domFromPos(offset - this.children[i].border, side);\n // Go back if there were any zero-length widgets with side >= 0 before this point\n for (; i > 0; i--) {\n let prev = this.children[i - 1];\n if (prev.size || !(prev instanceof BufferHackViewDesc || prev instanceof WidgetViewDesc && prev.side >= 0))\n break;\n }\n // Scan towards the first useable node\n if (side <= 0) {\n let prev, enter = true;\n for (;; i--, enter = false) {\n prev = i ? this.children[i - 1] : null;\n if (!prev || prev.dom.parentNode == this.contentDOM)\n break;\n }\n if (prev && side && enter && !prev.border && !prev.domAtom)\n return prev.domFromPos(prev.size, side);\n return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 };\n }\n else {\n let next, enter = true;\n for (;; i++, enter = false) {\n next = i < this.children.length ? this.children[i] : null;\n if (!next || next.dom.parentNode == this.contentDOM)\n break;\n }\n if (next && enter && !next.border && !next.domAtom)\n return next.domFromPos(0, side);\n return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length };\n }\n }\n // Used to find a DOM range in a single parent for a given changed\n // range.\n parseRange(from, to, base = 0) {\n if (this.children.length == 0)\n return { node: this.contentDOM, from, to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length };\n let fromOffset = -1, toOffset = -1;\n for (let offset = base, i = 0;; i++) {\n let child = this.children[i], end = offset + child.size;\n if (fromOffset == -1 && from <= end) {\n let 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 from = offset;\n for (let j = i; j > 0; j--) {\n let 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)\n fromOffset = 0;\n }\n if (fromOffset > -1 && (end > to || i == this.children.length - 1)) {\n to = end;\n for (let j = i + 1; j < this.children.length; j++) {\n let next = this.children[j];\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)\n toOffset = this.contentDOM.childNodes.length;\n break;\n }\n offset = end;\n }\n return { node: this.contentDOM, from, to, fromOffset, toOffset };\n }\n emptyChildAt(side) {\n if (this.border || !this.contentDOM || !this.children.length)\n return false;\n let child = this.children[side < 0 ? 0 : this.children.length - 1];\n return child.size == 0 || child.emptyChildAt(side);\n }\n domAfterPos(pos) {\n let { node, offset } = this.domFromPos(pos, 0);\n if (!isElt(node) || offset == node.childNodes.length)\n throw new RangeError(\"No node after pos \" + pos);\n return node.childNodes[offset];\n }\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.\n setSelection(anchor, head, view, force = false) {\n // If the selection falls entirely in a child, give it to that child\n let from = Math.min(anchor, head), to = Math.max(anchor, head);\n for (let i = 0, offset = 0; i < this.children.length; i++) {\n let 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, view, force);\n offset = end;\n }\n let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1);\n let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1);\n let domSel = view.root.getSelection();\n let selRange = view.domSelectionRange();\n let 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 ((gecko || safari) && anchor == head) {\n let { node, offset } = anchorDOM;\n if (isText(node)) {\n brKludge = !!(offset && node.nodeValue[offset - 1] == \"\\n\");\n // Issue #1128\n if (brKludge && offset == node.nodeValue.length) {\n for (let scan = node, after; scan; scan = scan.parentNode) {\n if (after = scan.nextSibling) {\n if (after.nodeName == \"BR\")\n anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 };\n break;\n }\n let desc = scan.pmViewDesc;\n if (desc && desc.node && desc.node.isBlock)\n break;\n }\n }\n }\n else {\n let prev = node.childNodes[offset - 1];\n brKludge = prev && (prev.nodeName == \"BR\" || prev.contentEditable == \"false\");\n }\n }\n // Firefox can act strangely when the selection is in front of an\n // uneditable node. See #1163 and https://bugzilla.mozilla.org/show_bug.cgi?id=1709536\n if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && isElt(selRange.focusNode)) {\n let after = selRange.focusNode.childNodes[selRange.focusOffset];\n if (after && after.contentEditable == \"false\")\n force = true;\n }\n if (!(force || brKludge && safari) &&\n isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) &&\n isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset))\n return;\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 let domSelExtended = false;\n if ((domSel.extend || anchor == head) && !(brKludge && gecko)) {\n domSel.collapse(anchorDOM.node, anchorDOM.offset);\n try {\n if (anchor != head)\n domSel.extend(headDOM.node, headDOM.offset);\n domSelExtended = true;\n }\n catch (_) {\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 // Similarly, this could crash on Safari if the editor is hidden, and\n // there was no selection.\n }\n }\n if (!domSelExtended) {\n if (anchor > head) {\n let tmp = anchorDOM;\n anchorDOM = headDOM;\n headDOM = tmp;\n }\n let 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 ignoreMutation(mutation) {\n return !this.contentDOM && mutation.type != \"selection\";\n }\n get contentLost() {\n return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM);\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.\n markDirty(from, to) {\n for (let offset = 0, i = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (offset == end ? from <= end && to >= offset : from < end && to > offset) {\n let 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))\n child.dirty = NODE_DIRTY;\n else\n child.markDirty(from - startInside, to - startInside);\n return;\n }\n else {\n child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length\n ? CONTENT_DIRTY : NODE_DIRTY;\n }\n }\n offset = end;\n }\n this.dirty = CONTENT_DIRTY;\n }\n markParentsDirty() {\n let level = 1;\n for (let node = this.parent; node; node = node.parent, level++) {\n let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;\n if (node.dirty < dirty)\n node.dirty = dirty;\n }\n }\n get domAtom() { return false; }\n get ignoreForCoords() { return false; }\n get ignoreForSelection() { return false; }\n isText(text) { return false; }\n}\n// A widget desc represents a widget decoration, which is a DOM node\n// drawn between the document nodes.\nclass WidgetViewDesc extends ViewDesc {\n constructor(parent, widget, view, pos) {\n let self, dom = widget.type.toDOM;\n if (typeof dom == \"function\")\n dom = dom(view, () => {\n if (!self)\n return pos;\n if (self.parent)\n return self.parent.posBeforeChild(self);\n });\n if (!widget.type.spec.raw) {\n let elt = isElt(dom) ? dom : document.createElement(\"span\");\n if (elt != dom) {\n elt.appendChild(dom);\n dom = elt;\n }\n if (!elt.hasAttribute(\"contenteditable\"))\n elt.contentEditable = \"false\";\n elt.classList.add(\"ProseMirror-widget\");\n }\n super(parent, [], dom, null);\n this.widget = widget;\n this.widget = widget;\n self = this;\n }\n matchesWidget(widget) {\n return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type);\n }\n parseRule() { return { ignore: true }; }\n stopEvent(event) {\n let stop = this.widget.spec.stopEvent;\n return stop ? stop(event) : false;\n }\n ignoreMutation(mutation) {\n return mutation.type != \"selection\" || this.widget.spec.ignoreSelection;\n }\n destroy() {\n this.widget.type.destroy(this.dom);\n super.destroy();\n }\n get domAtom() { return true; }\n get ignoreForSelection() { return !!this.widget.type.spec.relaxedSide; }\n get side() { return this.widget.type.side; }\n}\nclass CompositionViewDesc extends ViewDesc {\n constructor(parent, dom, textDOM, text) {\n super(parent, [], dom, null);\n this.textDOM = textDOM;\n this.text = text;\n }\n get size() { return this.text.length; }\n localPosFromDOM(dom, offset) {\n if (dom != this.textDOM)\n return this.posAtStart + (offset ? this.size : 0);\n return this.posAtStart + offset;\n }\n domFromPos(pos) {\n return { node: this.textDOM, offset: pos };\n }\n ignoreMutation(mut) {\n return mut.type === 'characterData' && mut.target.nodeValue == mut.oldValue;\n }\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.\nclass MarkViewDesc extends ViewDesc {\n constructor(parent, mark, dom, contentDOM, spec) {\n super(parent, [], dom, contentDOM);\n this.mark = mark;\n this.spec = spec;\n }\n static create(parent, mark, inline, view) {\n let custom = view.nodeViews[mark.type.name];\n let spec = custom && custom(mark, view, inline);\n if (!spec || !spec.dom)\n spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline), null, mark.attrs);\n return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom, spec);\n }\n parseRule() {\n if ((this.dirty & NODE_DIRTY) || this.mark.type.spec.reparseInView)\n return null;\n return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM };\n }\n matchesMark(mark) { return this.dirty != NODE_DIRTY && this.mark.eq(mark); }\n markDirty(from, to) {\n super.markDirty(from, to);\n // Move dirty info to nearest node view\n if (this.dirty != NOT_DIRTY) {\n let parent = this.parent;\n while (!parent.node)\n parent = parent.parent;\n if (parent.dirty < this.dirty)\n parent.dirty = this.dirty;\n this.dirty = NOT_DIRTY;\n }\n }\n slice(from, to, view) {\n let copy = MarkViewDesc.create(this.parent, this.mark, true, view);\n let nodes = this.children, size = this.size;\n if (to < size)\n nodes = replaceNodes(nodes, to, size, view);\n if (from > 0)\n nodes = replaceNodes(nodes, 0, from, view);\n for (let i = 0; i < nodes.length; i++)\n nodes[i].parent = copy;\n copy.children = nodes;\n return copy;\n }\n ignoreMutation(mutation) {\n return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n }\n destroy() {\n if (this.spec.destroy)\n this.spec.destroy();\n super.destroy();\n }\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.\nclass NodeViewDesc extends ViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM) {\n super(parent, [], dom, contentDOM);\n this.node = node;\n this.outerDeco = outerDeco;\n this.innerDeco = innerDeco;\n this.nodeDOM = nodeDOM;\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 finicky\n // implementation details to the user code that they probably will\n // never need.)\n static create(parent, node, outerDeco, innerDeco, view, pos) {\n let custom = view.nodeViews[node.type.name], descObj;\n let spec = custom && custom(node, view, () => {\n // (This is a function that allows the custom view to find its\n // own position)\n if (!descObj)\n return pos;\n if (descObj.parent)\n return descObj.parent.posBeforeChild(descObj);\n }, outerDeco, innerDeco);\n let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;\n if (node.isText) {\n if (!dom)\n dom = document.createTextNode(node.text);\n else if (!isText(dom))\n throw new RangeError(\"Text must be rendered as a DOM text node\");\n }\n else if (!dom) {\n let spec = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs);\n ({ dom, contentDOM } = spec);\n }\n if (!contentDOM && !node.isText && dom.nodeName != \"BR\") { // Chrome gets confused by
\n if (!dom.hasAttribute(\"contenteditable\"))\n dom.contentEditable = \"false\";\n if (node.type.spec.draggable)\n dom.draggable = true;\n }\n let nodeDOM = dom;\n dom = applyOuterDeco(dom, outerDeco, node);\n if (spec)\n return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec);\n else if (node.isText)\n return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM);\n else\n return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM);\n }\n parseRule(addedNodes) {\n // Experimental kludge to allow opt-in re-parsing of nodes\n if (this.node.type.spec.reparseInView)\n 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 let rule = { node: this.node.type.name, attrs: this.node.attrs };\n if (this.node.type.whitespace == \"pre\")\n rule.preserveWhitespace = \"full\";\n if (!this.contentDOM) {\n rule.getContent = () => this.node.content;\n }\n else if (!this.contentLost) {\n rule.contentElement = this.contentDOM;\n }\n else {\n // Chrome likes to randomly recreate parent nodes when\n // backspacing things. When that happens, this tries to find the\n // new parent.\n for (let i = this.children.length - 1; i >= 0; i--) {\n let child = this.children[i];\n if (this.dom.contains(child.dom.parentNode)) {\n rule.contentElement = child.dom.parentNode;\n break;\n }\n }\n if (!rule.contentElement) {\n let found = addedNodes &&\n addedNodes.find(n => isElt(n) && addedNodes.indexOf(n.parentNode) < 0 && this.dom.contains(n));\n if (found)\n rule.contentElement = found;\n else\n rule.getContent = () => Fragment.empty;\n }\n }\n return rule;\n }\n 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 get size() { return this.node.nodeSize; }\n get border() { return this.node.isLeaf ? 0 : 1; }\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 updateChildren(view, pos) {\n let inline = this.node.inlineContent, off = pos;\n let composition = view.composing ? this.localCompositionInfo(view, pos) : null;\n let localComposition = composition && composition.pos > -1 ? composition : null;\n let compositionInChild = composition && composition.pos < 0;\n let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view);\n let addBuffers = this.node.inlineContent, atBufferPos = addBuffers && this.node.isBlock;\n iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => {\n if (widget.spec.marks)\n updater.syncToMarks(widget.spec.marks, inline, view, i);\n else if (widget.type.side >= 0 && !insideNode)\n updater.syncToMarks(i == this.node.childCount ? Mark.none : this.node.child(i).marks, inline, view, i);\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 }, (child, outerDeco, innerDeco, i) => {\n // Make sure the wrapping mark descs match the node's marks.\n updater.syncToMarks(child.marks, inline, view, i);\n if (atBufferPos && child.isAtom && !child.isText)\n updater.addHackNode(\"IMG\", updater.top);\n // Try several strategies for drawing this node\n let compIndex;\n if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) ;\n else if (compositionInChild && view.state.selection.from > off &&\n view.state.selection.to < off + child.nodeSize &&\n (compIndex = updater.findIndexWithChild(composition.node)) > -1 &&\n updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) ;\n else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i, off)) ;\n else {\n // Add it as a new view\n updater.addNode(child, outerDeco, innerDeco, view, off);\n }\n off += child.nodeSize;\n if (addBuffers)\n atBufferPos = child.isAtom && !child.isText;\n });\n // Drop all remaining descs after the current position.\n updater.syncToMarks([], inline, view, 0);\n if (this.node.isTextblock)\n updater.addTextblockHacks();\n updater.destroyRest();\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 (localComposition)\n this.protectLocalComposition(view, localComposition);\n renderDescs(this.contentDOM, this.children, view);\n if (ios)\n iosHacks(this.dom);\n }\n }\n localCompositionInfo(view, pos) {\n // Only do something if both the selection and a focused text node\n // are inside of this node\n let { from, to } = view.state.selection;\n if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size)\n return null;\n let textNode = view.input.compositionNode;\n if (!textNode || !this.dom.contains(textNode.parentNode))\n return null;\n if (this.node.inlineContent) {\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 let text = textNode.nodeValue;\n let textPos = findTextInFragment(this.node.content, text, from - pos, to - pos);\n return textPos < 0 ? null : { node: textNode, pos: textPos, text };\n }\n else {\n return { node: textNode, pos: -1, text: \"\" };\n }\n }\n protectLocalComposition(view, { node, pos, text }) {\n // The node is already part of a local view desc, leave it there\n if (this.getDesc(node))\n return;\n // Create a composition view for the orphaned nodes\n let topNode = node;\n for (;; topNode = topNode.parentNode) {\n if (topNode.parentNode == this.contentDOM)\n break;\n while (topNode.previousSibling)\n topNode.parentNode.removeChild(topNode.previousSibling);\n while (topNode.nextSibling)\n topNode.parentNode.removeChild(topNode.nextSibling);\n if (topNode.pmViewDesc)\n topNode.pmViewDesc = undefined;\n }\n let desc = new CompositionViewDesc(this, topNode, node, text);\n view.input.compositionNodes.push(desc);\n // Patch up this.children to contain the composition view\n this.children = replaceNodes(this.children, pos, pos + text.length, view, desc);\n }\n // If this desc must be updated to match the given node decoration,\n // do so and return true.\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY ||\n !node.sameMarkup(this.node))\n return false;\n this.updateInner(node, outerDeco, innerDeco, view);\n return true;\n }\n updateInner(node, outerDeco, innerDeco, view) {\n this.updateOuterDeco(outerDeco);\n this.node = node;\n this.innerDeco = innerDeco;\n if (this.contentDOM)\n this.updateChildren(view, this.posAtStart);\n this.dirty = NOT_DIRTY;\n }\n updateOuterDeco(outerDeco) {\n if (sameOuterDeco(outerDeco, this.outerDeco))\n return;\n let needsWrap = !isElt(this.nodeDOM);\n let oldDOM = this.dom;\n this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap));\n if (this.dom != oldDOM) {\n oldDOM.pmViewDesc = undefined;\n this.dom.pmViewDesc = this;\n }\n this.outerDeco = outerDeco;\n }\n // Mark this node as being the selected node.\n selectNode() {\n if (isElt(this.nodeDOM)) {\n this.nodeDOM.classList.add(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable)\n this.nodeDOM.draggable = true;\n }\n }\n // Remove selected node marking from this node.\n deselectNode() {\n if (isElt(this.nodeDOM)) {\n this.nodeDOM.classList.remove(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable)\n this.nodeDOM.removeAttribute(\"draggable\");\n }\n }\n get domAtom() { return this.node.isAtom; }\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 let docView = new NodeViewDesc(undefined, doc, outerDeco, innerDeco, dom, dom, dom);\n if (docView.contentDOM)\n docView.updateChildren(view, 0);\n return docView;\n}\nclass TextViewDesc extends NodeViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, nodeDOM) {\n super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM);\n }\n parseRule() {\n let skip = this.nodeDOM.parentNode;\n while (skip && skip != this.dom && !skip.pmIsDeco)\n skip = skip.parentNode;\n return { skip: (skip || true) };\n }\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY || (this.dirty != NOT_DIRTY && !this.inParent()) ||\n !node.sameMarkup(this.node))\n 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)\n view.trackWrites = null;\n }\n this.node = node;\n this.dirty = NOT_DIRTY;\n return true;\n }\n inParent() {\n let parentDOM = this.parent.contentDOM;\n for (let n = this.nodeDOM; n; n = n.parentNode)\n if (n == parentDOM)\n return true;\n return false;\n }\n domFromPos(pos) {\n return { node: this.nodeDOM, offset: pos };\n }\n localPosFromDOM(dom, offset, bias) {\n if (dom == this.nodeDOM)\n return this.posAtStart + Math.min(offset, this.node.text.length);\n return super.localPosFromDOM(dom, offset, bias);\n }\n ignoreMutation(mutation) {\n return mutation.type != \"characterData\" && mutation.type != \"selection\";\n }\n slice(from, to, _view) {\n let node = this.node.cut(from, to), dom = document.createTextNode(node.text);\n return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom);\n }\n markDirty(from, to) {\n super.markDirty(from, to);\n if (this.dom != this.nodeDOM && (from == 0 || to == this.nodeDOM.nodeValue.length))\n this.dirty = NODE_DIRTY;\n }\n get domAtom() { return false; }\n isText(text) { return this.node.text == text; }\n}\n// A dummy desc used to tag extra BR or IMG nodes created to work\n// around contentEditable terribleness.\nclass BufferHackViewDesc extends ViewDesc {\n parseRule() { return { ignore: true }; }\n matchesHack(nodeName) { return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName; }\n get domAtom() { return true; }\n get ignoreForCoords() { return this.dom.nodeName == \"IMG\"; }\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.\nclass CustomNodeViewDesc extends NodeViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec) {\n super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM);\n this.spec = spec;\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 update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY)\n return false;\n if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) {\n let result = this.spec.update(node, outerDeco, innerDeco);\n if (result)\n this.updateInner(node, outerDeco, innerDeco, view);\n return result;\n }\n else if (!this.contentDOM && !node.isLeaf) {\n return false;\n }\n else {\n return super.update(node, outerDeco, innerDeco, view);\n }\n }\n selectNode() {\n this.spec.selectNode ? this.spec.selectNode() : super.selectNode();\n }\n deselectNode() {\n this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode();\n }\n setSelection(anchor, head, view, force) {\n this.spec.setSelection ? this.spec.setSelection(anchor, head, view.root)\n : super.setSelection(anchor, head, view, force);\n }\n destroy() {\n if (this.spec.destroy)\n this.spec.destroy();\n super.destroy();\n }\n stopEvent(event) {\n return this.spec.stopEvent ? this.spec.stopEvent(event) : false;\n }\n ignoreMutation(mutation) {\n return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n }\n}\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 let dom = parentDOM.firstChild, written = false;\n for (let i = 0; i < descs.length; i++) {\n let desc = descs[i], childDOM = desc.dom;\n if (childDOM.parentNode == parentDOM) {\n while (childDOM != dom) {\n dom = rm(dom);\n written = true;\n }\n dom = dom.nextSibling;\n }\n else {\n written = true;\n parentDOM.insertBefore(childDOM, dom);\n }\n if (desc instanceof MarkViewDesc) {\n let 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) {\n dom = rm(dom);\n written = true;\n }\n if (written && view.trackWrites == parentDOM)\n view.trackWrites = null;\n}\nconst OuterDecoLevel = function (nodeName) {\n if (nodeName)\n this.nodeName = nodeName;\n};\nOuterDecoLevel.prototype = Object.create(null);\nconst noDeco = [new OuterDecoLevel];\nfunction computeOuterDeco(outerDeco, node, needsWrap) {\n if (outerDeco.length == 0)\n return noDeco;\n let top = needsWrap ? noDeco[0] : new OuterDecoLevel, result = [top];\n for (let i = 0; i < outerDeco.length; i++) {\n let attrs = outerDeco[i].type.attrs;\n if (!attrs)\n continue;\n if (attrs.nodeName)\n result.push(top = new OuterDecoLevel(attrs.nodeName));\n for (let name in attrs) {\n let val = attrs[name];\n if (val == null)\n continue;\n if (needsWrap && result.length == 1)\n result.push(top = new OuterDecoLevel(node.isInline ? \"span\" : \"div\"));\n if (name == \"class\")\n top.class = (top.class ? top.class + \" \" : \"\") + val;\n else if (name == \"style\")\n top.style = (top.style ? top.style + \";\" : \"\") + val;\n else if (name != \"nodeName\")\n top[name] = val;\n }\n }\n return result;\n}\nfunction patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {\n // Shortcut for trivial case\n if (prevComputed == noDeco && curComputed == noDeco)\n return nodeDOM;\n let curDOM = nodeDOM;\n for (let i = 0; i < curComputed.length; i++) {\n let deco = curComputed[i], prev = prevComputed[i];\n if (i) {\n let parent;\n if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM &&\n (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) {\n curDOM = parent;\n }\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}\nfunction patchAttributes(dom, prev, cur) {\n for (let name in prev)\n if (name != \"class\" && name != \"style\" && name != \"nodeName\" && !(name in cur))\n dom.removeAttribute(name);\n for (let name in cur)\n if (name != \"class\" && name != \"style\" && name != \"nodeName\" && cur[name] != prev[name])\n dom.setAttribute(name, cur[name]);\n if (prev.class != cur.class) {\n let prevList = prev.class ? prev.class.split(\" \").filter(Boolean) : [];\n let curList = cur.class ? cur.class.split(\" \").filter(Boolean) : [];\n for (let i = 0; i < prevList.length; i++)\n if (curList.indexOf(prevList[i]) == -1)\n dom.classList.remove(prevList[i]);\n for (let i = 0; i < curList.length; i++)\n if (prevList.indexOf(curList[i]) == -1)\n dom.classList.add(curList[i]);\n if (dom.classList.length == 0)\n dom.removeAttribute(\"class\");\n }\n if (prev.style != cur.style) {\n if (prev.style) {\n let 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}\nfunction applyOuterDeco(dom, deco, node) {\n return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, !isElt(dom)));\n}\nfunction sameOuterDeco(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].type.eq(b[i].type))\n return false;\n return true;\n}\n// Remove a DOM node and return its next sibling.\nfunction rm(dom) {\n let next = dom.nextSibling;\n dom.parentNode.removeChild(dom);\n return next;\n}\n// Helper class for incrementally updating a tree of mark descs and\n// the widget and node descs inside of them.\nclass ViewTreeUpdater {\n constructor(top, lock, view) {\n this.lock = lock;\n this.view = view;\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 this.top = top;\n this.preMatch = preMatch(top.node.content, top);\n }\n // Destroy and remove the children between the given indices in\n // `this.top`.\n destroyBetween(start, end) {\n if (start == end)\n return;\n for (let i = start; i < end; i++)\n this.top.children[i].destroy();\n this.top.children.splice(start, end - start);\n this.changed = true;\n }\n // Destroy all remaining children in `this.top`.\n destroyRest() {\n this.destroyBetween(this.index, this.top.children.length);\n }\n // Sync the current stack of mark descs with the given array of\n // marks, reusing existing mark descs when possible.\n syncToMarks(marks, inline, view, parentIndex) {\n let keep = 0, depth = this.stack.length >> 1;\n let maxKeep = Math.min(depth, marks.length);\n while (keep < maxKeep &&\n (keep == depth - 1 ? this.top : this.stack[(keep + 1) << 1])\n .matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)\n keep++;\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 let found = -1, scanTo = this.top.children.length;\n if (parentIndex < this.preMatch.index)\n scanTo = Math.min(this.index + 3, scanTo);\n for (let i = this.index; i < scanTo; i++) {\n let next = this.top.children[i];\n if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) {\n found = i;\n break;\n }\n }\n // When nothing matches, try to update the mark view at this position\n // in place, so a custom mark view can adapt to a changed mark without\n // re-creating its DOM.\n if (found < 0 && this.index < this.top.children.length) {\n let cur = this.top.children[this.index];\n if (cur instanceof MarkViewDesc && cur.dirty != NODE_DIRTY &&\n cur.mark.type == marks[depth].type && cur.spec.update &&\n !this.isLocked(cur.dom) && cur.spec.update(marks[depth])) {\n cur.mark = marks[depth];\n found = this.index;\n this.changed = true;\n }\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 }\n else {\n let 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 // Try to find a node desc matching the given data. Skip over it and\n // return true when successful.\n findNodeMatch(node, outerDeco, innerDeco, index) {\n let found = -1, targetDesc;\n if (index >= this.preMatch.index &&\n (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top &&\n targetDesc.matchesNode(node, outerDeco, innerDeco)) {\n found = this.top.children.indexOf(targetDesc, this.index);\n }\n else {\n for (let i = this.index, e = Math.min(this.top.children.length, i + 5); i < e; i++) {\n let child = this.top.children[i];\n if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) {\n found = i;\n break;\n }\n }\n }\n if (found < 0)\n return false;\n this.destroyBetween(this.index, found);\n this.index++;\n return true;\n }\n updateNodeAt(node, outerDeco, innerDeco, index, view) {\n let child = this.top.children[index];\n if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM)\n child.dirty = CONTENT_DIRTY;\n if (!child.update(node, outerDeco, innerDeco, view))\n return false;\n this.destroyBetween(this.index, index);\n this.index++;\n return true;\n }\n findIndexWithChild(domNode) {\n for (;;) {\n let parent = domNode.parentNode;\n if (!parent)\n return -1;\n if (parent == this.top.contentDOM) {\n let desc = domNode.pmViewDesc;\n if (desc)\n for (let i = this.index; i < this.top.children.length; i++) {\n if (this.top.children[i] == desc)\n return i;\n }\n return -1;\n }\n domNode = parent;\n }\n }\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.\n updateNextNode(node, outerDeco, innerDeco, view, index, pos) {\n for (let i = this.index; i < this.top.children.length; i++) {\n let next = this.top.children[i];\n if (next instanceof NodeViewDesc) {\n let preMatch = this.preMatch.matched.get(next);\n if (preMatch != null && preMatch != index)\n return false;\n let nextDOM = next.dom, updated;\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 let locked = this.isLocked(nextDOM) &&\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)\n this.changed = true;\n this.index++;\n return true;\n }\n else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) {\n this.destroyBetween(this.index, i);\n this.top.children[this.index] = updated;\n if (updated.contentDOM) {\n updated.dirty = CONTENT_DIRTY;\n updated.updateChildren(view, pos + 1);\n updated.dirty = NOT_DIRTY;\n }\n this.changed = true;\n this.index++;\n return true;\n }\n break;\n }\n }\n return false;\n }\n // When a node with content is replaced by a different node with\n // identical content, move over its children.\n recreateWrapper(next, node, outerDeco, innerDeco, view, pos) {\n if (next.dirty || node.isAtom || !next.children.length ||\n !next.node.content.eq(node.content) ||\n !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco))\n return null;\n let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n if (wrapper.contentDOM) {\n wrapper.children = next.children;\n next.children = [];\n for (let ch of wrapper.children)\n ch.parent = wrapper;\n }\n next.destroy();\n return wrapper;\n }\n // Insert the node as a newly created node desc.\n addNode(node, outerDeco, innerDeco, view, pos) {\n let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n if (desc.contentDOM)\n desc.updateChildren(view, pos + 1);\n this.top.children.splice(this.index++, 0, desc);\n this.changed = true;\n }\n placeWidget(widget, view, pos) {\n let next = this.index < this.top.children.length ? this.top.children[this.index] : null;\n if (next && next.matchesWidget(widget) &&\n (widget == next.widget || !next.widget.type.toDOM.parentNode)) {\n this.index++;\n }\n else {\n let desc = new WidgetViewDesc(this.top, widget, view, pos);\n this.top.children.splice(this.index++, 0, desc);\n this.changed = true;\n }\n }\n // Make sure a textblock looks and behaves correctly in\n // contentEditable.\n addTextblockHacks() {\n let lastChild = this.top.children[this.index - 1], parent = this.top;\n while (lastChild instanceof MarkViewDesc) {\n parent = lastChild;\n lastChild = parent.children[parent.children.length - 1];\n }\n if (!lastChild || // Empty textblock\n !(lastChild instanceof TextViewDesc) ||\n /\\n$/.test(lastChild.node.text) ||\n (this.view.requiresGeckoHackNode && /\\s$/.test(lastChild.node.text))) {\n // Avoid bugs in Safari's cursor drawing (#1165) and Chrome's mouse selection (#1152)\n if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == \"false\")\n this.addHackNode(\"IMG\", parent);\n this.addHackNode(\"BR\", this.top);\n }\n }\n addHackNode(nodeName, parent) {\n if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) {\n this.index++;\n }\n else {\n let dom = document.createElement(nodeName);\n if (nodeName == \"IMG\") {\n dom.className = \"ProseMirror-separator\";\n dom.alt = \"\";\n }\n if (nodeName == \"BR\")\n dom.className = \"ProseMirror-trailingBreak\";\n let hack = new BufferHackViewDesc(this.top, [], dom, null);\n if (parent != this.top)\n parent.children.push(hack);\n else\n parent.children.splice(this.index++, 0, hack);\n this.changed = true;\n }\n }\n isLocked(node) {\n return this.lock && (node == this.lock || isElt(node) && node.contains(this.lock.parentNode));\n }\n}\n// Iterate from the end of the fragment and array of descs to find\n// directly matching ones, in order to avoid overeagerly reusing those\n// for other nodes.\nfunction preMatch(frag, parentDesc) {\n let curDesc = parentDesc, descI = curDesc.children.length;\n let fI = frag.childCount, matched = new Map, matches = [];\n outer: while (fI > 0) {\n let desc;\n for (;;) {\n if (descI) {\n let next = curDesc.children[descI - 1];\n if (next instanceof MarkViewDesc) {\n curDesc = next;\n descI = next.children.length;\n }\n else {\n desc = next;\n descI--;\n break;\n }\n }\n else if (curDesc == parentDesc) {\n break outer;\n }\n else {\n descI = curDesc.parent.children.indexOf(curDesc);\n curDesc = curDesc.parent;\n }\n }\n let node = desc.node;\n if (!node)\n continue;\n if (node != frag.child(fI - 1))\n break;\n --fI;\n matched.set(desc, fI);\n matches.push(desc);\n }\n return { index: fI, matched, matches: matches.reverse() };\n}\nfunction compareSide(a, b) {\n return a.type.side - b.type.side;\n}\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 let locals = deco.locals(parent), offset = 0;\n // Simple, cheap variant for when there are no local decorations\n if (locals.length == 0) {\n for (let i = 0; i < parent.childCount; i++) {\n let child = parent.child(i);\n onNode(child, locals, deco.forChild(offset, child), i);\n offset += child.nodeSize;\n }\n return;\n }\n let decoIndex = 0, active = [], restNode = null;\n for (let parentIndex = 0;;) {\n let widget, widgets;\n while (decoIndex < locals.length && locals[decoIndex].to == offset) {\n let next = locals[decoIndex++];\n if (next.widget) {\n if (!widget)\n widget = next;\n else\n (widgets || (widgets = [widget])).push(next);\n }\n }\n if (widget) {\n if (widgets) {\n widgets.sort(compareSide);\n for (let i = 0; i < widgets.length; i++)\n onWidget(widgets[i], parentIndex, !!restNode);\n }\n else {\n onWidget(widget, parentIndex, !!restNode);\n }\n }\n let child, index;\n if (restNode) {\n index = -1;\n child = restNode;\n restNode = null;\n }\n else if (parentIndex < parent.childCount) {\n index = parentIndex;\n child = parent.child(parentIndex++);\n }\n else {\n break;\n }\n for (let i = 0; i < active.length; i++)\n if (active[i].to <= offset)\n active.splice(i--, 1);\n while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)\n active.push(locals[decoIndex++]);\n let end = offset + child.nodeSize;\n if (child.isText) {\n let cutAt = end;\n if (decoIndex < locals.length && locals[decoIndex].from < cutAt)\n cutAt = locals[decoIndex].from;\n for (let i = 0; i < active.length; i++)\n if (active[i].to < cutAt)\n cutAt = active[i].to;\n if (cutAt < end) {\n restNode = child.cut(cutAt - offset);\n child = child.cut(0, cutAt - offset);\n end = cutAt;\n index = -1;\n }\n }\n else {\n while (decoIndex < locals.length && locals[decoIndex].to < end)\n decoIndex++;\n }\n let outerDeco = child.isInline && !child.isLeaf ? active.filter(d => !d.inline) : active.slice();\n onNode(child, outerDeco, deco.forChild(offset, child), index);\n offset = end;\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 let 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// Find a piece of text in an inline fragment, overlapping from-to\nfunction findTextInFragment(frag, text, from, to) {\n for (let i = 0, pos = 0; i < frag.childCount && pos <= to;) {\n let child = frag.child(i++), childStart = pos;\n pos += child.nodeSize;\n if (!child.isText)\n continue;\n let str = child.text;\n while (i < frag.childCount) {\n let next = frag.child(i++);\n pos += next.nodeSize;\n if (!next.isText)\n break;\n str += next.text;\n }\n if (pos >= from) {\n if (pos >= to && str.slice(to - text.length - childStart, to - childStart) == text)\n return to - text.length;\n let found = childStart < to ? str.lastIndexOf(text, to - childStart - 1) : -1;\n if (found >= 0 && found + text.length + childStart >= from)\n return childStart + found;\n if (from == to && str.length >= (to + text.length) - childStart &&\n str.slice(to - childStart, to - childStart + text.length) == text)\n return to;\n }\n }\n return -1;\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 let result = [];\n for (let i = 0, off = 0; i < nodes.length; i++) {\n let child = nodes[i], start = off, end = off += child.size;\n if (start >= to || end <= from) {\n result.push(child);\n }\n else {\n if (start < from)\n result.push(child.slice(0, from - start, view));\n if (replacement) {\n result.push(replacement);\n replacement = undefined;\n }\n if (end > to)\n result.push(child.slice(to - start, child.size, view));\n }\n }\n return result;\n}\n\nfunction selectionFromDOM(view, origin = null) {\n let domSel = view.domSelectionRange(), doc = view.state.doc;\n if (!domSel.focusNode)\n return null;\n let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;\n let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1);\n if (head < 0)\n return null;\n let $head = doc.resolve(head), anchor, selection;\n if (selectionCollapsed(domSel)) {\n anchor = head;\n while (nearestDesc && !nearestDesc.node)\n nearestDesc = nearestDesc.parent;\n if (nearestDesc && nearestDesc.node.isAtom && NodeSelection.isSelectable(nearestDesc.node) &&\n nearestDesc.parent &&\n !(nearestDesc.node.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {\n let pos = nearestDesc.posBefore;\n selection = new NodeSelection(head == pos ? $head : doc.resolve(pos));\n }\n else if (gecko && origin == \"key\" && head > view.state.selection.to &&\n isElt(domSel.focusNode) && domSel.focusOffset == domSel.focusNode.childNodes.length &&\n nearestDesc && nearestDesc.posAtStart > view.state.selection.to) {\n // Firefox will jump across scrollable wrapper nodes on keyboard\n // cursor motion (#1594). This tries to detect this situation\n // and work around it.\n for (let scan = domSel.focusNode;; scan = scan.parentNode) {\n if (getComputedStyle(scan).overflow != \"visible\") {\n selection = Selection.findFrom(doc.resolve(nearestDesc.posAtStart), 1);\n break;\n }\n if (scan == nearestDesc.dom || scan.nextSibling || !scan.parentNode || !isElt(scan.parentNode))\n break;\n }\n }\n }\n else {\n if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) {\n let min = head, max = head;\n for (let i = 0; i < domSel.rangeCount; i++) {\n let range = domSel.getRangeAt(i);\n min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1));\n max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1));\n }\n if (min < 0)\n return null;\n [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max];\n $head = doc.resolve(head);\n }\n else {\n anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1);\n }\n if (anchor < 0)\n return null;\n }\n let $anchor = doc.resolve(anchor);\n if (!selection) {\n let bias = origin == \"pointer\" || (view.state.selection.head < $head.pos && !inWidget) ? 1 : -1;\n selection = selectionBetween(view, $anchor, $head, bias);\n }\n return selection;\n}\nfunction editorOwnsSelection(view) {\n return view.editable ? view.hasFocus() :\n hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom);\n}\nfunction selectionToDOM(view, force = false) {\n let sel = view.state.selection;\n syncNodeSelection(view, sel);\n if (!editorOwnsSelection(view))\n return;\n // Need to delay selection normalization during a native selection\n // drag on Chrome, or it will cause further dragging to glitch.\n let mouseDown = view.input.mouseDown;\n if (!force && chrome && mouseDown) {\n let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection;\n if (domSel.anchorNode && curSel.anchorNode &&\n isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset) &&\n mouseDown.delaySelUpdate()) {\n view.domObserver.setCurSelection();\n return;\n }\n }\n view.domObserver.disconnectSelection();\n if (view.cursorWrapper) {\n selectCursorWrapper(view);\n }\n else {\n let { anchor, head } = sel, 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, force);\n if (brokenSelectBetweenUneditable) {\n if (resetEditableFrom)\n resetEditable(resetEditableFrom);\n if (resetEditableTo)\n resetEditable(resetEditableTo);\n }\n if (sel.visible) {\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n }\n else {\n view.dom.classList.add(\"ProseMirror-hideselection\");\n if (\"onselectionchange\" in document)\n removeClassOnSelectionChange(view);\n }\n }\n view.domObserver.setCurSelection();\n view.domObserver.connectSelection();\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.\nconst brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63;\nfunction temporarilyEditableNear(view, pos) {\n let { node, offset } = view.docView.domFromPos(pos, 0);\n let after = offset < node.childNodes.length ? node.childNodes[offset] : null;\n let before = offset ? node.childNodes[offset - 1] : null;\n if (safari && after && after.contentEditable == \"false\")\n return setEditable(after);\n if ((!after || after.contentEditable == \"false\") &&\n (!before || before.contentEditable == \"false\")) {\n if (after)\n return setEditable(after);\n else if (before)\n return setEditable(before);\n }\n}\nfunction setEditable(element) {\n element.contentEditable = \"true\";\n if (safari && element.draggable) {\n element.draggable = false;\n element.wasDraggable = true;\n }\n return element;\n}\nfunction resetEditable(element) {\n element.contentEditable = \"false\";\n if (element.wasDraggable) {\n element.draggable = true;\n element.wasDraggable = null;\n }\n}\nfunction removeClassOnSelectionChange(view) {\n let doc = view.dom.ownerDocument;\n doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n let domSel = view.domSelectionRange();\n let node = domSel.anchorNode, offset = domSel.anchorOffset;\n doc.addEventListener(\"selectionchange\", view.input.hideSelectionGuard = () => {\n if (domSel.anchorNode != node || domSel.anchorOffset != offset) {\n doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n setTimeout(() => {\n if (!editorOwnsSelection(view) || view.state.selection.visible)\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n }, 20);\n }\n });\n}\nfunction selectCursorWrapper(view) {\n let domSel = view.domSelection();\n if (!domSel)\n return;\n let node = view.cursorWrapper.dom, img = node.nodeName == \"IMG\";\n if (img)\n domSel.collapse(node.parentNode, domIndex(node) + 1);\n else\n domSel.collapse(node, 0);\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 && ie && ie_version <= 11) {\n node.disabled = true;\n node.disabled = false;\n }\n}\nfunction syncNodeSelection(view, sel) {\n if (sel instanceof NodeSelection) {\n let desc = view.docView.descAt(sel.from);\n if (desc != view.lastSelectedViewDesc) {\n clearNodeSelection(view);\n if (desc)\n desc.selectNode();\n view.lastSelectedViewDesc = desc;\n }\n }\n else {\n clearNodeSelection(view);\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 = undefined;\n }\n}\nfunction selectionBetween(view, $anchor, $head, bias) {\n return view.someProp(\"createSelectionBetween\", f => f(view, $anchor, $head))\n || TextSelection.between($anchor, $head, bias);\n}\nfunction hasFocusAndSelection(view) {\n if (view.editable && !view.hasFocus())\n return false;\n return hasSelection(view);\n}\nfunction hasSelection(view) {\n let sel = view.domSelectionRange();\n if (!sel.anchorNode)\n 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 contains(view.dom, sel.anchorNode) && (view.editable || contains(view.dom, sel.focusNode));\n }\n catch (_) {\n return false;\n }\n}\nfunction anchorInRightPlace(view) {\n let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0);\n let domSel = view.domSelectionRange();\n return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset);\n}\n\nfunction moveSelectionBlock(state, dir) {\n let { $anchor, $head } = state.selection;\n let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);\n let $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}\nfunction apply(view, sel) {\n view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());\n return true;\n}\nfunction selectHorizontally(view, dir, mods) {\n let sel = view.state.selection;\n if (sel instanceof TextSelection) {\n if (mods.indexOf(\"s\") > -1) {\n let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter;\n if (!node || node.isText || !node.isLeaf)\n return false;\n let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1));\n return apply(view, new TextSelection(sel.$anchor, $newHead));\n }\n else if (!sel.empty) {\n return false;\n }\n else if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\")) {\n let next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection))\n return apply(view, next);\n return false;\n }\n else if (!mac || mods.indexOf(\"m\") < 0) {\n let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;\n if (!node || node.isText)\n return false;\n let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos;\n if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM))\n 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 }\n else {\n // Chrome and Safari will introduce extra pointless cursor\n // positions around inline uneditable nodes (#937), and\n // Firefox will sometimes just plain refuse to move across\n // them (#1592), so in this situation we move the cursor\n // ourselves.\n return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize)));\n }\n }\n }\n else if (sel instanceof NodeSelection && sel.node.isInline) {\n return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from));\n }\n else {\n let next = moveSelectionBlock(view.state, dir);\n if (next)\n return apply(view, next);\n return false;\n }\n}\nfunction isIgnorable(dom, dir) {\n let desc = dom.pmViewDesc;\n return desc ? desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != \"BR\")\n : isElt(dom) && dom.contentEditable == \"false\";\n}\nfunction skipIgnoredNodes(view, dir) {\n return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view);\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 skipIgnoredNodesBefore(view) {\n let sel = view.domSelectionRange();\n let node = sel.focusNode, offset = sel.focusOffset;\n if (!node)\n return;\n let 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 (gecko && isElt(node) && offset < nodeSize(node) && isIgnorable(node.childNodes[offset], -1))\n force = true;\n for (;;) {\n if (offset > 0) {\n if (!isElt(node))\n break;\n let before = node.childNodes[offset - 1];\n if (isIgnorable(before, -1)) {\n moveNode = node;\n moveOffset = --offset;\n }\n else if (isText(before)) {\n node = before;\n offset = node.nodeValue.length;\n }\n else {\n break;\n }\n }\n else if (isBlockNode(node)) {\n break;\n }\n else {\n let prev = node.previousSibling;\n while (prev && isIgnorable(prev, -1)) {\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)\n break;\n offset = 0;\n }\n else {\n node = prev;\n offset = nodeSize(node);\n }\n }\n }\n if (force)\n setSelFocus(view, node, offset);\n else if (moveNode)\n setSelFocus(view, moveNode, moveOffset);\n}\n// Make sure the cursor isn't directly before one or more ignored\n// nodes.\nfunction skipIgnoredNodesAfter(view) {\n let sel = view.domSelectionRange();\n let node = sel.focusNode, offset = sel.focusOffset;\n if (!node)\n return;\n let len = nodeSize(node);\n let moveNode, moveOffset;\n for (;;) {\n if (offset < len) {\n if (!isElt(node))\n break;\n let after = node.childNodes[offset];\n if (isIgnorable(after, 1)) {\n moveNode = node;\n moveOffset = ++offset;\n }\n else {\n break;\n }\n }\n else if (isBlockNode(node)) {\n break;\n }\n else {\n let next = node.nextSibling;\n while (next && isIgnorable(next, 1)) {\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)\n break;\n offset = len = 0;\n }\n else {\n node = next;\n offset = 0;\n len = nodeSize(node);\n }\n }\n }\n if (moveNode)\n setSelFocus(view, moveNode, moveOffset);\n}\nfunction isBlockNode(dom) {\n let desc = dom.pmViewDesc;\n return desc && desc.node && desc.node.isBlock;\n}\nfunction textNodeAfter(node, offset) {\n while (node && offset == node.childNodes.length && !hasBlockDesc(node)) {\n offset = domIndex(node) + 1;\n node = node.parentNode;\n }\n while (node && offset < node.childNodes.length) {\n let next = node.childNodes[offset];\n if (isText(next))\n return next;\n if (isElt(next) && next.contentEditable == \"false\")\n break;\n node = next;\n offset = 0;\n }\n}\nfunction textNodeBefore(node, offset) {\n while (node && !offset && !hasBlockDesc(node)) {\n offset = domIndex(node);\n node = node.parentNode;\n }\n while (node && offset) {\n let next = node.childNodes[offset - 1];\n if (isText(next))\n return next;\n if (isElt(next) && next.contentEditable == \"false\")\n break;\n node = next;\n offset = node.childNodes.length;\n }\n}\nfunction setSelFocus(view, node, offset) {\n if (!isText(node)) {\n let before, after;\n if (after = textNodeAfter(node, offset)) {\n node = after;\n offset = 0;\n }\n else if (before = textNodeBefore(node, offset)) {\n node = before;\n offset = before.nodeValue.length;\n }\n }\n let sel = view.domSelection(), range = view.domSelectionRange();\n if (!sel)\n return;\n if (selectionCollapsed(range)) {\n sel.collapse(node, offset);\n }\n else if (sel.extend) {\n sel.collapse(range.anchorNode, range.anchorOffset);\n sel.extend(node, offset);\n }\n view.domObserver.setCurSelection();\n let { state } = view;\n // If no state update ends up happening, reset the selection.\n setTimeout(() => {\n if (view.state == state)\n selectionToDOM(view);\n }, 50);\n}\nfunction findDirection(view, pos) {\n let $pos = view.state.doc.resolve(pos);\n if (!(chrome || windows) && $pos.parent.inlineContent) {\n let coords = view.coordsAtPos(pos);\n if (pos > $pos.start()) {\n let before = view.coordsAtPos(pos - 1);\n let mid = (before.top + before.bottom) / 2;\n if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1)\n return before.left < coords.left ? \"ltr\" : \"rtl\";\n }\n if (pos < $pos.end()) {\n let after = view.coordsAtPos(pos + 1);\n let mid = (after.top + after.bottom) / 2;\n if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1)\n return after.left > coords.left ? \"ltr\" : \"rtl\";\n }\n }\n let block = view.dom;\n for (let d = $pos.depth; d > 0; d--)\n if ($pos.node(d).isBlock) {\n block = view.nodeDOM($pos.before(d)) || block;\n break;\n }\n let computed = getComputedStyle(block).direction;\n return computed == \"rtl\" ? \"rtl\" : \"ltr\";\n}\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 let sel = view.state.selection;\n if (sel instanceof TextSelection && !sel.empty || mods.indexOf(\"s\") > -1)\n return false;\n if (mac && mods.indexOf(\"m\") > -1)\n return false;\n let { $from, $to } = sel;\n if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? \"up\" : \"down\")) {\n let next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection))\n return apply(view, next);\n }\n if (!$from.parent.inlineContent) {\n let side = dir < 0 ? $from : $to;\n let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir);\n return beyond ? apply(view, beyond) : false;\n }\n return false;\n}\nfunction stopNativeHorizontalDelete(view, dir) {\n if (!(view.state.selection instanceof TextSelection))\n return true;\n let { $head, $anchor, empty } = view.state.selection;\n if (!$head.sameParent($anchor))\n return true;\n if (!empty)\n return false;\n if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\"))\n return true;\n let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);\n if (nextNode && !nextNode.isText) {\n let tr = view.state.tr;\n if (dir < 0)\n tr.delete($head.pos - nextNode.nodeSize, $head.pos);\n else\n tr.delete($head.pos, $head.pos + nextNode.nodeSize);\n view.dispatch(tr);\n return true;\n }\n return false;\n}\nfunction switchEditable(view, node, state) {\n view.domObserver.stop();\n node.contentEditable = state;\n view.domObserver.start();\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 (!safari || view.state.selection.$head.parentOffset > 0)\n return false;\n let { focusNode, focusOffset } = view.domSelectionRange();\n if (focusNode && isElt(focusNode) && focusOffset == 0 &&\n focusNode.firstChild && isElt(focusNode.firstChild) && focusNode.firstChild.contentEditable == \"false\") {\n let child = focusNode.firstChild;\n switchEditable(view, child, \"true\");\n setTimeout(() => switchEditable(view, child, \"false\"), 20);\n }\n return false;\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.\nfunction getMods(event) {\n let result = \"\";\n if (event.ctrlKey)\n result += \"c\";\n if (event.metaKey)\n result += \"m\";\n if (event.altKey)\n result += \"a\";\n if (event.shiftKey)\n result += \"s\";\n return result;\n}\nfunction captureKeyDown(view, event) {\n let code = event.keyCode, mods = getMods(event);\n if (code == 8 || (mac && code == 72 && mods == \"c\")) { // Backspace, Ctrl-h on Mac\n return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1);\n }\n else if ((code == 46 && !event.shiftKey) || (mac && code == 68 && mods == \"c\")) { // Delete, Ctrl-d on Mac\n return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1);\n }\n else if (code == 13 || code == 27) { // Enter, Esc\n return true;\n }\n else if (code == 37 || (mac && code == 66 && mods == \"c\")) { // Left arrow, Ctrl-b on Mac\n let dir = code == 37 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? -1 : 1) : -1;\n return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n }\n else if (code == 39 || (mac && code == 70 && mods == \"c\")) { // Right arrow, Ctrl-f on Mac\n let dir = code == 39 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? 1 : -1) : 1;\n return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n }\n else if (code == 38 || (mac && code == 80 && mods == \"c\")) { // Up arrow, Ctrl-p on Mac\n return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1);\n }\n else if (code == 40 || (mac && code == 78 && mods == \"c\")) { // Down arrow, Ctrl-n on Mac\n return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1);\n }\n else if (mods == (mac ? \"m\" : \"c\") &&\n (code == 66 || code == 73 || code == 89 || code == 90)) { // Mod-[biyz]\n return true;\n }\n return false;\n}\n\nfunction serializeForClipboard(view, slice) {\n view.someProp(\"transformCopied\", f => { slice = f(slice, view); });\n let context = [], { content, openStart, openEnd } = slice;\n while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {\n openStart--;\n openEnd--;\n let node = content.firstChild;\n context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null);\n content = node.content;\n }\n let serializer = view.someProp(\"clipboardSerializer\") || DOMSerializer.fromSchema(view.state.schema);\n let doc = detachedDoc(), wrap = doc.createElement(\"div\");\n wrap.appendChild(serializer.serializeFragment(content, { document: doc }));\n let firstChild = wrap.firstChild, needsWrap, wrappers = 0;\n while (firstChild && isElt(firstChild) && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {\n for (let i = needsWrap.length - 1; i >= 0; i--) {\n let wrapper = doc.createElement(needsWrap[i]);\n while (wrap.firstChild)\n wrapper.appendChild(wrap.firstChild);\n wrap.appendChild(wrapper);\n wrappers++;\n }\n firstChild = wrap.firstChild;\n }\n if (firstChild && isElt(firstChild))\n firstChild.setAttribute(\"data-pm-slice\", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : \"\"} ${JSON.stringify(context)}`);\n let text = view.someProp(\"clipboardTextSerializer\", f => f(slice, view)) ||\n slice.content.textBetween(0, slice.content.size, \"\\n\\n\");\n return { dom: wrap, text, slice };\n}\n// Read a slice of content from the clipboard (or drop data).\nfunction parseFromClipboard(view, text, html, plainText, $context) {\n let inCode = $context.parent.type.spec.code;\n let dom, slice;\n if (!html && !text)\n return null;\n let asText = !!text && (plainText || inCode || !html);\n if (asText) {\n view.someProp(\"transformPastedText\", f => { text = f(text, inCode || plainText, view); });\n if (inCode) {\n slice = new Slice(Fragment.from(view.state.schema.text(text.replace(/\\r\\n?/g, \"\\n\"))), 0, 0);\n view.someProp(\"transformPasted\", f => { slice = f(slice, view, true); });\n return slice;\n }\n let parsed = view.someProp(\"clipboardTextParser\", f => f(text, $context, plainText, view));\n if (parsed) {\n slice = parsed;\n }\n else {\n let marks = $context.marks();\n let { schema } = view.state, serializer = DOMSerializer.fromSchema(schema);\n dom = document.createElement(\"div\");\n text.split(/(?:\\r\\n?|\\n)+/).forEach(block => {\n let p = dom.appendChild(document.createElement(\"p\"));\n if (block)\n p.appendChild(serializer.serializeNode(schema.text(block, marks)));\n });\n }\n }\n else {\n view.someProp(\"transformPastedHTML\", f => { html = f(html, view); });\n dom = readHTML(html);\n if (webkit)\n restoreReplacedSpaces(dom);\n }\n let contextNode = dom && dom.querySelector(\"[data-pm-slice]\");\n let sliceData = contextNode && /^(\\d+) (\\d+)(?: -(\\d+))? (.*)/.exec(contextNode.getAttribute(\"data-pm-slice\") || \"\");\n if (sliceData && sliceData[3])\n for (let i = +sliceData[3]; i > 0; i--) {\n let child = dom.firstChild;\n while (child && !isElt(child))\n child = child.nextSibling;\n if (!child)\n break;\n dom = child;\n }\n if (!slice) {\n let parser = view.someProp(\"clipboardParser\") || view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n slice = parser.parseSlice(dom, {\n preserveWhitespace: !!(asText || sliceData),\n context: $context,\n ruleFromNode(dom) {\n if (dom.nodeName == \"BR\" && !dom.nextSibling &&\n dom.parentNode && !inlineParents.test(dom.parentNode.nodeName))\n return { ignore: true };\n return null;\n }\n });\n }\n if (sliceData) {\n slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[4]);\n }\n else { // HTML wasn't created by ProseMirror. Make sure top-level siblings are coherent\n slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), true);\n if (slice.openStart || slice.openEnd) {\n let openStart = 0, openEnd = 0;\n for (let node = slice.content.firstChild; openStart < slice.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) { }\n for (let node = slice.content.lastChild; openEnd < slice.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) { }\n slice = closeSlice(slice, openStart, openEnd);\n }\n }\n view.someProp(\"transformPasted\", f => { slice = f(slice, view, asText); });\n return slice;\n}\nconst inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;\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)\n return fragment;\n for (let d = $context.depth; d >= 0; d--) {\n let parent = $context.node(d);\n let match = parent.contentMatchAt($context.index(d));\n let lastWrap, result = [];\n fragment.forEach(node => {\n if (!result)\n return;\n let wrap = match.findWrapping(node.type), inLast;\n if (!wrap)\n 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 }\n else {\n if (result.length)\n result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length);\n let wrapped = withWrappers(node, wrap);\n result.push(wrapped);\n match = match.matchType(wrapped.type);\n lastWrap = wrap;\n }\n });\n if (result)\n return Fragment.from(result);\n }\n return fragment;\n}\nfunction withWrappers(node, wrap, from = 0) {\n for (let i = wrap.length - 1; i >= from; i--)\n node = wrap[i].create(null, Fragment.from(node));\n return node;\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 let inner = addToSibling(wrap, lastWrap, node, sibling.lastChild, depth + 1);\n if (inner)\n return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner));\n let 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}\nfunction closeRight(node, depth) {\n if (depth == 0)\n return node;\n let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1));\n let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true);\n return node.copy(fragment.append(fill));\n}\nfunction closeRange(fragment, side, from, to, depth, openEnd) {\n let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content;\n if (fragment.childCount > 1)\n openEnd = 0;\n if (depth < to - 1)\n inner = closeRange(inner, side, from, to, depth + 1, openEnd);\n if (depth >= from)\n inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, 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}\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// 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.\nconst 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};\nfunction detachedDoc() {\n return document.implementation.createHTMLDocument(\"title\");\n}\nlet _policy = null;\nfunction maybeWrapTrusted(html) {\n let trustedTypes = window.trustedTypes;\n if (!trustedTypes)\n return html;\n // With the require-trusted-types-for CSP, Chrome will block\n // innerHTML, even on a detached document. This wraps the string in\n // a way that makes the browser allow us to use its parser again.\n if (!_policy) {\n if (_policy = trustedTypes.defaultPolicy)\n try {\n return _policy.createHTML(html);\n }\n catch (_a) { }\n _policy = trustedTypes.createPolicy(\"ProseMirrorClipboard\", { createHTML: (s) => s });\n }\n return _policy.createHTML(html);\n}\nfunction readHTML(html) {\n let metas = /^(\\s*]*>)*/.exec(html);\n if (metas)\n html = html.slice(metas[0].length);\n let doc = detachedDoc(), elt = doc.body;\n let firstTag = /<([a-z][^>\\s]+)/i.exec(html), wrap;\n if (wrap = firstTag && wrapMap[firstTag[1].toLowerCase()])\n html = wrap.map(n => \"<\" + n + \">\").join(\"\") + html + wrap.map(n => \"\").reverse().join(\"\");\n elt.innerHTML = maybeWrapTrusted(html);\n if (wrap)\n for (let i = 0; i < wrap.length; i++)\n elt = elt.querySelector(wrap[i]) || elt;\n // Inline styles defined in the pasted content, so that parse rules pick them up\n for (let i = 0; i < doc.styleSheets.length; i++) {\n let style = doc.styleSheets[i];\n for (let j = 0; j < style.rules.length; j++) {\n let rule = style.rules[j];\n if (rule instanceof CSSStyleRule) {\n let matches = elt.querySelectorAll(rule.selectorText);\n for (let k = 0; k < matches.length; k++)\n matches[k].style.cssText += rule.style.cssText;\n }\n }\n }\n return elt;\n}\n// Webkit browsers do some hard-to-predict replacement of regular\n// spaces with non-breaking spaces when putting content on the\n// clipboard. This tries to convert such non-breaking spaces (which\n// will be wrapped in a plain span on Chrome, a span with class\n// Apple-converted-space on Safari) back to regular spaces.\nfunction restoreReplacedSpaces(dom) {\n let nodes = dom.querySelectorAll(chrome ? \"span:not([class]):not([style])\" : \"span.Apple-converted-space\");\n for (let i = 0; i < nodes.length; i++) {\n let node = nodes[i];\n if (node.childNodes.length == 1 && node.textContent == \"\\u00a0\" && node.parentNode)\n node.parentNode.replaceChild(dom.ownerDocument.createTextNode(\" \"), node);\n }\n}\nfunction addContext(slice, context) {\n if (!slice.size)\n return slice;\n let schema = slice.content.firstChild.type.schema, array;\n try {\n array = JSON.parse(context);\n }\n catch (e) {\n return slice;\n }\n let { content, openStart, openEnd } = slice;\n for (let i = array.length - 2; i >= 0; i -= 2) {\n let type = schema.nodes[array[i]];\n if (!type || type.hasRequiredAttrs())\n break;\n try {\n content = Fragment.from(type.create(array[i + 1], content));\n }\n catch (e) {\n break;\n }\n openStart++;\n openEnd++;\n }\n return new Slice(content, openStart, openEnd);\n}\n\n// A collection of DOM events that occur within the editor, and callback functions\n// to invoke when the event fires.\nconst handlers = {};\nconst editHandlers = {};\nconst passiveHandlers = { touchstart: true, touchmove: true };\nclass InputState {\n constructor() {\n this.shiftKey = false;\n this.mouseDown = null;\n this.lastKeyCode = null;\n this.lastKeyCodeTime = 0;\n this.lastClick = { time: 0, x: 0, y: 0, type: \"\", button: 0 };\n this.lastSelectionOrigin = null;\n this.lastSelectionTime = 0;\n this.lastIOSEnter = 0;\n this.lastIOSEnterFallbackTimeout = -1;\n this.lastFocus = 0;\n this.lastTouch = 0;\n this.lastChromeDelete = 0;\n this.composing = false;\n this.compositionNode = null;\n this.composingTimeout = -1;\n this.compositionNodes = [];\n this.compositionEndedAt = -2e8;\n this.compositionID = 1;\n this.badSafariComposition = false;\n // Set to a composition ID when there are pending changes at compositionend\n this.compositionPendingChanges = 0;\n this.domChangeCount = 0;\n this.eventHandlers = Object.create(null);\n this.hideSelectionGuard = null;\n }\n}\nfunction initInput(view) {\n for (let event in handlers) {\n let handler = handlers[event];\n view.dom.addEventListener(event, view.input.eventHandlers[event] = (event) => {\n if (eventBelongsToView(view, event) && !runCustomHandler(view, event) &&\n (view.editable || !(event.type in editHandlers)))\n handler(view, event);\n }, passiveHandlers[event] ? { passive: true } : undefined);\n }\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 (safari)\n view.dom.addEventListener(\"input\", () => null);\n ensureListeners(view);\n}\nfunction setSelectionOrigin(view, origin) {\n view.input.lastSelectionOrigin = origin;\n view.input.lastSelectionTime = Date.now();\n}\nfunction destroyInput(view) {\n if (view.input.mouseDown)\n view.input.mouseDown.done();\n view.domObserver.stop();\n for (let type in view.input.eventHandlers)\n view.dom.removeEventListener(type, view.input.eventHandlers[type]);\n clearTimeout(view.input.composingTimeout);\n clearTimeout(view.input.lastIOSEnterFallbackTimeout);\n}\nfunction ensureListeners(view) {\n view.someProp(\"handleDOMEvents\", currentHandlers => {\n for (let type in currentHandlers)\n if (!view.input.eventHandlers[type])\n view.dom.addEventListener(type, view.input.eventHandlers[type] = event => runCustomHandler(view, event));\n });\n}\nfunction runCustomHandler(view, event) {\n return view.someProp(\"handleDOMEvents\", handlers => {\n let handler = handlers[event.type];\n return handler ? handler(view, event) || event.defaultPrevented : false;\n });\n}\nfunction eventBelongsToView(view, event) {\n if (!event.bubbles)\n return true;\n if (event.defaultPrevented)\n return false;\n for (let 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}\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}\neditHandlers.keydown = (view, _event) => {\n let event = _event;\n view.input.shiftKey = event.keyCode == 16 || event.shiftKey;\n if (inOrNearComposition(view))\n return;\n view.input.lastKeyCode = event.keyCode;\n view.input.lastKeyCodeTime = Date.now();\n // Suppress enter key events on Chrome Android, because those tend\n // to be part of a confused sequence of composition events fired,\n // and handling them eagerly tends to corrupt the input.\n if (android && chrome && event.keyCode == 13)\n return;\n if (event.keyCode != 229)\n view.domObserver.forceFlush();\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 (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {\n let now = Date.now();\n view.input.lastIOSEnter = now;\n view.input.lastIOSEnterFallbackTimeout = setTimeout(() => {\n if (view.input.lastIOSEnter == now) {\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")));\n view.input.lastIOSEnter = 0;\n }\n }, 200);\n }\n else if (view.someProp(\"handleKeyDown\", f => f(view, event)) || captureKeyDown(view, event)) {\n event.preventDefault();\n }\n else {\n setSelectionOrigin(view, \"key\");\n }\n};\neditHandlers.keyup = (view, event) => {\n if (event.keyCode == 16)\n view.input.shiftKey = false;\n};\neditHandlers.keypress = (view, _event) => {\n let event = _event;\n if (inOrNearComposition(view) || !event.charCode ||\n event.ctrlKey && !event.altKey || mac && event.metaKey)\n return;\n if (view.someProp(\"handleKeyPress\", f => f(view, event))) {\n event.preventDefault();\n return;\n }\n let sel = view.state.selection;\n if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {\n let text = String.fromCharCode(event.charCode);\n let deflt = () => view.state.tr.insertText(text).scrollIntoView();\n if (!/[\\r\\n]/.test(text) && !view.someProp(\"handleTextInput\", f => f(view, sel.$from.pos, sel.$to.pos, text, deflt)))\n view.dispatch(deflt());\n event.preventDefault();\n }\n};\nfunction eventCoords(event) { return { left: event.clientX, top: event.clientY }; }\nfunction isNear(event, click) {\n let dx = click.x - event.clientX, dy = click.y - event.clientY;\n return dx * dx + dy * dy < 100;\n}\nfunction runHandlerOnContext(view, propName, pos, inside, event) {\n if (inside == -1)\n return false;\n let $pos = view.state.doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n if (view.someProp(propName, f => 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 true;\n }\n return false;\n}\nfunction updateSelection(view, selection, origin) {\n if (!view.focused)\n view.focus();\n if (view.state.selection.eq(selection))\n return;\n let tr = view.state.tr.setSelection(selection);\n tr.setMeta(\"pointer\", true);\n view.dispatch(tr);\n}\nfunction selectClickedLeaf(view, inside) {\n if (inside == -1)\n return false;\n let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter;\n if (node && node.isAtom && NodeSelection.isSelectable(node)) {\n updateSelection(view, new NodeSelection($pos));\n return true;\n }\n return false;\n}\nfunction selectClickedNode(view, inside) {\n if (inside == -1)\n return false;\n let sel = view.state.selection, selectedNode, selectAt;\n if (sel instanceof NodeSelection)\n selectedNode = sel.node;\n let $pos = view.state.doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n let 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 if (selectAt != null) {\n updateSelection(view, NodeSelection.create(view.state.doc, selectAt));\n return true;\n }\n else {\n return false;\n }\n}\nfunction handleSingleClick(view, pos, inside, event, selectNode) {\n return runHandlerOnContext(view, \"handleClickOn\", pos, inside, event) ||\n view.someProp(\"handleClick\", f => f(view, pos, event)) ||\n (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside));\n}\nfunction handleDoubleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleDoubleClickOn\", pos, inside, event) ||\n view.someProp(\"handleDoubleClick\", f => f(view, pos, event));\n}\nfunction handleTripleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleTripleClickOn\", pos, inside, event) ||\n view.someProp(\"handleTripleClick\", f => f(view, pos, event)) ||\n defaultTripleClick(view, inside, event);\n}\nfunction defaultTripleClick(view, inside, event) {\n if (event.button != 0)\n return false;\n let selection = selectionForTripleClick(view, inside, true), doc = view.state.doc;\n if (!selection)\n return false;\n updateSelection(view, selection);\n if (selection instanceof TextSelection && doc.eq(view.state.doc))\n view.input.mouseDown = new TripleClickDrag(view, selection);\n return true;\n}\nfunction selectionForTripleClick(view, inside, selectNodes) {\n let doc = view.state.doc;\n if (inside == -1)\n return doc.inlineContent ? TextSelection.create(doc, 0, doc.content.size) : null;\n let $pos = doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n let nodePos = $pos.before(i);\n if (node.inlineContent)\n return TextSelection.create(doc, nodePos + 1, nodePos + 1 + node.content.size);\n else if (selectNodes && NodeSelection.isSelectable(node))\n return NodeSelection.create(doc, nodePos);\n }\n return null;\n}\nfunction forceDOMFlush(view) {\n return endComposition(view);\n}\nconst selectNodeModifier = mac ? \"metaKey\" : \"ctrlKey\";\nhandlers.mousedown = (view, _event) => {\n let event = _event;\n view.input.shiftKey = event.shiftKey;\n let flushed = forceDOMFlush(view);\n let now = Date.now(), type = \"singleClick\";\n if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier] &&\n view.input.lastClick.button == event.button) {\n if (view.input.lastClick.type == \"singleClick\")\n type = \"doubleClick\";\n else if (view.input.lastClick.type == \"doubleClick\")\n type = \"tripleClick\";\n }\n view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type, button: event.button };\n if (view.input.mouseDown)\n view.input.mouseDown.done();\n let pos = view.posAtCoords(eventCoords(event));\n if (!pos)\n return;\n if (type == \"singleClick\") {\n view.input.mouseDown = new LeftMouseDown(view, pos, event, !!flushed);\n }\n else if ((type == \"doubleClick\" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) {\n event.preventDefault();\n }\n else {\n setSelectionOrigin(view, \"pointer\");\n }\n};\nclass MouseDown {\n constructor(view) {\n this.view = view;\n this.mightDrag = null;\n view.root.addEventListener(\"mouseup\", this.up = this.up.bind(this));\n view.root.addEventListener(\"mousemove\", this.move = this.move.bind(this));\n }\n up(event) {\n this.done();\n }\n move(event) {\n if (event.buttons == 0)\n this.done();\n }\n done() {\n this.view.root.removeEventListener(\"mouseup\", this.up);\n this.view.root.removeEventListener(\"mousemove\", this.move);\n if (this.view.input.mouseDown == this)\n this.view.input.mouseDown = null;\n }\n delaySelUpdate() { return false; }\n}\nclass LeftMouseDown extends MouseDown {\n constructor(view, pos, event, flushed) {\n super(view);\n this.pos = pos;\n this.event = event;\n this.flushed = flushed;\n this.delayedSelectionSync = false;\n this.startDoc = view.state.doc;\n this.selectNode = !!event[selectNodeModifier];\n this.allowDefault = event.shiftKey;\n let targetNode, targetPos;\n if (pos.inside > -1) {\n targetNode = view.state.doc.nodeAt(pos.inside);\n targetPos = pos.inside;\n }\n else {\n let $pos = view.state.doc.resolve(pos.pos);\n targetNode = $pos.parent;\n targetPos = $pos.depth ? $pos.before() : 0;\n }\n const target = flushed ? null : event.target;\n const targetDesc = target ? view.docView.nearestDesc(target, true) : null;\n this.target = targetDesc && isElt(targetDesc.nodeDOM) ? targetDesc.nodeDOM : null;\n let { selection } = view.state;\n if (event.button == 0 &&\n (targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false ||\n selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos))\n this.mightDrag = {\n node: targetNode,\n pos: targetPos,\n addAttr: !!(this.target && !this.target.draggable),\n setUneditable: !!(this.target && 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)\n this.target.draggable = true;\n if (this.mightDrag.setUneditable)\n setTimeout(() => {\n if (this.view.input.mouseDown == this)\n this.target.setAttribute(\"contentEditable\", \"false\");\n }, 20);\n this.view.domObserver.start();\n }\n setSelectionOrigin(view, \"pointer\");\n }\n done() {\n super.done();\n if (this.mightDrag && this.target) {\n this.view.domObserver.stop();\n if (this.mightDrag.addAttr)\n this.target.removeAttribute(\"draggable\");\n if (this.mightDrag.setUneditable)\n this.target.removeAttribute(\"contentEditable\");\n this.view.domObserver.start();\n }\n if (this.delayedSelectionSync)\n setTimeout(() => {\n if (!this.view.isDestroyed)\n selectionToDOM(this.view);\n });\n }\n up(event) {\n this.done();\n if (!this.view.dom.contains(event.target))\n return;\n let pos = this.pos;\n if (this.view.state.doc != this.startDoc)\n pos = this.view.posAtCoords(eventCoords(event));\n this.updateAllowDefault(event);\n if (this.allowDefault || !pos) {\n setSelectionOrigin(this.view, \"pointer\");\n }\n else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {\n event.preventDefault();\n }\n else if (event.button == 0 &&\n (this.flushed ||\n // Safari ignores clicks on draggable elements\n (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 (chrome && !this.view.state.selection.visible &&\n Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2))) {\n updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)));\n event.preventDefault();\n }\n else {\n setSelectionOrigin(this.view, \"pointer\");\n }\n }\n move(event) {\n this.updateAllowDefault(event);\n setSelectionOrigin(this.view, \"pointer\");\n super.move(event);\n }\n updateAllowDefault(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 }\n delaySelUpdate() {\n if (!this.allowDefault)\n return false;\n this.delayedSelectionSync = true;\n return true;\n }\n}\nclass TripleClickDrag extends MouseDown {\n constructor(view, startSelection) {\n super(view);\n this.startSelection = startSelection;\n this.startDoc = view.state.doc;\n }\n move(event) {\n if (event.buttons == 0 || this.view.isDestroyed || !this.view.state.doc.eq(this.startDoc)) {\n this.done();\n return;\n }\n event.preventDefault();\n setSelectionOrigin(this.view, \"pointer\");\n let pos = this.view.posAtCoords(eventCoords(event));\n let target = pos && selectionForTripleClick(this.view, pos.inside, false);\n if (!target)\n return;\n let { doc } = this.view.state, start = this.startSelection;\n let [anchor, head] = target.from < start.from ? [start.to, target.from] : [start.from, target.to];\n updateSelection(this.view, TextSelection.create(doc, anchor, head));\n }\n}\nhandlers.touchstart = view => {\n view.input.lastTouch = Date.now();\n forceDOMFlush(view);\n setSelectionOrigin(view, \"pointer\");\n};\nhandlers.touchmove = view => {\n view.input.lastTouch = Date.now();\n setSelectionOrigin(view, \"pointer\");\n};\nhandlers.contextmenu = view => forceDOMFlush(view);\nfunction inOrNearComposition(view, event) {\n if (view.composing)\n 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 (safari && Math.abs(Date.now() - view.input.compositionEndedAt) < 500) {\n view.input.compositionEndedAt = -2e8;\n return true;\n }\n return false;\n}\n// Drop active composition after 5 seconds of inactivity on Android\nconst timeoutComposition = android ? 5000 : -1;\neditHandlers.compositionstart = editHandlers.compositionupdate = view => {\n if (!view.composing) {\n view.domObserver.flush();\n let { state } = view, $pos = state.selection.$to;\n if (state.selection instanceof TextSelection && state.selection.empty &&\n (state.storedMarks ||\n (!$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some(m => m.type.spec.inclusive === false)) ||\n chrome && windows && selectionBeforeUneditable(view))) { // Issue #1500\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 }\n else {\n endComposition(view, !state.selection.empty);\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 (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {\n let sel = view.domSelectionRange();\n for (let node = sel.focusNode, offset = sel.focusOffset; node && isElt(node) && offset != 0;) {\n let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1];\n if (!before)\n break;\n if (isText(before)) {\n let sel = view.domSelection();\n if (sel)\n sel.collapse(before, before.nodeValue.length);\n break;\n }\n else {\n node = before;\n offset = -1;\n }\n }\n }\n }\n view.input.composing = true;\n }\n scheduleComposeEnd(view, timeoutComposition);\n};\nfunction selectionBeforeUneditable(view) {\n let { focusNode, focusOffset } = view.domSelectionRange();\n if (!focusNode || !isElt(focusNode) || focusOffset >= focusNode.childNodes.length)\n return false;\n let next = focusNode.childNodes[focusOffset];\n return isElt(next) && next.contentEditable == \"false\";\n}\neditHandlers.compositionend = (view, event) => {\n if (view.composing) {\n view.input.composing = false;\n view.input.compositionEndedAt = Date.now();\n view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0;\n view.input.compositionNode = null;\n if (view.input.badSafariComposition)\n view.domObserver.forceFlush();\n else if (view.input.compositionPendingChanges)\n Promise.resolve().then(() => view.domObserver.flush());\n view.input.compositionID++;\n scheduleComposeEnd(view, 20);\n }\n};\nfunction scheduleComposeEnd(view, delay) {\n clearTimeout(view.input.composingTimeout);\n if (delay > -1)\n view.input.composingTimeout = setTimeout(() => endComposition(view), delay);\n}\nfunction clearComposition(view) {\n if (view.composing) {\n view.input.composing = false;\n view.input.compositionEndedAt = Date.now();\n }\n while (view.input.compositionNodes.length > 0)\n view.input.compositionNodes.pop().markParentsDirty();\n}\nfunction findCompositionNode(view) {\n let sel = view.domSelectionRange();\n if (!sel.focusNode)\n return null;\n let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset);\n let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset);\n if (textBefore && textAfter && textBefore != textAfter) {\n let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode;\n if (textBefore == lastChanged || textAfter == lastChanged)\n return lastChanged;\n if (!descAfter || !descAfter.isText(textAfter.nodeValue)) {\n return textAfter;\n }\n else if (view.input.compositionNode == textAfter) {\n let descBefore = textBefore.pmViewDesc;\n if (!(!descBefore || !descBefore.isText(textBefore.nodeValue)))\n return textAfter;\n }\n }\n return textBefore || textAfter;\n}\n/**\n@internal\n*/\nfunction endComposition(view, restarting = false) {\n if (android && view.domObserver.flushingSoon >= 0)\n return;\n view.domObserver.forceFlush();\n clearComposition(view);\n if (restarting || view.docView && view.docView.dirty) {\n let sel = selectionFromDOM(view), cur = view.state.selection;\n if (sel && !sel.eq(cur))\n view.dispatch(view.state.tr.setSelection(sel));\n else if ((view.markCursor || restarting) && !cur.$from.node(cur.$from.sharedDepth(cur.to)).inlineContent)\n view.dispatch(view.state.tr.deleteSelection());\n else\n view.updateState(view.state);\n return true;\n }\n return false;\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)\n return;\n let wrap = view.dom.parentNode.appendChild(document.createElement(\"div\"));\n wrap.appendChild(dom);\n wrap.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n let 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(() => {\n if (wrap.parentNode)\n wrap.parentNode.removeChild(wrap);\n view.focus();\n }, 50);\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.\nconst brokenClipboardAPI = (ie && ie_version < 15) ||\n (ios && webkit_version < 604);\nhandlers.copy = editHandlers.cut = (view, _event) => {\n let event = _event;\n let sel = view.state.selection, cut = event.type == \"cut\";\n if (sel.empty)\n return;\n // IE and Edge's clipboard interface is completely broken\n let data = brokenClipboardAPI ? null : event.clipboardData;\n let slice = sel.content(), { dom, text } = serializeForClipboard(view, slice);\n if (data) {\n event.preventDefault();\n data.clearData();\n data.setData(\"text/html\", dom.innerHTML);\n data.setData(\"text/plain\", text);\n }\n else {\n captureCopy(view, dom);\n }\n if (cut)\n view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta(\"uiEvent\", \"cut\"));\n};\nfunction sliceSingleNode(slice) {\n return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null;\n}\nfunction capturePaste(view, event) {\n if (!view.dom.parentNode)\n return;\n let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code;\n let target = view.dom.parentNode.appendChild(document.createElement(plainText ? \"textarea\" : \"div\"));\n if (!plainText)\n target.contentEditable = \"true\";\n target.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n target.focus();\n let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n setTimeout(() => {\n view.focus();\n if (target.parentNode)\n target.parentNode.removeChild(target);\n if (plainText)\n doPaste(view, target.value, null, plain, event);\n else\n doPaste(view, target.textContent, target.innerHTML, plain, event);\n }, 50);\n}\nfunction doPaste(view, text, html, preferPlain, event) {\n let slice = parseFromClipboard(view, text, html, preferPlain, view.state.selection.$from);\n if (view.someProp(\"handlePaste\", f => f(view, event, slice || Slice.empty)))\n return true;\n if (!slice)\n return false;\n let singleNode = sliceSingleNode(slice);\n let tr = singleNode\n ? view.state.tr.replaceSelectionWith(singleNode, preferPlain)\n : view.state.tr.replaceSelection(slice);\n view.dispatch(tr.scrollIntoView().setMeta(\"paste\", true).setMeta(\"uiEvent\", \"paste\"));\n return true;\n}\nfunction getText(clipboardData) {\n let text = clipboardData.getData(\"text/plain\") || clipboardData.getData(\"Text\");\n if (text)\n return text;\n let uris = clipboardData.getData(\"text/uri-list\");\n return uris ? uris.replace(/\\r?\\n/g, \" \") : \"\";\n}\neditHandlers.paste = (view, _event) => {\n let event = _event;\n // Handling paste from JavaScript during composition is very poorly\n // handled by browsers, so as a dodgy but preferable kludge, we just\n // let the browser do its native thing there, except on Android,\n // where the editor is almost always composing.\n if (view.composing && !android)\n return;\n let data = brokenClipboardAPI ? null : event.clipboardData;\n let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n if (data && doPaste(view, getText(data), data.getData(\"text/html\"), plain, event))\n event.preventDefault();\n else\n capturePaste(view, event);\n};\nclass Dragging {\n constructor(slice, move, node) {\n this.slice = slice;\n this.move = move;\n this.node = node;\n }\n}\nconst dragCopyModifier = mac ? \"altKey\" : \"ctrlKey\";\nfunction dragMoves(view, event) {\n let copy;\n view.someProp(\"dragCopies\", test => { copy = copy || test(event); });\n return copy != null ? !copy : !event[dragCopyModifier];\n}\nhandlers.dragstart = (view, _event) => {\n let event = _event;\n let mouseDown = view.input.mouseDown;\n if (mouseDown)\n mouseDown.done();\n if (!event.dataTransfer)\n return;\n let sel = view.state.selection;\n let pos = sel.empty ? null : view.posAtCoords(eventCoords(event));\n let node;\n if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ;\n else if (mouseDown && mouseDown.mightDrag) {\n node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos);\n }\n else if (event.target && isElt(event.target)) {\n let desc = view.docView.nearestDesc(event.target, true);\n if (desc && desc.node.type.spec.draggable && desc != view.docView)\n node = NodeSelection.create(view.state.doc, desc.posBefore);\n }\n let draggedSlice = (node || view.state.selection).content();\n let { dom, text, slice } = serializeForClipboard(view, draggedSlice);\n // Pre-120 Chrome versions clear files when calling `clearData` (#1472)\n if (!event.dataTransfer.files.length || !chrome || chrome_version > 120)\n event.dataTransfer.clearData();\n event.dataTransfer.setData(brokenClipboardAPI ? \"Text\" : \"text/html\", dom.innerHTML);\n // See https://code.haverbeke.berlin/prosemirror/prosemirror/issues/1156\n event.dataTransfer.effectAllowed = \"copyMove\";\n if (!brokenClipboardAPI)\n event.dataTransfer.setData(\"text/plain\", text);\n view.dragging = new Dragging(slice, dragMoves(view, event), node);\n};\nhandlers.dragend = view => {\n let dragging = view.dragging;\n window.setTimeout(() => {\n if (view.dragging == dragging)\n view.dragging = null;\n }, 50);\n};\neditHandlers.dragover = editHandlers.dragenter = (_, e) => e.preventDefault();\neditHandlers.drop = (view, event) => {\n try {\n handleDrop(view, event, view.dragging);\n }\n finally {\n view.dragging = null;\n }\n};\nfunction handleDrop(view, event, dragging) {\n if (!event.dataTransfer)\n return;\n let eventPos = view.posAtCoords(eventCoords(event));\n if (!eventPos)\n return;\n let $mouse = view.state.doc.resolve(eventPos.pos);\n let slice = dragging && dragging.slice;\n if (slice) {\n view.someProp(\"transformPasted\", f => { slice = f(slice, view, false); });\n }\n else {\n slice = parseFromClipboard(view, getText(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData(\"text/html\"), false, $mouse);\n }\n let move = !!(dragging && dragMoves(view, event));\n if (view.someProp(\"handleDrop\", f => f(view, event, slice || Slice.empty, move))) {\n event.preventDefault();\n return;\n }\n if (!slice)\n return;\n event.preventDefault();\n let insertPos = slice ? dropPoint(view.state.doc, $mouse.pos, slice) : $mouse.pos;\n if (insertPos == null)\n insertPos = $mouse.pos;\n let tr = view.state.tr;\n if (move) {\n let { node } = dragging;\n if (node)\n node.replace(tr);\n else\n tr.deleteSelection();\n }\n let pos = tr.mapping.map(insertPos);\n let isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1;\n let 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))\n return;\n let $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 }\n else {\n let end = tr.mapping.map(insertPos);\n tr.mapping.maps[tr.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo);\n tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(end)));\n }\n view.focus();\n view.dispatch(tr.setMeta(\"uiEvent\", \"drop\"));\n}\nhandlers.focus = view => {\n view.input.lastFocus = Date.now();\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(() => {\n if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange()))\n selectionToDOM(view);\n }, 20);\n }\n};\nhandlers.blur = (view, _event) => {\n let event = _event;\n if (view.focused) {\n view.domObserver.stop();\n view.dom.classList.remove(\"ProseMirror-focused\");\n view.domObserver.start();\n if (event.relatedTarget && view.dom.contains(event.relatedTarget))\n view.domObserver.currentSelection.clear();\n view.focused = false;\n }\n};\nhandlers.beforeinput = (view, _event) => {\n let event = _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 // Very specific hack to deal with backspace sometimes failing on\n // Chrome and Firefox Android when after an uneditable node.\n if (android && event.inputType == \"deleteContentBackward\") {\n view.domObserver.flushSoon();\n let { domChangeCount } = view.input;\n setTimeout(() => {\n if (view.input.domChangeCount != domChangeCount)\n 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\", f => f(view, keyEvent(8, \"Backspace\"))))\n return;\n let { $cursor } = view.state.selection;\n // Crude approximation of backspace behavior when no command handled it\n if ($cursor && $cursor.pos > 0)\n view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView());\n }, 50);\n }\n};\n// Make sure all handlers get registered\nfor (let prop in editHandlers)\n handlers[prop] = editHandlers[prop];\n\nfunction compareObjs(a, b) {\n if (a == b)\n return true;\n for (let p in a)\n if (a[p] !== b[p])\n return false;\n for (let p in b)\n if (!(p in a))\n return false;\n return true;\n}\nclass FragmentCursor {\n constructor(frag) {\n this.frag = frag;\n this.index = 0;\n this.off = 0;\n }\n nodeAt(off) {\n while (this.off <= off && this.index < this.frag.childCount) {\n let next = this.frag.child(this.index);\n if (this.off == off)\n return next;\n this.off += next.nodeSize;\n this.index++;\n }\n return null;\n }\n}\nclass WidgetType {\n constructor(toDOM, spec) {\n this.toDOM = toDOM;\n this.spec = spec || noSpec;\n this.side = this.spec.side || 0;\n }\n map(mapping, span, offset, oldOffset) {\n let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);\n return deleted ? null : new Decoration(pos - offset, pos - offset, this);\n }\n valid() { return true; }\n 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 destroy(node) {\n if (this.spec.destroy)\n this.spec.destroy(node);\n }\n}\nclass InlineType {\n constructor(attrs, spec) {\n this.attrs = attrs;\n this.spec = spec || noSpec;\n }\n map(mapping, span, offset, oldOffset) {\n let from = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;\n let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;\n return from >= to ? null : new Decoration(from, to, this);\n }\n valid(_, span) { return span.from < span.to; }\n eq(other) {\n return this == other ||\n (other instanceof InlineType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec));\n }\n static is(span) { return span.type instanceof InlineType; }\n destroy() { }\n}\nclass NodeType {\n constructor(attrs, spec) {\n this.attrs = attrs;\n this.spec = spec || noSpec;\n }\n map(mapping, span, offset, oldOffset) {\n let from = mapping.mapResult(span.from + oldOffset, 1);\n if (from.deleted)\n return null;\n let to = mapping.mapResult(span.to + oldOffset, -1);\n if (to.deleted || to.pos <= from.pos)\n return null;\n return new Decoration(from.pos - offset, to.pos - offset, this);\n }\n valid(node, span, cursor) {\n let found = cursor.nodeAt(span.from);\n return !!found && !found.isText && span.from + found.nodeSize == span.to;\n }\n eq(other) {\n return this == other ||\n (other instanceof NodeType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec));\n }\n destroy() { }\n}\n/**\nDecoration objects can be provided to the view through the\n[`decorations` prop](https://prosemirror.net/docs/ref/#view.EditorProps.decorations). They come in\nseveral variants—see the static members of this class for details.\n*/\nclass Decoration {\n /**\n @internal\n */\n constructor(\n /**\n The start position of the decoration.\n */\n from, \n /**\n The end position. Will be the same as `from` for [widget\n decorations](https://prosemirror.net/docs/ref/#view.Decoration^widget).\n */\n to, \n /**\n @internal\n */\n type) {\n this.from = from;\n this.to = to;\n this.type = type;\n }\n /**\n @internal\n */\n copy(from, to) {\n return new Decoration(from, to, this.type);\n }\n /**\n @internal\n */\n eq(other, offset = 0) {\n return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to;\n }\n /**\n @internal\n */\n map(mapping, offset, oldOffset) {\n return this.type.map(mapping, this, offset, oldOffset);\n }\n /**\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 static widget(pos, toDOM, spec) {\n return new Decoration(pos, pos, new WidgetType(toDOM, spec));\n }\n /**\n Creates an inline decoration, which adds the given attributes to\n each inline node between `from` and `to`.\n */\n static inline(from, to, attrs, spec) {\n return new Decoration(from, to, new InlineType(attrs, spec));\n }\n /**\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 static node(from, to, attrs, spec) {\n return new Decoration(from, to, new NodeType(attrs, spec));\n }\n /**\n The spec provided when creating this decoration. Can be useful\n if you've stored extra information in that object.\n */\n get spec() { return this.type.spec; }\n /**\n @internal\n */\n get inline() { return this.type instanceof InlineType; }\n /**\n @internal\n */\n get widget() { return this.type instanceof WidgetType; }\n}\nconst none = [], noSpec = {};\n/**\nA collection of [decorations](https://prosemirror.net/docs/ref/#view.Decoration), organized in such\na way that the drawing algorithm can efficiently use and compare\nthem. This is a persistent data structure—it is not modified,\nupdates create a new value.\n*/\nclass DecorationSet {\n /**\n @internal\n */\n constructor(local, children) {\n this.local = local.length ? local : none;\n this.children = children.length ? children : none;\n }\n /**\n Create a set of decorations, using the structure of the given\n document. This will consume (modify) the `decorations` array, so\n you must make a copy if you want need to preserve that.\n */\n static create(doc, decorations) {\n return decorations.length ? buildTree(decorations, doc, 0, noSpec) : empty;\n }\n /**\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.\n */\n find(start, end, predicate) {\n let result = [];\n this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate);\n return result;\n }\n findInner(start, end, result, offset, predicate) {\n for (let i = 0; i < this.local.length; i++) {\n let 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 (let i = 0; i < this.children.length; i += 3) {\n if (this.children[i] < end && this.children[i + 1] > start) {\n let childOff = this.children[i] + 1;\n this.children[i + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate);\n }\n }\n }\n /**\n Map the set of decorations in response to a change in the\n document.\n */\n map(mapping, doc, options) {\n if (this == empty || mapping.maps.length == 0)\n return this;\n return this.mapInner(mapping, doc, 0, 0, options || noSpec);\n }\n /**\n @internal\n */\n mapInner(mapping, node, offset, oldOffset, options) {\n let newLocal;\n if (this.local.length) {\n let cur = new FragmentCursor(node.content);\n for (let i = 0; i < this.local.length; i++) {\n let mapped = this.local[i].map(mapping, offset, oldOffset);\n if (mapped && mapped.type.valid(node, mapped, cur))\n (newLocal || (newLocal = [])).push(mapped);\n else if (options.onRemove)\n 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), none) : empty;\n }\n /**\n Add the given array of decorations to the ones in the set,\n producing a new set. Consumes the `decorations` array. Needs\n access to the current document to create the appropriate tree\n structure.\n */\n add(doc, decorations) {\n if (!decorations.length)\n return this;\n if (this == empty)\n return DecorationSet.create(doc, decorations);\n return this.addInner(doc, decorations, 0);\n }\n addInner(doc, decorations, offset) {\n let children, childIndex = 0;\n doc.forEach((childNode, childOffset) => {\n let baseOffset = childOffset + offset, found;\n if (!(found = takeSpansForNode(decorations, childNode, baseOffset)))\n return;\n if (!children)\n children = this.children.slice();\n while (childIndex < children.length && children[childIndex] < childOffset)\n 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 let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset);\n if (local.length) {\n let cur = new FragmentCursor(doc.content);\n for (let i = 0; i < local.length; i++)\n if (!local[i].type.valid(doc, local[i], cur))\n local.splice(i--, 1);\n }\n return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children);\n }\n /**\n Create a new set that contains the decorations in this set, minus\n the ones in the given array.\n */\n remove(decorations) {\n if (decorations.length == 0 || this == empty)\n return this;\n return this.removeInner(decorations, 0);\n }\n removeInner(decorations, offset) {\n let children = this.children, local = this.local;\n for (let i = 0; i < children.length; i += 3) {\n let found;\n let from = children[i] + offset, to = children[i + 1] + offset;\n for (let j = 0, span; j < decorations.length; j++)\n 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)\n continue;\n if (children == this.children)\n children = this.children.slice();\n let removed = children[i + 2].removeInner(found, from + 1);\n if (removed != empty) {\n children[i + 2] = removed;\n }\n else {\n children.splice(i, 3);\n i -= 3;\n }\n }\n if (local.length)\n for (let i = 0, span; i < decorations.length; i++)\n if (span = decorations[i]) {\n for (let j = 0; j < local.length; j++)\n if (local[j].eq(span, offset)) {\n if (local == this.local)\n local = this.local.slice();\n local.splice(j--, 1);\n }\n }\n if (children == this.children && local == this.local)\n return this;\n return local.length || children.length ? new DecorationSet(local, children) : empty;\n }\n forChild(offset, node) {\n if (this == empty)\n return this;\n if (node.isLeaf)\n return DecorationSet.empty;\n let child, local;\n for (let i = 0; i < this.children.length; i += 3)\n if (this.children[i] >= offset) {\n if (this.children[i] == offset)\n child = this.children[i + 2];\n break;\n }\n let start = offset + 1, end = start + node.content.size;\n for (let i = 0; i < this.local.length; i++) {\n let dec = this.local[i];\n if (dec.from < end && dec.to > start && (dec.type instanceof InlineType)) {\n let from = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start;\n if (from < to)\n (local || (local = [])).push(dec.copy(from, to));\n }\n }\n if (local) {\n let localSet = new DecorationSet(local.sort(byPos), none);\n return child ? new DecorationGroup([localSet, child]) : localSet;\n }\n return child || empty;\n }\n /**\n @internal\n */\n eq(other) {\n if (this == other)\n return true;\n if (!(other instanceof DecorationSet) ||\n this.local.length != other.local.length ||\n this.children.length != other.children.length)\n return false;\n for (let i = 0; i < this.local.length; i++)\n if (!this.local[i].eq(other.local[i]))\n return false;\n for (let i = 0; i < this.children.length; i += 3)\n if (this.children[i] != other.children[i] ||\n this.children[i + 1] != other.children[i + 1] ||\n !this.children[i + 2].eq(other.children[i + 2]))\n return false;\n return true;\n }\n /**\n @internal\n */\n locals(node) {\n return removeOverlap(this.localsInner(node));\n }\n /**\n @internal\n */\n localsInner(node) {\n if (this == empty)\n return none;\n if (node.inlineContent || !this.local.some(InlineType.is))\n return this.local;\n let result = [];\n for (let 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 forEachSet(f) { f(this); }\n}\n/**\nThe empty set of decorations.\n*/\nDecorationSet.empty = new DecorationSet([], []);\n/**\n@internal\n*/\nDecorationSet.removeOverlap = removeOverlap;\nconst empty = DecorationSet.empty;\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.\nclass DecorationGroup {\n constructor(members) {\n this.members = members;\n }\n map(mapping, doc) {\n const mappedDecos = this.members.map(member => member.map(mapping, doc, noSpec));\n return DecorationGroup.from(mappedDecos);\n }\n forChild(offset, child) {\n if (child.isLeaf)\n return DecorationSet.empty;\n let found = [];\n for (let i = 0; i < this.members.length; i++) {\n let result = this.members[i].forChild(offset, child);\n if (result == empty)\n continue;\n if (result instanceof DecorationGroup)\n found = found.concat(result.members);\n else\n found.push(result);\n }\n return DecorationGroup.from(found);\n }\n eq(other) {\n if (!(other instanceof DecorationGroup) ||\n other.members.length != this.members.length)\n return false;\n for (let i = 0; i < this.members.length; i++)\n if (!this.members[i].eq(other.members[i]))\n return false;\n return true;\n }\n locals(node) {\n let result, sorted = true;\n for (let i = 0; i < this.members.length; i++) {\n let locals = this.members[i].localsInner(node);\n if (!locals.length)\n continue;\n if (!result) {\n result = locals;\n }\n else {\n if (sorted) {\n result = result.slice();\n sorted = false;\n }\n for (let j = 0; j < locals.length; j++)\n result.push(locals[j]);\n }\n }\n return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none;\n }\n // Create a group for the given array of decoration sets, or return\n // a single set when possible.\n static from(members) {\n switch (members.length) {\n case 0: return empty;\n case 1: return members[0];\n default: return new DecorationGroup(members.every(m => m instanceof DecorationSet) ? members :\n members.reduce((r, m) => r.concat(m instanceof DecorationSet ? m : m.members), []));\n }\n }\n forEachSet(f) {\n for (let i = 0; i < this.members.length; i++)\n this.members[i].forEachSet(f);\n }\n}\nfunction mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) {\n let children = oldChildren.slice();\n // Mark the children that are directly touched by changes, and\n // move those that are after the changes.\n for (let i = 0, baseOffset = oldOffset; i < mapping.maps.length; i++) {\n let moved = 0;\n mapping.maps[i].forEach((oldStart, oldEnd, newStart, newEnd) => {\n let dSize = (newEnd - newStart) - (oldEnd - oldStart);\n for (let i = 0; i < children.length; i += 3) {\n let end = children[i + 1];\n if (end < 0 || oldStart > end + baseOffset - moved)\n continue;\n let start = children[i] + baseOffset - moved;\n if (oldEnd >= start) {\n children[i + 1] = oldStart <= start ? -2 : -1;\n }\n else if (oldStart >= baseOffset && dSize) {\n children[i] += dSize;\n children[i + 1] += dSize;\n }\n }\n moved += dSize;\n });\n baseOffset = mapping.maps[i].map(baseOffset, -1);\n }\n // Find the child nodes that still correspond to a single node,\n // recursively call mapInner on them and update their positions.\n let mustRebuild = false;\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] < 0) { // Touched nodes\n if (children[i + 1] == -2) {\n mustRebuild = true;\n children[i + 1] = -1;\n continue;\n }\n let from = mapping.map(oldChildren[i] + 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 let to = mapping.map(oldChildren[i + 1] + oldOffset, -1), toLocal = to - offset;\n let { index, offset: childOffset } = node.content.findIndex(fromLocal);\n let childNode = node.maybeChild(index);\n if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {\n let mapped = children[i + 2]\n .mapInner(mapping, childNode, from + 1, oldChildren[i] + oldOffset + 1, options);\n if (mapped != empty) {\n children[i] = fromLocal;\n children[i + 1] = toLocal;\n children[i + 2] = mapped;\n }\n else {\n children[i + 1] = -2;\n mustRebuild = true;\n }\n }\n else {\n mustRebuild = true;\n }\n }\n // Remaining children must be collected and rebuilt into the appropriate structure\n if (mustRebuild) {\n let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options);\n let built = buildTree(decorations, node, 0, options);\n newLocal = built.local;\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] < 0) {\n children.splice(i, 3);\n i -= 3;\n }\n for (let i = 0, j = 0; i < built.children.length; i += 3) {\n let from = built.children[i];\n while (j < children.length && children[j] < from)\n j += 3;\n children.splice(j, 0, built.children[i], built.children[i + 1], built.children[i + 2]);\n }\n }\n return new DecorationSet(newLocal.sort(byPos), children);\n}\nfunction moveSpans(spans, offset) {\n if (!offset || !spans.length)\n return spans;\n let result = [];\n for (let i = 0; i < spans.length; i++) {\n let span = spans[i];\n result.push(new Decoration(span.from + offset, span.to + offset, span.type));\n }\n return result;\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 (let i = 0; i < set.local.length; i++) {\n let mapped = set.local[i].map(mapping, offset, oldOffset);\n if (mapped)\n decorations.push(mapped);\n else if (options.onRemove)\n options.onRemove(set.local[i].spec);\n }\n for (let i = 0; i < set.children.length; i += 3)\n gather(set.children[i + 2], set.children[i] + oldOffset + 1);\n }\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] == -1)\n gather(children[i + 2], oldChildren[i] + oldOffset + 1);\n return decorations;\n}\nfunction takeSpansForNode(spans, node, offset) {\n if (node.isLeaf)\n return null;\n let end = offset + node.nodeSize, found = null;\n for (let i = 0, span; 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}\nfunction withoutNulls(array) {\n let result = [];\n for (let i = 0; i < array.length; i++)\n if (array[i] != null)\n result.push(array[i]);\n return result;\n}\n// Build up a tree that corresponds to a set of decorations. `offset`\n// is a base offset that should be subtracted 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 let children = [], hasNulls = false;\n node.forEach((childNode, localStart) => {\n let found = takeSpansForNode(spans, childNode, localStart + offset);\n if (found) {\n hasNulls = true;\n let subtree = buildTree(found, childNode, offset + localStart + 1, options);\n if (subtree != empty)\n children.push(localStart, localStart + childNode.nodeSize, subtree);\n }\n });\n let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);\n if (locals.length) {\n let cur = new FragmentCursor(node.content);\n for (let i = 0; i < locals.length; i++)\n if (!locals[i].type.valid(node, locals[i], cur)) {\n if (options.onRemove)\n options.onRemove(locals[i].spec);\n locals.splice(i--, 1);\n }\n }\n return locals.length || children.length ? new DecorationSet(locals, children) : empty;\n}\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// 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 let working = spans;\n for (let i = 0; i < working.length - 1; i++) {\n let span = working[i];\n if (span.from != span.to)\n for (let j = i + 1; j < working.length; j++) {\n let next = working[j];\n if (next.from == span.from) {\n if (next.to != span.to) {\n if (working == spans)\n 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 }\n else {\n if (next.from < span.to) {\n if (working == spans)\n 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}\nfunction insertAhead(array, i, deco) {\n while (i < array.length && byPos(deco, array[i]) > 0)\n i++;\n array.splice(i, 0, deco);\n}\n// Get the decorations associated with the current props of a view.\nfunction viewDecorations(view) {\n let found = [];\n view.someProp(\"decorations\", f => {\n let result = f(view.state);\n if (result && result != empty)\n 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\nconst 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\nconst useCharData = ie && ie_version <= 11;\nclass SelectionState {\n constructor() {\n this.anchorNode = null;\n this.anchorOffset = 0;\n this.focusNode = null;\n this.focusOffset = 0;\n }\n set(sel) {\n this.anchorNode = sel.anchorNode;\n this.anchorOffset = sel.anchorOffset;\n this.focusNode = sel.focusNode;\n this.focusOffset = sel.focusOffset;\n }\n clear() {\n this.anchorNode = this.focusNode = null;\n }\n eq(sel) {\n return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset &&\n sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset;\n }\n}\nclass DOMObserver {\n constructor(view, handleDOMChange) {\n this.view = view;\n this.handleDOMChange = handleDOMChange;\n this.queue = [];\n this.flushingSoon = -1;\n this.observer = null;\n this.currentSelection = new SelectionState;\n this.onCharData = null;\n this.suppressingSelectionUpdates = false;\n this.lastChangedTextNode = null;\n this.observer = window.MutationObserver &&\n new window.MutationObserver(mutations => {\n for (let i = 0; i < mutations.length; i++)\n this.queue.push(mutations[i]);\n if (ie && ie_version <= 11 && mutations.some(m => m.type == \"childList\" && m.removedNodes.length ||\n m.type == \"characterData\" && m.oldValue.length > m.target.nodeValue.length)) {\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 this.flushSoon();\n }\n else if (safari && view.composing && mutations.some(m => m.type == \"childList\" && m.target.nodeName == \"TR\")) {\n // Safari does weird stuff when finishing a composition in a\n // table cell, which tends to involve inserting inappropriate\n // nodes in the table row.\n view.input.badSafariComposition = true;\n this.flushSoon();\n }\n else {\n this.flush();\n }\n });\n if (useCharData) {\n this.onCharData = e => {\n this.queue.push({ target: e.target, type: \"characterData\", oldValue: e.prevValue });\n this.flushSoon();\n };\n }\n this.onSelectionChange = this.onSelectionChange.bind(this);\n }\n flushSoon() {\n if (this.flushingSoon < 0)\n this.flushingSoon = window.setTimeout(() => { this.flushingSoon = -1; this.flush(); }, 20);\n }\n forceFlush() {\n if (this.flushingSoon > -1) {\n window.clearTimeout(this.flushingSoon);\n this.flushingSoon = -1;\n this.flush();\n }\n }\n start() {\n if (this.observer) {\n this.observer.takeRecords();\n this.observer.observe(this.view.dom, observeOptions);\n }\n if (this.onCharData)\n this.view.dom.addEventListener(\"DOMCharacterDataModified\", this.onCharData);\n this.connectSelection();\n }\n stop() {\n if (this.observer) {\n let take = this.observer.takeRecords();\n if (take.length) {\n for (let i = 0; i < take.length; i++)\n this.queue.push(take[i]);\n window.setTimeout(() => this.flush(), 20);\n }\n this.observer.disconnect();\n }\n if (this.onCharData)\n this.view.dom.removeEventListener(\"DOMCharacterDataModified\", this.onCharData);\n this.disconnectSelection();\n }\n connectSelection() {\n this.view.dom.ownerDocument.addEventListener(\"selectionchange\", this.onSelectionChange);\n }\n disconnectSelection() {\n this.view.dom.ownerDocument.removeEventListener(\"selectionchange\", this.onSelectionChange);\n }\n suppressSelectionUpdates() {\n this.suppressingSelectionUpdates = true;\n setTimeout(() => this.suppressingSelectionUpdates = false, 50);\n }\n onSelectionChange() {\n if (!hasFocusAndSelection(this.view))\n return;\n if (this.suppressingSelectionUpdates)\n 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 (ie && ie_version <= 11 && !this.view.state.selection.empty) {\n let sel = this.view.domSelectionRange();\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 setCurSelection() {\n this.currentSelection.set(this.view.domSelectionRange());\n }\n ignoreSelectionChange(sel) {\n if (!sel.focusNode)\n return true;\n let ancestors = new Set, container;\n for (let scan = sel.focusNode; scan; scan = parentNode(scan))\n ancestors.add(scan);\n for (let scan = sel.anchorNode; scan; scan = parentNode(scan))\n if (ancestors.has(scan)) {\n container = scan;\n break;\n }\n let desc = container && this.view.docView.nearestDesc(container);\n if (desc && desc.ignoreMutation({\n type: \"selection\",\n target: isText(container) ? container.parentNode : container\n })) {\n this.setCurSelection();\n return true;\n }\n }\n pendingRecords() {\n if (this.observer)\n for (let mut of this.observer.takeRecords())\n this.queue.push(mut);\n return this.queue;\n }\n flush() {\n let { view } = this;\n if (!view.docView || this.flushingSoon > -1)\n return;\n let mutations = this.pendingRecords();\n if (mutations.length)\n this.queue = [];\n let selRange, newSel = false;\n if (!this.suppressingSelectionUpdates && hasFocusAndSelection(view)) {\n selRange = view.domSelectionRange();\n newSel = !this.currentSelection.eq(selRange) && !this.ignoreSelectionChange(selRange);\n }\n let from = -1, to = -1, typeOver = false, added = [];\n if (view.editable) {\n for (let i = 0; i < mutations.length; i++) {\n let result = this.registerMutation(mutations[i], added);\n if (result) {\n from = from < 0 ? result.from : Math.min(result.from, from);\n to = to < 0 ? result.to : Math.max(result.to, to);\n if (result.typeOver)\n typeOver = true;\n }\n }\n }\n if (added.some(n => n.nodeName == \"BR\") &&\n (view.input.lastKeyCode == 8 || view.input.lastKeyCode == 46 ||\n chrome && (view.composing || view.input.compositionEndedAt > Date.now() - 50) &&\n mutations.some(m => m.type == \"childList\" && m.removedNodes.length))) {\n // Browsers sometimes insert a bogus break node if you\n // backspace out the last bit of text before an inline-flex node (#1552)\n for (let node of added)\n if (node.nodeName == \"BR\" && node.parentNode) {\n let after = node.nextSibling;\n while (after && isElt(after)) {\n if (after.contentEditable == \"false\") {\n node.parentNode.removeChild(node);\n break;\n }\n after = after.firstChild;\n }\n }\n }\n else if (gecko && added.length) {\n let brs = added.filter(n => n.nodeName == \"BR\");\n if (brs.length == 2) {\n let [a, b] = brs;\n if (a.parentNode && a.parentNode.parentNode == b.parentNode)\n b.remove();\n else\n a.remove();\n }\n else {\n let { focusNode } = this.currentSelection;\n for (let br of brs) {\n let parent = br.parentNode;\n if (parent && parent.nodeName == \"LI\" && (!focusNode || blockParent(view, focusNode) != parent))\n br.remove();\n }\n }\n }\n let readSel = null;\n // If it looks like the browser has reset the selection to the\n // start of the document after focus, restore the selection from\n // the state\n if (from < 0 && newSel && view.input.lastFocus > Date.now() - 200 &&\n Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 &&\n selectionCollapsed(selRange) && (readSel = selectionFromDOM(view)) &&\n readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) {\n view.input.lastFocus = 0;\n selectionToDOM(view);\n this.currentSelection.set(selRange);\n view.scrollToSelection();\n }\n else if (from > -1 || newSel) {\n if (from > -1) {\n view.docView.markDirty(from, to);\n checkCSS(view);\n }\n if (view.input.badSafariComposition) {\n view.input.badSafariComposition = false;\n fixUpBadSafariComposition(view, added);\n }\n this.handleDOMChange(from, to, typeOver, added);\n if (view.docView && view.docView.dirty)\n view.updateState(view.state);\n else if (selRange && !this.currentSelection.eq(selRange))\n selectionToDOM(view);\n if (selRange)\n this.currentSelection.set(selRange);\n }\n }\n registerMutation(mut, added) {\n // Ignore mutations inside nodes that were already noted as inserted\n if (added.indexOf(mut.target) > -1)\n return null;\n let 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))\n return null;\n if (mut.type == \"childList\") {\n for (let i = 0; i < mut.addedNodes.length; i++) {\n let node = mut.addedNodes[i];\n added.push(node);\n if (isText(node))\n this.lastChangedTextNode = node;\n }\n if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target))\n return { from: desc.posBefore, to: desc.posAfter };\n let prev = mut.previousSibling, next = mut.nextSibling;\n if (ie && 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 (let i = 0; i < mut.addedNodes.length; i++) {\n let { previousSibling, nextSibling } = mut.addedNodes[i];\n if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0)\n prev = previousSibling;\n if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0)\n next = nextSibling;\n }\n }\n let fromOffset = prev && prev.parentNode == mut.target\n ? domIndex(prev) + 1 : 0;\n let from = desc.localPosFromDOM(mut.target, fromOffset, -1);\n let toOffset = next && next.parentNode == mut.target\n ? domIndex(next) : mut.target.childNodes.length;\n let to = desc.localPosFromDOM(mut.target, toOffset, 1);\n return { from, to };\n }\n else if (mut.type == \"attributes\") {\n return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border };\n }\n else { // \"characterData\"\n this.lastChangedTextNode = mut.target;\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}\nlet cssChecked = new WeakMap();\nlet cssCheckWarned = false;\nfunction checkCSS(view) {\n if (cssChecked.has(view))\n return;\n cssChecked.set(view, null);\n if (['normal', 'nowrap', 'pre-line'].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) {\n view.requiresGeckoHackNode = gecko;\n if (cssCheckWarned)\n return;\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 cssCheckWarned = true;\n }\n}\nfunction rangeToSelectionRange(view, range) {\n let anchorNode = range.startContainer, anchorOffset = range.startOffset;\n let focusNode = range.endContainer, focusOffset = range.endOffset;\n let currentAnchor = view.domAtPos(view.state.selection.anchor);\n // Since such a range doesn't distinguish between anchor and head,\n // use a heuristic that flips it around if its end matches the\n // current anchor.\n if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset))\n [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];\n return { anchorNode, anchorOffset, focusNode, focusOffset };\n}\n// Used to work around a Safari Selection/shadow DOM bug\n// Based on https://github.com/codemirror/dev/issues/414 fix\nfunction safariShadowSelectionRange(view, selection) {\n if (selection.getComposedRanges) {\n let range = selection.getComposedRanges(view.root)[0];\n if (range)\n return rangeToSelectionRange(view, range);\n }\n let found;\n function read(event) {\n event.preventDefault();\n event.stopImmediatePropagation();\n found = event.getTargetRanges()[0];\n }\n // Because Safari (at least in 2018-2022) doesn't provide regular\n // access to the selection inside a shadowRoot, we have to perform a\n // ridiculous hack to get at it—using `execCommand` to trigger a\n // `beforeInput` event so that we can read the target range from the\n // event.\n view.dom.addEventListener(\"beforeinput\", read, true);\n document.execCommand(\"indent\");\n view.dom.removeEventListener(\"beforeinput\", read, true);\n return found ? rangeToSelectionRange(view, found) : null;\n}\nfunction blockParent(view, node) {\n for (let p = node.parentNode; p && p != view.dom; p = p.parentNode) {\n let desc = view.docView.nearestDesc(p, true);\n if (desc && desc.node.isBlock)\n return p;\n }\n return null;\n}\n// Kludge for a Safari bug where, on ending a composition in an\n// otherwise empty table cell, it randomly moves the composed text\n// into the table row around that cell, greatly confusing everything\n// (#188).\nfunction fixUpBadSafariComposition(view, addedNodes) {\n var _a;\n let { focusNode, focusOffset } = view.domSelectionRange();\n for (let node of addedNodes) {\n if (((_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.nodeName) == \"TR\") {\n let nextCell = node.nextSibling;\n while (nextCell && (nextCell.nodeName != \"TD\" && nextCell.nodeName != \"TH\"))\n nextCell = nextCell.nextSibling;\n if (nextCell) {\n let parent = nextCell;\n for (;;) {\n let first = parent.firstChild;\n if (!first || !isElt(first) || first.contentEditable == \"false\" || /^(BR|IMG)$/.test(first.nodeName))\n break;\n parent = first;\n }\n parent.insertBefore(node, parent.firstChild);\n if (focusNode == node)\n view.domSelection().collapse(node, focusOffset);\n }\n else {\n node.parentNode.removeChild(node);\n }\n }\n }\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.\nfunction parseBetween(view, from_, to_, addedNodes) {\n let { node: parent, fromOffset, toOffset, from, to } = view.docView.parseRange(from_, to_);\n let domSel = view.domSelectionRange();\n let find;\n let anchor = domSel.anchorNode;\n if (anchor && contains(view.dom, anchor)) {\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 (chrome && view.input.lastKeyCode === 8) {\n for (let off = toOffset; off > fromOffset; off--) {\n let node = parent.childNodes[off - 1], desc = node.pmViewDesc;\n if (node.nodeName == \"BR\" && !desc) {\n toOffset = off;\n break;\n }\n if (!desc || desc.size)\n break;\n }\n }\n let startDoc = view.state.doc;\n let parser = view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n let $from = startDoc.resolve(from);\n let 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.whitespace == \"pre\" ? \"full\" : true,\n findPositions: find,\n ruleFromNode: ruleFromNode(addedNodes),\n context: $from\n });\n if (find && find[0].pos != null) {\n let anchor = find[0].pos, head = find[1] && find[1].pos;\n if (head == null)\n head = anchor;\n sel = { anchor: anchor + from, head: head + from };\n }\n return { doc, sel, from, to };\n}\nconst ruleFromNode = (added) => (dom) => {\n let desc = dom.pmViewDesc;\n if (desc) {\n return desc.parseRule(added);\n }\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 (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {\n let skip = document.createElement(\"div\");\n skip.appendChild(document.createElement(\"li\"));\n return { skip };\n }\n else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {\n return { ignore: true };\n }\n }\n else if (dom.nodeName == \"IMG\" && dom.getAttribute(\"mark-placeholder\")) {\n return { ignore: true };\n }\n return null;\n};\nconst isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;\nfunction readDOMChange(view, from, to, typeOver, addedNodes) {\n let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0);\n view.input.compositionPendingChanges = 0;\n if (from < 0) {\n let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null;\n let newSel = selectionFromDOM(view, origin);\n if (newSel && !view.state.selection.eq(newSel)) {\n if (chrome && android &&\n view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\"))))\n return;\n let tr = view.state.tr.setSelection(newSel);\n if (origin == \"pointer\")\n tr.setMeta(\"pointer\", true);\n else if (origin == \"key\")\n tr.scrollIntoView();\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n view.dispatch(tr);\n }\n return;\n }\n let $before = view.state.doc.resolve(from);\n let shared = $before.sharedDepth(to);\n from = $before.before(shared + 1);\n to = view.state.doc.resolve(to).after(shared + 1);\n let sel = view.state.selection;\n let parse = parseBetween(view, from, to, addedNodes);\n let doc = view.state.doc, compare = doc.slice(parse.from, parse.to);\n let preferredPos, preferredSide;\n // Prefer anchoring to end when Backspace is pressed\n if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) {\n preferredPos = view.state.selection.to;\n preferredSide = \"end\";\n }\n else {\n preferredPos = view.state.selection.from;\n preferredSide = \"start\";\n }\n view.input.lastKeyCode = null;\n let change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide);\n if (change)\n view.input.domChangeCount++;\n if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) &&\n addedNodes.some(n => isElt(n) && !isInline.test(n.nodeName)) &&\n (!change || change.endA >= change.endB) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")))) {\n view.input.lastIOSEnter = 0;\n return;\n }\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 }\n else {\n if (parse.sel) {\n let sel = resolveSelection(view, view.state.doc, parse.sel);\n if (sel && !sel.eq(view.state.selection)) {\n let tr = view.state.tr.setSelection(sel);\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n view.dispatch(tr);\n }\n }\n return;\n }\n }\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 view.state.selection.from >= parse.from) {\n change.start = view.state.selection.from;\n }\n else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 &&\n view.state.selection.to <= parse.to) {\n change.endB += (view.state.selection.to - change.endA);\n change.endA = view.state.selection.to;\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 (ie && 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 let $from = parse.doc.resolveNoCache(change.start - parse.from);\n let $to = parse.doc.resolveNoCache(change.endB - parse.from);\n let $fromA = doc.resolve(change.start);\n let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA;\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 (((ios && view.input.lastIOSEnter > Date.now() - 225 &&\n (!inlineChange || addedNodes.some(n => n.nodeName == \"DIV\" || n.nodeName == \"P\"))) ||\n (!inlineChange && looksLikeEnter(parse.doc, $from.pos, $to.pos))) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")))) {\n view.input.lastIOSEnter = 0;\n return;\n }\n // Same for backspace\n if (view.state.selection.anchor > change.start &&\n (inlineChange ? change.endA > change.start && change.endB == change.start\n : looksLikeBlockJoin(doc, change.start, change.endA, $from, $to)) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(8, \"Backspace\")))) {\n if (android && chrome)\n view.domObserver.suppressSelectionUpdates(); // #820\n return;\n }\n // Chrome will occasionally, during composition, delete the\n // entire composition and then immediately insert it again. This is\n // used to detect that situation.\n if (chrome && change.endB == change.start)\n view.input.lastChromeDelete = Date.now();\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 (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(() => {\n view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(13, \"Enter\")); });\n }, 20);\n }\n let chFrom = change.start, chTo = change.endA;\n let mkTr = (base) => {\n let tr = base || view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from));\n if (parse.sel) {\n let sel = resolveSelection(view, tr.doc, parse.sel);\n // Chrome 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 && !(chrome && view.composing && sel.empty &&\n (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) &&\n (sel.head == chFrom || sel.head == tr.mapping.map(chTo) - 1) ||\n ie && sel.empty && sel.head == chFrom))\n tr.setSelection(sel);\n }\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n return tr.scrollIntoView();\n };\n let markChange;\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 (ie && ie_version <= 11 && $from.parentOffset == 0) {\n view.domObserver.suppressSelectionUpdates();\n setTimeout(() => selectionToDOM(view), 20);\n }\n let tr = mkTr(view.state.tr.delete(chFrom, chTo));\n let marks = doc.resolve(change.start).marksAcross(doc.resolve(change.endA));\n if (marks)\n tr.ensureMarks(marks);\n view.dispatch(tr);\n }\n else if ( // Adding or removing a mark\n change.endA == change.endB &&\n (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start())))) {\n let tr = mkTr(view.state.tr);\n if (markChange.type == \"add\")\n tr.addMark(chFrom, chTo, markChange.mark);\n else\n tr.removeMark(chFrom, chTo, markChange.mark);\n view.dispatch(tr);\n }\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 let text = $from.parent.textBetween($from.parentOffset, $to.parentOffset);\n let deflt = () => mkTr(view.state.tr.insertText(text, chFrom, chTo));\n if (!view.someProp(\"handleTextInput\", f => f(view, chFrom, chTo, text, deflt)))\n view.dispatch(deflt());\n }\n else {\n view.dispatch(mkTr());\n }\n }\n else {\n view.dispatch(mkTr());\n }\n}\nfunction resolveSelection(view, doc, parsedSel) {\n if (Math.max(parsedSel.anchor, parsedSel.head) > doc.content.size)\n return null;\n return selectionBetween(view, doc.resolve(parsedSel.anchor), doc.resolve(parsedSel.head));\n}\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 let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;\n let added = curMarks, removed = prevMarks, type, mark, update;\n for (let i = 0; i < prevMarks.length; i++)\n added = prevMarks[i].removeFromSet(added);\n for (let i = 0; i < curMarks.length; i++)\n removed = curMarks[i].removeFromSet(removed);\n if (added.length == 1 && removed.length == 0) {\n mark = added[0];\n type = \"add\";\n update = (node) => node.mark(mark.addToSet(node.marks));\n }\n else if (added.length == 0 && removed.length == 1) {\n mark = removed[0];\n type = \"remove\";\n update = (node) => node.mark(mark.removeFromSet(node.marks));\n }\n else {\n return null;\n }\n let updated = [];\n for (let i = 0; i < prev.childCount; i++)\n updated.push(update(prev.child(i)));\n if (Fragment.from(updated).eq(cur))\n return { mark, type };\n}\nfunction looksLikeBlockJoin(old, start, end, $newStart, $newEnd) {\n if ( // 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 let $start = old.resolve(start);\n // Handle the case where, rather than joining blocks, the change just removed an entire block\n if (!$newStart.parent.inlineContent) {\n let after = $start.nodeAfter;\n return after != null && end == start + after.nodeSize;\n }\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 let $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 // The fragments after the join point must match\n return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content);\n}\nfunction looksLikeEnter(content, from, to) {\n let newTextlines = 0, newLeaves = 0;\n content.nodesBetween(from, to, (node, pos) => {\n if (node.isTextblock && pos >= from && pos < to)\n newTextlines++;\n else if (node.isText ? /\\S/.test(node.text.slice(Math.max(0, from - pos), Math.min(node.nodeSize, to - pos))) : node.isLeaf)\n newLeaves++;\n });\n return newLeaves == 0 && newTextlines == 1;\n}\nfunction skipClosingAndOpening($pos, fromEnd, mayOpen) {\n let 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 let 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}\nfunction findDiff(a, b, pos, preferredPos, preferredSide) {\n let start = a.findDiffStart(b, pos), lenA = pos + a.size, lenB = pos + b.size;\n if (start == null)\n return null;\n let { a: endA, b: endB } = a.findDiffEnd(b, lenA, lenB);\n if (preferredSide == \"end\") {\n let adjust = Math.max(0, start - Math.min(endA, endB));\n preferredPos -= endA + adjust - start;\n }\n if (endA < start && lenA < lenB) {\n let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0;\n start -= move;\n endB = start + (endB - endA);\n endA = start;\n }\n else if (endB < start) {\n let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0;\n start -= move;\n endA = start + (endA - endB);\n endB = start;\n }\n return { start, endA, endB };\n}\n\n/**\n@internal\n*/\nconst __parseFromClipboard = parseFromClipboard;\n/**\n@internal\n*/\nconst __endComposition = endComposition;\n/**\nAn editor view manages the DOM structure that represents an\neditable document. Its state and behavior are determined by its\n[props](https://prosemirror.net/docs/ref/#view.DirectEditorProps).\n*/\nclass EditorView {\n /**\n Create a view. `place` may be a DOM node that the editor should\n be appended to, a function that will place it into the document,\n or an object whose `mount` property holds the node to use as the\n document container. If it is `null`, the editor will not be\n added to the document.\n */\n constructor(place, props) {\n this._root = null;\n /**\n @internal\n */\n this.focused = false;\n /**\n Kludge used to work around a Chrome bug @internal\n */\n this.trackWrites = null;\n this.mounted = false;\n /**\n @internal\n */\n this.markCursor = null;\n /**\n @internal\n */\n this.cursorWrapper = null;\n /**\n @internal\n */\n this.lastSelectedViewDesc = undefined;\n /**\n @internal\n */\n this.input = new InputState;\n this.prevDirectPlugins = [];\n this.pluginViews = [];\n /**\n Holds `true` when a hack node is needed in Firefox to prevent the\n [space is eaten issue](https://code.haverbeke.berlin/prosemirror/prosemirror/issues/651)\n @internal\n */\n this.requiresGeckoHackNode = false;\n /**\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 */\n this.dragging = null;\n this._props = props;\n this.state = props.state;\n this.directPlugins = props.plugins || [];\n this.directPlugins.forEach(checkStateComponent);\n this.dispatch = this.dispatch.bind(this);\n this.dom = (place && place.mount) || document.createElement(\"div\");\n if (place) {\n if (place.appendChild)\n place.appendChild(this.dom);\n else if (typeof place == \"function\")\n place(this.dom);\n else if (place.mount)\n this.mounted = true;\n }\n this.editable = getEditable(this);\n updateCursorWrapper(this);\n this.nodeViews = buildNodeViews(this);\n this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);\n this.domObserver = new DOMObserver(this, (from, to, typeOver, added) => readDOMChange(this, from, to, typeOver, added));\n this.domObserver.start();\n initInput(this);\n this.updatePluginViews();\n }\n /**\n Holds `true` when a\n [composition](https://w3c.github.io/uievents/#events-compositionevents)\n is active.\n */\n get composing() { return this.input.composing; }\n /**\n The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps).\n */\n get props() {\n if (this._props.state != this.state) {\n let prev = this._props;\n this._props = {};\n for (let name in prev)\n this._props[name] = prev[name];\n this._props.state = this.state;\n }\n return this._props;\n }\n /**\n Update the view's props. Will immediately cause an update to\n the DOM.\n */\n update(props) {\n if (props.handleDOMEvents != this._props.handleDOMEvents)\n ensureListeners(this);\n let prevProps = this._props;\n this._props = props;\n if (props.plugins) {\n props.plugins.forEach(checkStateComponent);\n this.directPlugins = props.plugins;\n }\n this.updateStateInner(props.state, prevProps);\n }\n /**\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))`.\n */\n setProps(props) {\n let updated = {};\n for (let name in this._props)\n updated[name] = this._props[name];\n updated.state = this.state;\n for (let name in props)\n updated[name] = props[name];\n this.update(updated);\n }\n /**\n Update the editor's `state` prop, without touching any of the\n other props.\n */\n updateState(state) {\n this.updateStateInner(state, this._props);\n }\n updateStateInner(state, prevProps) {\n var _a;\n let 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 let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins;\n if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) {\n let nodeViews = buildNodeViews(this);\n if (changedNodeViews(nodeViews, this.nodeViews)) {\n this.nodeViews = nodeViews;\n redraw = true;\n }\n }\n if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) {\n ensureListeners(this);\n }\n this.editable = getEditable(this);\n updateCursorWrapper(this);\n let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);\n let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? \"reset\"\n : state.scrollToSelection > prev.scrollToSelection ? \"to selection\" : \"preserve\";\n let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);\n if (updateDoc || !state.selection.eq(prev.selection))\n updateSel = true;\n let oldScrollPos = scroll == \"preserve\" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);\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 let forceSelUpdate = updateDoc && (ie || 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 let chromeKludge = chrome ? (this.trackWrites = this.domSelectionRange().focusNode) : null;\n if (this.composing)\n this.input.compositionNode = findCompositionNode(this);\n if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {\n this.docView.updateOuterDeco(outerDeco);\n this.docView.destroy();\n this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);\n }\n if (chromeKludge && (!this.trackWrites || !this.dom.contains(this.trackWrites)))\n 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 let mouseDown = this.input.mouseDown;\n if (forceSelUpdate ||\n !(mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) &&\n anchorInRightPlace(this) && mouseDown.delaySelUpdate())) {\n selectionToDOM(this, forceSelUpdate);\n }\n else {\n syncNodeSelection(this, state.selection);\n this.domObserver.setCurSelection();\n }\n this.domObserver.start();\n }\n this.updatePluginViews(prev);\n if (((_a = this.dragging) === null || _a === void 0 ? void 0 : _a.node) && !prev.doc.eq(state.doc))\n this.updateDraggedNode(this.dragging, prev);\n if (scroll == \"reset\") {\n this.dom.scrollTop = 0;\n }\n else if (scroll == \"to selection\") {\n this.scrollToSelection();\n }\n else if (oldScrollPos) {\n resetScrollPos(oldScrollPos);\n }\n }\n /**\n @internal\n */\n scrollToSelection() {\n let startDOM = this.domSelectionRange().focusNode;\n if (!startDOM || !contains(this.dom, startDOM)) ;\n else if (this.someProp(\"handleScrollToSelection\", f => f(this))) ;\n else if (this.state.selection instanceof NodeSelection) {\n let target = this.docView.domAfterPos(this.state.selection.from);\n if (isElt(target))\n scrollRectIntoView(this, target.getBoundingClientRect(), startDOM);\n }\n else {\n scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM);\n }\n }\n destroyPluginViews() {\n let view;\n while (view = this.pluginViews.pop())\n if (view.destroy)\n view.destroy();\n }\n updatePluginViews(prevState) {\n if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {\n this.prevDirectPlugins = this.directPlugins;\n this.destroyPluginViews();\n for (let i = 0; i < this.directPlugins.length; i++) {\n let plugin = this.directPlugins[i];\n if (plugin.spec.view)\n this.pluginViews.push(plugin.spec.view(this));\n }\n for (let i = 0; i < this.state.plugins.length; i++) {\n let plugin = this.state.plugins[i];\n if (plugin.spec.view)\n this.pluginViews.push(plugin.spec.view(this));\n }\n }\n else {\n for (let i = 0; i < this.pluginViews.length; i++) {\n let pluginView = this.pluginViews[i];\n if (pluginView.update)\n pluginView.update(this, prevState);\n }\n }\n }\n updateDraggedNode(dragging, prev) {\n let sel = dragging.node, found = -1;\n if (sel.from < this.state.doc.content.size && this.state.doc.nodeAt(sel.from) == sel.node) {\n found = sel.from;\n }\n else {\n let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size);\n let moved = movedPos > 0 && movedPos < this.state.doc.content.size && this.state.doc.nodeAt(movedPos);\n if (moved == sel.node)\n found = movedPos;\n }\n this.dragging = new Dragging(dragging.slice, dragging.move, found < 0 ? undefined : NodeSelection.create(this.state.doc, found));\n }\n someProp(propName, f) {\n let prop = this._props && this._props[propName], value;\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n for (let i = 0; i < this.directPlugins.length; i++) {\n let prop = this.directPlugins[i].props[propName];\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n }\n let plugins = this.state.plugins;\n if (plugins)\n for (let i = 0; i < plugins.length; i++) {\n let prop = plugins[i].props[propName];\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n }\n }\n /**\n Query whether the view has focus.\n */\n hasFocus() {\n // Work around IE not handling focus correctly if resize handles are shown.\n // If the cursor is inside an element with resize handles, activeElement\n // will be that element instead of this.dom.\n if (ie) {\n // If activeElement is within this.dom, and there are no other elements\n // setting `contenteditable` to false in between, treat it as focused.\n let node = this.root.activeElement;\n if (node == this.dom)\n return true;\n if (!node || !this.dom.contains(node))\n return false;\n while (node && this.dom != node && this.dom.contains(node)) {\n if (node.contentEditable == 'false')\n return false;\n node = node.parentElement;\n }\n return true;\n }\n return this.root.activeElement == this.dom;\n }\n /**\n Focus the editor.\n */\n focus() {\n this.domObserver.stop();\n if (this.editable)\n focusPreventScroll(this.dom);\n selectionToDOM(this);\n this.domObserver.start();\n }\n /**\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.\n */\n get root() {\n let cached = this._root;\n if (cached == null)\n for (let search = this.dom.parentNode; search; search = search.parentNode) {\n if (search.nodeType == 9 || (search.nodeType == 11 && search.host)) {\n if (!search.getSelection)\n Object.getPrototypeOf(search).getSelection = () => search.ownerDocument.getSelection();\n return this._root = search;\n }\n }\n return cached || document;\n }\n /**\n When an existing editor view is moved to a new document or\n shadow tree, call this to make it recompute its root.\n */\n updateRoot() {\n this._root = null;\n }\n /**\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.\n */\n posAtCoords(coords) {\n return posAtCoords(this, coords);\n }\n /**\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\n is used. When < 0, the element before the position is used,\n otherwise the element after.\n */\n coordsAtPos(pos, side = 1) {\n return coordsAtPos(this, pos, side);\n }\n /**\n Find the DOM position that corresponds to the given document\n position. When `side` is negative, find the position as close as\n possible to the content before the position. When positive,\n prefer positions close to the content after the position. When\n zero, prefer as shallow a position as possible.\n \n Note that you should **not** mutate the editor's internal DOM,\n only inspect it (and even that is usually not necessary).\n */\n domAtPos(pos, side = 0) {\n return this.docView.domFromPos(pos, side);\n }\n /**\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.\n */\n nodeDOM(pos) {\n let desc = this.docView.descAt(pos);\n return desc ? desc.nodeDOM : null;\n }\n /**\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.\n */\n posAtDOM(node, offset, bias = -1) {\n let pos = this.docView.posFromDOM(node, offset, bias);\n if (pos == null)\n throw new RangeError(\"DOM position not inside the editor\");\n return pos;\n }\n /**\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.\n */\n endOfTextblock(dir, state) {\n return endOfTextblock(this, state || this.state, dir);\n }\n /**\n Run the editor's paste logic with the given HTML string. The\n `event`, if given, will be passed to the\n [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook.\n */\n pasteHTML(html, event) {\n return doPaste(this, \"\", html, false, event || new ClipboardEvent(\"paste\"));\n }\n /**\n Run the editor's paste logic with the given plain-text input.\n */\n pasteText(text, event) {\n return doPaste(this, text, null, true, event || new ClipboardEvent(\"paste\"));\n }\n /**\n Serialize the given slice as it would be if it was copied from\n this editor. Returns a DOM element that contains a\n representation of the slice as its children, a textual\n representation, and the transformed slice (which can be\n different from the given input due to hooks like\n [`transformCopied`](https://prosemirror.net/docs/ref/#view.EditorProps.transformCopied)).\n */\n serializeForClipboard(slice) {\n return serializeForClipboard(this, slice);\n }\n /**\n Removes the editor from the DOM and destroys all [node\n views](https://prosemirror.net/docs/ref/#view.NodeView).\n */\n destroy() {\n if (!this.docView)\n 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 }\n else if (this.dom.parentNode) {\n this.dom.parentNode.removeChild(this.dom);\n }\n this.docView.destroy();\n this.docView = null;\n clearReusedRange();\n }\n /**\n This is true when the view has been\n [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be\n used anymore).\n */\n get isDestroyed() {\n return this.docView == null;\n }\n /**\n Used for testing.\n */\n dispatchEvent(event) {\n return dispatchEvent(this, event);\n }\n /**\n @internal\n */\n domSelectionRange() {\n let sel = this.dom.isConnected !== false && this.domSelection();\n if (!sel)\n return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 };\n return safari && this.root.nodeType === 11 &&\n deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel;\n }\n /**\n @internal\n */\n domSelection() {\n return this.root.getSelection();\n }\n}\nEditorView.prototype.dispatch = function (tr) {\n let dispatchTransaction = this._props.dispatchTransaction;\n if (dispatchTransaction)\n dispatchTransaction.call(this, tr);\n else\n this.updateState(this.state.apply(tr));\n};\nfunction computeDocDeco(view) {\n let attrs = Object.create(null);\n attrs.class = \"ProseMirror\";\n attrs.contenteditable = String(view.editable);\n view.someProp(\"attributes\", value => {\n if (typeof value == \"function\")\n value = value(view.state);\n if (value)\n for (let attr in value) {\n if (attr == \"class\")\n attrs.class += \" \" + value[attr];\n else if (attr == \"style\")\n attrs.style = (attrs.style ? attrs.style + \";\" : \"\") + value[attr];\n else if (!attrs[attr] && attr != \"contenteditable\" && attr != \"nodeName\")\n attrs[attr] = String(value[attr]);\n }\n });\n if (!attrs.translate)\n attrs.translate = \"no\";\n return [Decoration.node(0, view.state.doc.content.size, attrs)];\n}\nfunction updateCursorWrapper(view) {\n if (view.markCursor) {\n let dom = document.createElement(\"img\");\n dom.className = \"ProseMirror-separator\";\n dom.setAttribute(\"mark-placeholder\", \"true\");\n dom.setAttribute(\"alt\", \"\");\n view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) };\n }\n else {\n view.cursorWrapper = null;\n }\n}\nfunction getEditable(view) {\n return !view.someProp(\"editable\", value => value(view.state) === false);\n}\nfunction selectionContextChanged(sel1, sel2) {\n let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));\n return sel1.$anchor.start(depth) != sel2.$anchor.start(depth);\n}\nfunction buildNodeViews(view) {\n let result = Object.create(null);\n function add(obj) {\n for (let prop in obj)\n if (!Object.prototype.hasOwnProperty.call(result, prop))\n result[prop] = obj[prop];\n }\n view.someProp(\"nodeViews\", add);\n view.someProp(\"markViews\", add);\n return result;\n}\nfunction changedNodeViews(a, b) {\n let nA = 0, nB = 0;\n for (let prop in a) {\n if (a[prop] != b[prop])\n return true;\n nA++;\n }\n for (let _ in b)\n nB++;\n return nA != nB;\n}\nfunction checkStateComponent(plugin) {\n if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction)\n throw new RangeError(\"Plugins passed directly to the view must not have a state component\");\n}\n\nexport { Decoration, DecorationSet, EditorView, __endComposition, __parseFromClipboard };\n", + "export const EqualityTraitSymbol = Symbol('Equality')\n\n/**\n * @typedef {{ [EqualityTraitSymbol]:(other:EqualityTrait)=>boolean }} EqualityTrait\n */\n\n/**\n *\n * Utility function to compare any two objects.\n *\n * Note that it is expected that the first parameter is more specific than the latter one.\n *\n * @example js\n * class X { [traits.EqualityTraitSymbol] (other) { return other === this } }\n * class X2 { [traits.EqualityTraitSymbol] (other) { return other === this }, x2 () { return 2 } }\n * // this is fine\n * traits.equals(new X2(), new X())\n * // this is not, because the left type is less specific than the right one\n * traits.equals(new X(), new X2())\n *\n * @template {EqualityTrait} T\n * @param {NoInfer} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equals = (a, b) => a === b || !!a?.[EqualityTraitSymbol]?.(b) || false\n", + "import * as equalityTrait from './trait/equality.js'\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 * @param {any} o\n * @return {o is { [k:string]:any }}\n */\nexport const isObject = o => typeof o === 'object'\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 * @template V\n * @param {{[key:string]: V}} obj\n * @return {Array}\n */\nexport const values = Object.values\n\n/**\n * @template V\n * @param {{[k:string]:V}} obj\n * @param {function(V,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 * @todo implement mapToArray & map\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 * @deprecated use object.size instead\n * @param {Object} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @return {number}\n */\nexport const size = obj => keys(obj).length\n\n/**\n * @template {{ [key:string|number|symbol]: any }} T\n * @param {T} obj\n * @param {(v:T[keyof T],k:keyof T)=>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|null|undefined} obj\n */\nexport const isEmpty = obj => {\n // eslint-disable-next-line no-unreachable-loop\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @template {{ [key:string|number|symbol]: any }} T\n * @param {T} obj\n * @param {(v:T[keyof T],k:keyof T)=>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|number|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 || (size(a) === size(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && equalityTrait.equals(b[key], val)))\n\n/**\n * Make an object immutable. This hurts performance and is usually not needed if you perform good\n * coding practices.\n */\nexport const freeze = Object.freeze\n\n/**\n * Make an object and all its children immutable.\n * This *really* hurts performance and is usually not needed if you perform good coding practices.\n *\n * @template {any} T\n * @param {T} o\n * @return {Readonly}\n */\nexport const deepFreeze = (o) => {\n for (const key in o) {\n const c = o[key]\n if (typeof c === 'object' || typeof c === 'function') {\n deepFreeze(o[key])\n }\n }\n return freeze(o)\n}\n\n/**\n * Get object property. Create T if property is undefined and set T on object.\n *\n * @function\n * @template {object} KV\n * @template {keyof KV} [K=keyof KV]\n * @param {KV} o\n * @param {K} key\n * @param {() => KV[K]} createT\n * @return {KV[K]}\n */\nexport const setIfUndefined = (o, key, createT) => hasProperty(o, key) ? o[key] : (o[key] = createT())\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'\nimport * as equalityTrait from './trait/equality.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 && ((array.isArray(a) && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/* c8 ignore start */\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a === b) {\n return true\n }\n if (a == null || b == null || (a.constructor !== b.constructor && (a.constructor || Object) !== (b.constructor || Object))) {\n return false\n }\n if (a[equalityTrait.EqualityTraitSymbol] != null) {\n return a[equalityTrait.EqualityTraitSymbol](b)\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 undefined:\n case Object:\n if (object.size(a) !== object.size(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/**\n * @template V\n * @template {V} OPTS\n *\n * @param {V} value\n * @param {Array} options\n */\n// @ts-ignore\nexport const isOneOf = (value, options) => options.includes(value)\n/* c8 ignore stop */\n\nexport const isArray = array.isArray\n\n/**\n * @param {any} s\n * @return {s is String}\n */\nexport const isString = (s) => s && s.constructor === String\n\n/**\n * @param {any} n\n * @return {n is Number}\n */\nexport const isNumber = n => n != null && n.constructor === Number\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {any} n\n * @param {TYPE} T\n * @return {n is InstanceType}\n */\nexport const is = (n, T) => n && n.constructor === T\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {TYPE} T\n */\nexport const isTemplate = (T) =>\n /**\n * @param {any} n\n * @return {n is InstanceType}\n **/\n n => n && n.constructor === T\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 * @template {string|Array} T\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 */\n\nconst highSurrogateRegex = /[\\uD800-\\uDBFF]/\nconst lowSurrogateRegex = /[\\uDC00-\\uDFFF]/\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 the last same character is a high surrogate, we need to rollback to the previous character\n if (left > 0 && highSurrogateRegex.test(a[left - 1])) left--\n while (right + left < a.length && right + left < b.length && a[a.length - right - 1] === b[b.length - right - 1]) {\n right++\n }\n // If the last same character is a low surrogate, we need to rollback to the previous character\n if (right > 0 && lowSurrogateRegex.test(a[a.length - right])) right--\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 while (right + left < a.length && right + left < b.length && compare(a[a.length - right - 1], b[b.length - right - 1])) {\n right++\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 * Diff text and try to diff at the current cursor position.\n *\n * @param {string} a\n * @param {string} b\n * @param {number} cursor This should refer to the current left cursor-range position\n */\nexport const simpleDiffStringWithCursor = (a, b, cursor) => {\n let left = 0 // number of same characters counting from left\n let right = 0 // number of same characters counting from right\n // Iterate left to the right until we find a changed character\n // First iteration considers the current cursor position\n while (\n left < a.length &&\n left < b.length &&\n a[left] === b[left] &&\n left < cursor\n ) {\n left++\n }\n // If the last same character is a high surrogate, we need to rollback to the previous character\n if (left > 0 && highSurrogateRegex.test(a[left - 1])) left--\n // Iterate right to the left until we find a changed character\n while (\n right + left < a.length &&\n right + left < b.length &&\n a[a.length - right - 1] === b[b.length - right - 1]\n ) {\n right++\n }\n // If the last same character is a low surrogate, we need to rollback to the previous character\n if (right > 0 && lowSurrogateRegex.test(a[a.length - right])) right--\n // Try to iterate left further to the right without caring about the current cursor position\n while (\n right + left < a.length &&\n right + left < b.length &&\n a[left] === b[left]\n ) {\n left++\n }\n if (left > 0 && highSurrogateRegex.test(a[left - 1])) left--\n return {\n index: left,\n remove: a.length - left - right,\n insert: b.slice(left, b.length - right)\n }\n}\n", + "import { Fragment, Node, Schema, Slice } from \"prosemirror-model\";\nimport { EditorState, Plugin, PluginKey, Selection, TextSelection } from \"prosemirror-state\";\nimport { Awareness, Cursor, EphemeralStore, LoroDoc, LoroList, LoroMap, LoroText, LoroTree, UndoManager, isContainer } from \"loro-crdt\";\nimport { Decoration, DecorationSet, EditorView } from \"prosemirror-view\";\nimport { simpleDiff } from \"lib0/diff\";\nimport { equalityDeep } from \"lib0/function\";\n\n//#region src/lib.ts\nconst ROOT_DOC_KEY = \"doc\";\nconst ATTRIBUTES_KEY = \"attributes\";\nconst CHILDREN_KEY = \"children\";\nconst NODE_NAME_KEY = \"nodeName\";\n/**\n* Maps PM non-text nodes to their corresponding Loro Container IDs.\n*/\nconst WEAK_NODE_TO_LORO_CONTAINER_MAPPING = /* @__PURE__ */ new WeakMap();\nfunction updateLoroToPmState(doc, mapping, editorState, containerId) {\n\tconst node = editorState.doc;\n\tconst map = containerId ? doc.getContainerById(containerId) : doc.getMap(ROOT_DOC_KEY);\n\tlet isInit = false;\n\tif (map.get(\"nodeName\") == null) {\n\t\tdoc.commit();\n\t\tisInit = true;\n\t\tmap.set(\"nodeName\", node.type.name);\n\t}\n\tupdateLoroMap(map, node, mapping);\n\tif (isInit) doc.commit({ origin: \"sys:init\" });\n\telse doc.commit({ origin: \"loroSyncPlugin\" });\n}\nfunction createNodeFromLoroObj(schema, obj, mapping) {\n\tlet retval = mapping.get(obj.id) ?? null;\n\tif (retval != null) return retval;\n\tif (obj instanceof LoroMap) {\n\t\tconst attributes = getLoroMapAttributes(obj);\n\t\tconst children = getLoroMapChildren(obj);\n\t\tconst nodeName = obj.get(\"nodeName\");\n\t\tif (nodeName == null || typeof nodeName !== \"string\") throw new Error(\"Invalid nodeName\");\n\t\tconst mappedChildren = children.toArray().flatMap((child) => createNodeFromLoroObj(schema, child, mapping)).filter((n) => n !== null);\n\t\ttry {\n\t\t\tretval = schema.node(nodeName, attributes.toJSON(), mappedChildren);\n\t\t\tWEAK_NODE_TO_LORO_CONTAINER_MAPPING.set(retval, obj.id);\n\t\t} catch (e) {\n\t\t\tconsole.error(e);\n\t\t}\n\t} else if (obj instanceof LoroText) {\n\t\tretval = [];\n\t\tfor (const delta of obj.toDelta()) {\n\t\t\tif (delta.insert == null) continue;\n\t\t\ttry {\n\t\t\t\tconst marks = [];\n\t\t\t\tfor (const [markName, mark] of Object.entries(delta.attributes ?? {})) {\n\t\t\t\t\tconst markAttrs = valueToAttrs(mark);\n\t\t\t\t\tmarks.push(schema.mark(markName, markAttrs ?? void 0));\n\t\t\t\t}\n\t\t\t\tretval.push(schema.text(delta.insert, marks));\n\t\t\t} catch (e) {\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t} else\n /* v8 ignore next */\n\tthrow new Error(\"Invalid LoroType\");\n\tif (retval != null) {\n\t\tif (!Array.isArray(retval)) WEAK_NODE_TO_LORO_CONTAINER_MAPPING.set(retval, obj.id);\n\t\tmapping.set(obj.id, retval);\n\t} else mapping.delete(obj.id);\n\treturn retval;\n}\nfunction createLoroChild(parentList, pos, nodeOrNodeList, mapping) {\n\treturn Array.isArray(nodeOrNodeList) ? createLoroText(parentList, pos, nodeOrNodeList, mapping) : createLoroMap(parentList, pos, nodeOrNodeList, mapping);\n}\nfunction createLoroText(parentList, pos, nodes, mapping) {\n\tconst obj = parentList.insertContainer(pos ?? parentList.length, new LoroText()).getAttached();\n\tconst delta = nodes.map((node) => ({\n\t\tinsert: node.text,\n\t\tattributes: nodeMarksToAttributes(node.marks)\n\t}));\n\tobj.applyDelta(delta);\n\tmapping.set(obj.id, nodes);\n\treturn obj;\n}\nfunction updateLoroText(obj, nodes, mapping) {\n\tmapping.set(obj.id, nodes);\n\tconst content = nodes.map((p) => ({\n\t\tinsert: p.text,\n\t\tattributes: nodeMarksToAttributes(p.marks)\n\t}));\n\tconst { insert, remove, index } = simpleDiff(obj.toString(), content.map((c) => c.insert).join(\"\"));\n\tif (remove > 0) obj.delete(index, remove);\n\tif (insert.length) obj.insert(index, insert);\n\tconst styles = diffTextStyles(obj.toDelta(), content);\n\tif (styles != null) obj.applyDelta(styles);\n}\n/**\n* Computes the minimal delta that restyles `current` (what the LoroText\n* holds) as `content` (what ProseMirror wants). The text of both sides must\n* already be equal. Returns null when the styles already agree everywhere.\n*/\nfunction diffTextStyles(current, content) {\n\tconst styles = [];\n\tlet i = 0;\n\tlet iUsed = 0;\n\tlet j = 0;\n\tlet jUsed = 0;\n\twhile (i < current.length && j < content.length) {\n\t\tconst currentRun = current[i];\n\t\tconst contentRun = content[j];\n\t\tif (currentRun.insert == null) {\n\t\t\ti += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tconst length = Math.min(currentRun.insert.length - iUsed, contentRun.insert.length - jUsed);\n\t\tif (length > 0) {\n\t\t\tconst patch = attributesPatch(currentRun.attributes ?? {}, contentRun.attributes);\n\t\t\tstyles.push(patch != null ? {\n\t\t\t\tretain: length,\n\t\t\t\tattributes: patch\n\t\t\t} : { retain: length });\n\t\t}\n\t\tiUsed += length;\n\t\tif (iUsed === currentRun.insert.length) {\n\t\t\ti += 1;\n\t\t\tiUsed = 0;\n\t\t}\n\t\tjUsed += length;\n\t\tif (jUsed === contentRun.insert.length) {\n\t\t\tj += 1;\n\t\t\tjUsed = 0;\n\t\t}\n\t}\n\twhile (styles.length > 0 && styles[styles.length - 1].attributes == null) styles.pop();\n\treturn styles.length > 0 ? styles : null;\n}\n/**\n* Computes the attribute changes that turn `current` into `wanted`, or null\n* if they are already equal.\n*/\nfunction attributesPatch(current, wanted) {\n\tlet patch = null;\n\tfor (const [key, attrs] of Object.entries(wanted)) if (!equalityDeep(current[key], attrs)) {\n\t\tpatch = patch ?? {};\n\t\tpatch[key] = attrs;\n\t}\n\tfor (const key of Object.keys(current)) if (!(key in wanted) && current[key] != null) {\n\t\tpatch = patch ?? {};\n\t\tpatch[key] = null;\n\t}\n\treturn patch;\n}\nfunction nodeMarksToAttributes(marks) {\n\tconst pattrs = {};\n\tfor (const mark of marks) pattrs[mark.type.name] = mark.attrs;\n\treturn pattrs;\n}\nfunction valueToAttrs(value) {\n\tif (value != null && typeof value === \"object\" && !Array.isArray(value) && !(value instanceof Uint8Array)) return value;\n\treturn null;\n}\nfunction eqLoroTextNodes(obj, nodes) {\n\tconst delta = obj.toDelta();\n\treturn delta.length === nodes.length && delta.every((delta, i) => delta.insert === nodes[i].text && Object.keys(delta.attributes || {}).length === nodes[i].marks.length && nodes[i].marks.every((mark) => {\n\t\tconst attrs = valueToAttrs((delta.attributes || {})[mark.type.name]);\n\t\treturn attrs != null && eqAttrs(attrs, mark.attrs);\n\t}));\n}\n/**\n* Whether the loro object is equal to the node.\n*/\nfunction eqLoroObjNode(obj, node) {\n\tif (obj instanceof LoroMap) {\n\t\tif (Array.isArray(node) || !eqNodeName(obj, node)) return false;\n\t\tconst loroChildren = getLoroMapChildren(obj);\n\t\tconst normalizedContent = normalizeNodeContent(node);\n\t\treturn loroChildren.length === normalizedContent.length && eqAttrs(getLoroMapAttributes(obj).toJSON(), node.attrs) && normalizedContent.every((childNode, i) => eqLoroObjNode(loroChildren.get(i), childNode));\n\t}\n\treturn obj instanceof LoroText && Array.isArray(node) && eqLoroTextNodes(obj, node);\n}\nfunction eqAttrs(attrs1, attrs2) {\n\tconst keys = Object.keys(attrs1).filter((key) => attrs1[key] !== null);\n\tlet eq = keys.length === Object.keys(attrs2).filter((key) => attrs2[key] !== null).length;\n\tfor (let i = 0; eq && i < keys.length; i++) {\n\t\tconst key = keys[i];\n\t\tconst l = attrs1[key];\n\t\tconst r = attrs2[key];\n\t\teq = l === r || typeof l === \"object\" && l !== null && typeof r === \"object\" && r !== null && eqAttrs(l, r);\n\t}\n\treturn eq;\n}\nfunction eqNodeName(obj, node) {\n\treturn !Array.isArray(node) && obj.get(\"nodeName\") === node.type.name;\n}\n/**\n* Checks if two nodes (or arrays of nodes) are equal.\n* - If both are the same object, returns true.\n* - If both are single nodes, uses their .eq() method.\n* - If both are arrays, checks that they have the same length and each corresponding node is equal.\n*/\nfunction eqMappedNode(mapped, node) {\n\tif (mapped === node) return true;\n\tif (!Array.isArray(mapped) && !Array.isArray(node) && node) return mapped?.eq(node) ?? false;\n\tif (Array.isArray(mapped) && Array.isArray(node)) {\n\t\tif (mapped.length !== node.length) return false;\n\t\tfor (let i = 0; i < mapped.length; i++) if (!node[i].eq(mapped[i])) return false;\n\t\treturn true;\n\t}\n\treturn false;\n}\nfunction normalizeNodeContent(node) {\n\tconst res = [];\n\tlet textNodes = null;\n\tnode.content.forEach((node, _offset, _i) => {\n\t\tif (node.isText) {\n\t\t\tif (textNodes == null) {\n\t\t\t\ttextNodes = [];\n\t\t\t\tres.push(textNodes);\n\t\t\t}\n\t\t\ttextNodes.push(node);\n\t\t} else {\n\t\t\tres.push(node);\n\t\t\ttextNodes = null;\n\t\t}\n\t});\n\treturn res;\n}\nfunction computeChildEqualityFactor(obj, node, mapping) {\n\tconst loroChildren = getLoroMapChildren(obj);\n\tconst loroChildLength = loroChildren.length;\n\tconst nodeChildren = normalizeNodeContent(node);\n\tconst nodeChildLength = nodeChildren.length;\n\tconst minLength = Math.min(loroChildLength, nodeChildLength);\n\tlet left = 0;\n\tlet right = 0;\n\tlet foundMappedChild = false;\n\tfor (; left < minLength; left++) {\n\t\tconst leftLoro = loroChildren.get(left);\n\t\tconst leftNode = nodeChildren[left];\n\t\tif (eqMappedNode(leftLoro != null && isContainer(leftLoro) ? mapping.get(leftLoro.id) : void 0, leftNode)) foundMappedChild = true;\n\t\telse if (leftLoro == null || leftNode == null || !eqLoroObjNode(leftLoro, leftNode)) break;\n\t}\n\tfor (; left + right < minLength; right++) {\n\t\tconst rightLoro = loroChildren.get(loroChildLength - right - 1);\n\t\tconst rightNode = nodeChildren[nodeChildLength - right - 1];\n\t\tif (eqMappedNode(rightLoro != null && isContainer(rightLoro) ? mapping.get(rightLoro.id) : void 0, rightNode)) foundMappedChild = true;\n\t\telse if (rightLoro == null || rightNode == null || !eqLoroObjNode(rightLoro, rightNode)) break;\n\t}\n\treturn {\n\t\tfactor: left + right,\n\t\tfoundMappedChild\n\t};\n}\nfunction createLoroMap(parentList, pos, node, mapping) {\n\tconst obj = parentList.insertContainer(pos ?? parentList.length, new LoroMap()).getAttached();\n\tobj.set(\"nodeName\", node.type.name);\n\tconst attrs = getLoroMapAttributes(obj);\n\tfor (const [key, value] of Object.entries(node.attrs)) if (value !== null) attrs.set(key, value);\n\tconst children = getLoroMapChildren(obj);\n\tnormalizeNodeContent(node).forEach((child, _i) => createLoroChild(children, null, child, mapping));\n\tWEAK_NODE_TO_LORO_CONTAINER_MAPPING.set(node, obj.id);\n\tmapping.set(obj.id, node);\n\treturn obj;\n}\nfunction updateLoroMap(obj, node, mapping) {\n\tmapping.set(obj.id, node);\n\tWEAK_NODE_TO_LORO_CONTAINER_MAPPING.set(node, obj.id);\n\tif (!eqNodeName(obj, node)) throw new Error(\"node name mismatch!\");\n\tupdateLoroMapAttributes(obj, node, mapping);\n\tupdateLoroMapChildren(obj, node, mapping);\n}\nfunction getLoroMapAttributes(obj) {\n\treturn obj.getOrCreateContainer(ATTRIBUTES_KEY, new LoroMap());\n}\nfunction updateLoroMapAttributes(obj, node, _mapping) {\n\tconst attrs = getLoroMapAttributes(obj);\n\tconst keys = new Set(attrs.keys());\n\tconst pAttrs = node.attrs;\n\tfor (const [key, value] of Object.entries(pAttrs)) {\n\t\tif (value !== null) {\n\t\t\tif (!equalityDeep(attrs.get(key), value)) attrs.set(key, value);\n\t\t} else attrs.delete(key);\n\t\tkeys.delete(key);\n\t}\n\tfor (const key of keys) attrs.delete(key);\n}\nfunction getLoroMapChildren(obj) {\n\treturn obj.getOrCreateContainer(CHILDREN_KEY, new LoroList());\n}\nfunction updateLoroMapChildren(obj, node, mapping) {\n\tconst loroChildren = getLoroMapChildren(obj);\n\tconst loroChildLength = loroChildren.length;\n\tconst nodeChildren = normalizeNodeContent(node);\n\tconst nodeChildLength = nodeChildren.length;\n\tconst minLength = Math.min(nodeChildLength, loroChildLength);\n\tlet left = 0;\n\tlet right = 0;\n\tfor (; left < minLength; left++) {\n\t\tconst leftLoro = loroChildren.get(left);\n\t\tconst leftNode = nodeChildren[left];\n\t\tif (leftLoro == null || leftNode == null) break;\n\t\tif (isContainer(leftLoro) && mapping.get(leftLoro.id) !== leftNode) if (eqMappedNode(mapping.get(leftLoro.id), leftNode) || eqLoroObjNode(leftLoro, leftNode)) {\n\t\t\tif (!Array.isArray(leftNode)) updateLoroMap(leftLoro, leftNode, mapping);\n\t\t} else break;\n\t}\n\tfor (; right + left < minLength; right++) {\n\t\tconst rightLoro = loroChildren.get(loroChildLength - right - 1);\n\t\tconst rightNode = nodeChildren[nodeChildLength - right - 1];\n\t\tif (rightLoro == null || rightNode == null) break;\n\t\tif (isContainer(rightLoro) && mapping.get(rightLoro.id) !== rightNode) if (eqMappedNode(mapping.get(rightLoro.id), rightNode) || eqLoroObjNode(rightLoro, rightNode)) {\n\t\t\tif (!Array.isArray(rightNode)) updateLoroMap(rightLoro, rightNode, mapping);\n\t\t} else break;\n\t}\n\twhile (loroChildLength - left - right > 0 && nodeChildLength - left - right > 0) {\n\t\tconst leftLoro = loroChildren.get(left);\n\t\tconst leftNode = nodeChildren[left];\n\t\tconst rightLoro = loroChildren.get(loroChildLength - right - 1);\n\t\tconst rightNode = nodeChildren[nodeChildLength - right - 1];\n\t\tif (leftLoro instanceof LoroText && Array.isArray(leftNode)) {\n\t\t\tif (!eqLoroTextNodes(leftLoro, leftNode)) updateLoroText(leftLoro, leftNode, mapping);\n\t\t\tleft += 1;\n\t\t} else {\n\t\t\tlet updateLeft = leftLoro instanceof LoroMap && eqNodeName(leftLoro, leftNode);\n\t\t\tlet updateRight = rightLoro instanceof LoroMap && eqNodeName(rightLoro, rightNode);\n\t\t\tif (updateLeft && updateRight) {\n\t\t\t\tconst leftEquality = computeChildEqualityFactor(leftLoro, leftNode, mapping);\n\t\t\t\tconst rightEquality = computeChildEqualityFactor(rightLoro, rightNode, mapping);\n\t\t\t\tif (leftEquality.foundMappedChild && !rightEquality.foundMappedChild) updateRight = false;\n\t\t\t\telse if (rightEquality.foundMappedChild && !leftEquality.foundMappedChild) updateLeft = false;\n\t\t\t\telse if (leftEquality.factor < rightEquality.factor) updateLeft = false;\n\t\t\t\telse updateRight = false;\n\t\t\t}\n\t\t\tif (updateLeft) {\n\t\t\t\tupdateLoroMap(leftLoro, leftNode, mapping);\n\t\t\t\tleft += 1;\n\t\t\t} else if (updateRight) {\n\t\t\t\tupdateLoroMap(rightLoro, rightNode, mapping);\n\t\t\t\tright += 1;\n\t\t\t} else {\n\t\t\t\tconst child = loroChildren.get(left);\n\t\t\t\tif (isContainer(child)) mapping.delete(child.id);\n\t\t\t\tloroChildren.delete(left, 1);\n\t\t\t\tcreateLoroChild(loroChildren, left, leftNode, mapping);\n\t\t\t\tleft += 1;\n\t\t\t}\n\t\t}\n\t}\n\tconst loroDelLength = loroChildLength - left - right;\n\tif (loroChildLength === 1 && nodeChildLength === 0 && loroChildren.get(0) instanceof LoroText) {\n\t\tconst loroText = loroChildren.get(0);\n\t\tmapping.delete(loroText.id);\n\t\tloroText.delete(0, loroText.length);\n\t} else if (loroDelLength > 0) {\n\t\tloroChildren.toArray().slice(left, left + loroDelLength).filter(isContainer).forEach((type) => mapping.delete(type.id));\n\t\tloroChildren.delete(left, loroDelLength);\n\t}\n\tif (left + right < nodeChildLength) nodeChildren.slice(left, nodeChildLength - right).forEach((nodeChild, i) => createLoroChild(loroChildren, left + i, nodeChild, mapping));\n}\nfunction clearChangedNodes(doc, event, mapping) {\n\tfor (const e of event.events) {\n\t\tconst obj = doc.getContainerById(e.target);\n\t\tmapping.delete(obj.id);\n\t\tlet parentObj = obj.parent();\n\t\twhile (parentObj) {\n\t\t\tmapping.delete(parentObj.id);\n\t\t\tparentObj = parentObj.parent();\n\t\t}\n\t}\n}\n/**\n* Set a text selection between the given anchor and head positions. This\n* function will ignore out-of-bounds positions, and find a valid selection near\n* the given positions.\n*/\nfunction safeSetSelection(view, anchor, head) {\n\tconst doc = view.state.doc;\n\tconst docSize = doc.content.size;\n\tif (anchor < 0 || anchor > docSize || head != null && (head < 0 || head > docSize)) return;\n\tconst $anchor = doc.resolve(anchor);\n\tconst $head = head != null ? doc.resolve(head) : void 0;\n\tconst selection = TextSelection.between($anchor, $head || $anchor);\n\tview.dispatch(view.state.tr.setSelection(selection));\n}\n\n//#endregion\n//#region src/sync-plugin-key.ts\nconst loroSyncPluginKey = new PluginKey(\"loro-sync\");\n\n//#endregion\n//#region src/cursor/common.ts\nconst createCursorPlugin = (pluginKey, store, options) => {\n\tconst getSelection = options.getSelection || ((state) => state.selection);\n\tconst createSelection = options.createSelection || ((user) => ({\n\t\tclass: \"loro-selection\",\n\t\t\"data-peer\": user,\n\t\tstyle: `background-color: rgba(228, 208, 102, 0.5)`\n\t}));\n\tconst createCursor = options.createCursor || ((user) => {\n\t\tconst cursorUserData = store.getAll()[user];\n\t\tconst cursor = document.createElement(\"span\");\n\t\tcursor.classList.add(\"ProseMirror-loro-cursor\");\n\t\tcursor.setAttribute(\"style\", `border-color: ${cursorUserData?.user?.color ?? user.slice(0, 6)}`);\n\t\tconst userDiv = document.createElement(\"div\");\n\t\tuserDiv.setAttribute(\"style\", `background-color: ${cursorUserData?.user?.color ?? user.slice(0, 6)}`);\n\t\tuserDiv.insertBefore(document.createTextNode(cursorUserData?.user?.name ?? user.slice(0, 6)), null);\n\t\tconst nonbreakingSpace1 = document.createTextNode(\"⁠\");\n\t\tconst nonbreakingSpace2 = document.createTextNode(\"⁠\");\n\t\tcursor.insertBefore(nonbreakingSpace1, null);\n\t\tcursor.insertBefore(userDiv, null);\n\t\tcursor.insertBefore(nonbreakingSpace2, null);\n\t\treturn cursor;\n\t});\n\tconst plugin = new Plugin({\n\t\tkey: pluginKey,\n\t\tstate: {\n\t\t\tinit(_, state) {\n\t\t\t\treturn createDecorations(state, store, plugin, createSelection, createCursor);\n\t\t\t},\n\t\t\tapply(tr, prevState, _oldState, newState) {\n\t\t\t\tconst loroState = loroSyncPluginKey.getState(newState);\n\t\t\t\tconst loroCursorState = tr.getMeta(pluginKey);\n\t\t\t\tif (loroState && loroState.changedBy !== \"local\" || loroCursorState && loroCursorState.presenceUpdated) return createDecorations(newState, store, plugin, createSelection, createCursor);\n\t\t\t\treturn prevState.map(tr.mapping, tr.doc);\n\t\t\t}\n\t\t},\n\t\tprops: { decorations: (state) => {\n\t\t\treturn plugin.getState(state);\n\t\t} },\n\t\tview: (view) => {\n\t\t\tconst storeListener = (origin) => {\n\t\t\t\tif (origin !== \"local\") setTimeout(() => {\n\t\t\t\t\tif (view.isDestroyed) return;\n\t\t\t\t\tlet tr = view.state.tr;\n\t\t\t\t\ttr.setMeta(pluginKey, { presenceUpdated: true });\n\t\t\t\t\tview.dispatch(tr);\n\t\t\t\t}, 0);\n\t\t\t};\n\t\t\tconst updateCursorInfo = () => {\n\t\t\t\tconst loroState = loroSyncPluginKey.getState(view.state);\n\t\t\t\tconst current = store.getLocal();\n\t\t\t\tif (loroState?.doc == null) return;\n\t\t\t\tconst pmRootNode = view.state.doc;\n\t\t\t\tif (view.hasFocus()) {\n\t\t\t\t\tconst { anchor, focus } = convertPmSelectionToCursors(pmRootNode, getSelection(view.state), loroState);\n\t\t\t\t\tif (current == null || !cursorEq(current.anchor, anchor) || !cursorEq(current.focus, focus)) store.setLocal({\n\t\t\t\t\t\tuser: options.user,\n\t\t\t\t\t\tanchor,\n\t\t\t\t\t\tfocus\n\t\t\t\t\t});\n\t\t\t\t} else if (current?.focus != null) store.setLocal({});\n\t\t\t};\n\t\t\tconst unsubscribe = store.subscribe(storeListener);\n\t\t\tview.dom.addEventListener(\"focusin\", updateCursorInfo);\n\t\t\tview.dom.addEventListener(\"focusout\", updateCursorInfo);\n\t\t\treturn {\n\t\t\t\tupdate: updateCursorInfo,\n\t\t\t\tdestroy: () => {\n\t\t\t\t\tview.dom.removeEventListener(\"focusin\", updateCursorInfo);\n\t\t\t\t\tview.dom.removeEventListener(\"focusout\", updateCursorInfo);\n\t\t\t\t\tunsubscribe();\n\t\t\t\t\tstore.setLocal({});\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t});\n\treturn plugin;\n};\nfunction createDecorations(state, store, _plugin, createSelection, createCursor) {\n\tconst all = store.getAll();\n\tconst d = [];\n\tconst loroState = loroSyncPluginKey.getState(state);\n\tif (!loroState) return DecorationSet.create(state.doc, []);\n\tconst doc = loroState.doc;\n\tconst thisPeer = doc.peerIdStr;\n\tfor (const [peer, cursor] of Object.entries(all)) {\n\t\tif (peer === thisPeer) continue;\n\t\tif (!cursor.anchor || !cursor.focus) continue;\n\t\tconst [focus, focusCursorUpdate] = cursorToAbsolutePosition(cursor.focus, doc, loroState.mapping);\n\t\td.push(Decoration.widget(focus, createCursor(peer)));\n\t\tif (!cursorEq(cursor.anchor, cursor.focus)) {\n\t\t\tconst [anchor, anchorCursorUpdate] = cursorToAbsolutePosition(cursor.anchor, doc, loroState.mapping);\n\t\t\td.push(Decoration.inline(Math.min(anchor, focus), Math.max(anchor, focus), createSelection(peer)));\n\t\t\tif (focusCursorUpdate || anchorCursorUpdate) {\n\t\t\t\tconst existingLocalState = store.getLocal();\n\t\t\t\tstore.setLocal({\n\t\t\t\t\t...existingLocalState?.user && { user: existingLocalState.user },\n\t\t\t\t\tanchor: anchorCursorUpdate || cursor.anchor,\n\t\t\t\t\tfocus: focusCursorUpdate || cursor.focus\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (focusCursorUpdate) {\n\t\t\tconst existingLocalState = store.getLocal();\n\t\t\tstore.setLocal({\n\t\t\t\t...existingLocalState?.user && { user: existingLocalState.user },\n\t\t\t\tfocus: focusCursorUpdate,\n\t\t\t\tanchor: focusCursorUpdate\n\t\t\t});\n\t\t}\n\t}\n\treturn DecorationSet.create(state.doc, d);\n}\nfunction convertPmSelectionToCursors(pmRootNode, selection, loroState) {\n\tconst anchor = absolutePositionToCursor(pmRootNode, selection.anchor, loroState.doc, loroState.mapping);\n\treturn {\n\t\tanchor,\n\t\tfocus: selection.head == selection.anchor ? anchor : absolutePositionToCursor(pmRootNode, selection.head, loroState.doc, loroState.mapping)\n\t};\n}\nfunction getByValue(map, searchValue) {\n\tfor (let [key, value] of map.entries()) if (value === searchValue) return key;\n}\nfunction absolutePositionToCursor(pmRootNode, anchor, doc, mapping) {\n\tconst pos = pmRootNode.resolve(anchor);\n\tconst nodeParent = pos.node(pos.depth);\n\tconst offset = pos.parentOffset;\n\tconst loroId = WEAK_NODE_TO_LORO_CONTAINER_MAPPING.get(nodeParent) ?? getByValue(mapping, nodeParent);\n\tif (!loroId) {\n\t\tif (anchor > 1) console.error(\"Cannot find the loroNode\");\n\t\treturn;\n\t}\n\tconst children = doc.getMap(loroId).get(CHILDREN_KEY);\n\tif (children.length == 0) return children.getCursor(0);\n\tlet index = offset;\n\tlet childIndex = 0;\n\twhile (index >= 0 && childIndex < children.length) {\n\t\tconst child = children.get(childIndex);\n\t\tchildIndex += 1;\n\t\tif (child instanceof LoroText) return child.getCursor(index);\n\t\telse {\n\t\t\tif (index == 0) {\n\t\t\t\tif (childIndex < children.length) index += 1;\n\t\t\t}\n\t\t\tindex -= 1;\n\t\t}\n\t}\n}\nfunction cursorToAbsolutePosition(cursor, doc, mapping) {\n\tconst containerId = cursor.containerId();\n\tlet index = -1;\n\tlet targetChildId;\n\tlet loroNode;\n\tlet update;\n\tif (containerId.endsWith(\"List\")) {\n\t\tconst loroList = doc.getContainerById(containerId);\n\t\tif (!loroList) return [1, void 0];\n\t\tconst parentNode = loroList.parent();\n\t\tif (!parentNode) return [1, void 0];\n\t\ttargetChildId = parentNode.id;\n\t\tloroNode = parentNode.parent()?.parent();\n\t\tindex = 0;\n\t} else {\n\t\tconst loroText = doc.getText(containerId);\n\t\tconst pos = doc.getCursorPos(cursor);\n\t\tif (!pos) return [1, void 0];\n\t\tupdate = pos.update;\n\t\tindex += pos.offset;\n\t\ttargetChildId = loroText.id;\n\t\tloroNode = loroText.parent()?.parent();\n\t}\n\twhile (loroNode != null) {\n\t\tconst children = loroNode.get(CHILDREN_KEY);\n\t\tif (children instanceof LoroList) {\n\t\t\tconst childIds = children.toArray();\n\t\t\tfor (const iter of childIds) {\n\t\t\t\tif (iter.id === targetChildId) break;\n\t\t\t\tconst mapped = mapping.get(iter.id);\n\t\t\t\tif (Array.isArray(mapped)) mapped.forEach((child) => {\n\t\t\t\t\tindex += child.nodeSize;\n\t\t\t\t});\n\t\t\t\telse if (mapped != null) index += mapped.nodeSize;\n\t\t\t\telse console.error(childIds, children.toJSON());\n\t\t\t}\n\t\t\ttargetChildId = loroNode.id;\n\t\t\tloroNode = loroNode.parent()?.parent();\n\t\t\tindex += 1;\n\t\t} else throw new Error(\"Unreachable code\");\n\t}\n\treturn [index, update];\n}\nfunction cursorEq(a, b) {\n\tif (!a && !b) return true;\n\tif (!a || !b) return false;\n\tconst aPos = a.pos();\n\tconst bPos = b.pos();\n\treturn aPos?.peer === bPos?.peer && aPos?.counter === bPos?.counter && a.containerId() === b.containerId();\n}\n\n//#endregion\n//#region src/text-style.ts\nconst LORO_TEXT_STYLE_CACHE = /* @__PURE__ */ new WeakSet();\nfunction getLoroTextStyle(schema) {\n\treturn Object.fromEntries(Object.entries(schema.marks).map(([markName, markType]) => [markName, { expand: markType.spec.inclusive !== false ? \"after\" : \"none\" }]));\n}\nfunction configLoroTextStyle(doc, schema) {\n\tif (LORO_TEXT_STYLE_CACHE.has(doc)) return;\n\tLORO_TEXT_STYLE_CACHE.add(doc);\n\tdoc.configTextStyle(getLoroTextStyle(schema));\n}\n\n//#endregion\n//#region src/undo-plugin-key.ts\nconst loroUndoPluginKey = new PluginKey(\"loro-undo\");\n\n//#endregion\n//#region src/sync-plugin.ts\nconst LoroSyncPlugin = (props) => {\n\treturn new Plugin({\n\t\tkey: loroSyncPluginKey,\n\t\tprops: { editable: (state) => {\n\t\t\treturn loroSyncPluginKey.getState(state)?.snapshot == null;\n\t\t} },\n\t\tstate: {\n\t\t\tinit: (_config, editorState) => {\n\t\t\t\tconfigLoroTextStyle(props.doc, editorState.schema);\n\t\t\t\treturn {\n\t\t\t\t\tdoc: props.doc,\n\t\t\t\t\tmapping: props.mapping ?? /* @__PURE__ */ new Map(),\n\t\t\t\t\tchangedBy: \"local\",\n\t\t\t\t\tcontainerId: props.containerId\n\t\t\t\t};\n\t\t\t},\n\t\t\tapply: (tr, state, oldEditorState, newEditorState) => {\n\t\t\t\tconst meta = tr.getMeta(loroSyncPluginKey);\n\t\t\t\tconst undoState = loroUndoPluginKey.getState(oldEditorState);\n\t\t\t\tif (meta?.type === \"non-local-updates\") state.changedBy = \"import\";\n\t\t\t\telse state.changedBy = \"local\";\n\t\t\t\tswitch (meta?.type) {\n\t\t\t\t\tcase \"doc-changed\":\n\t\t\t\t\t\tif (!undoState?.isUndoing.current) updateLoroToPmState(state.doc, state.mapping, newEditorState, props.containerId);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"update-state\":\n\t\t\t\t\t\tstate = {\n\t\t\t\t\t\t\t...state,\n\t\t\t\t\t\t\t...meta.state\n\t\t\t\t\t\t};\n\t\t\t\t\t\tstate.doc.commit({\n\t\t\t\t\t\t\torigin: \"sys:init\",\n\t\t\t\t\t\t\ttimestamp: Date.now()\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault: break;\n\t\t\t\t}\n\t\t\t\treturn state;\n\t\t\t}\n\t\t},\n\t\tappendTransaction: (transactions, _oldEditorState, newEditorState) => {\n\t\t\tif (transactions.some((tr) => tr.docChanged)) return newEditorState.tr.setMeta(loroSyncPluginKey, { type: \"doc-changed\" });\n\t\t\treturn null;\n\t\t},\n\t\tview: (view) => {\n\t\t\tconst timeoutId = setTimeout(() => init(view), 0);\n\t\t\treturn {\n\t\t\t\tupdate: (_view, _prevState) => {},\n\t\t\t\tdestroy: () => {\n\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t});\n};\nfunction init(view) {\n\tif (view.isDestroyed) return;\n\tconst state = loroSyncPluginKey.getState(view.state);\n\tlet docSubscription = state.docSubscription;\n\tdocSubscription?.();\n\tif (state.containerId) docSubscription = state.doc.getContainerById(state.containerId).subscribe((event) => {\n\t\tupdateNodeOnLoroEvent(view, event);\n\t});\n\telse docSubscription = state.doc.subscribe((event) => updateNodeOnLoroEvent(view, event));\n\tconst innerDoc = state.containerId ? state.doc.getContainerById(state.containerId) : state.doc.getMap(ROOT_DOC_KEY);\n\tconst mapping = /* @__PURE__ */ new Map();\n\tif (innerDoc.size === 0) {\n\t\tconst tr = view.state.tr.delete(0, view.state.doc.content.size);\n\t\ttr.setMeta(loroSyncPluginKey, {\n\t\t\ttype: \"update-state\",\n\t\t\tstate: {\n\t\t\t\tmapping,\n\t\t\t\tdocSubscription,\n\t\t\t\tsnapshot: null\n\t\t\t}\n\t\t});\n\t\tview.dispatch(tr);\n\t} else {\n\t\tconst schema = view.state.schema;\n\t\tconst node = createNodeFromLoroObj(schema, innerDoc, mapping);\n\t\tconst tr = view.state.tr.replace(0, view.state.doc.content.size, new Slice(Fragment.from(node), 0, 0));\n\t\ttr.setMeta(loroSyncPluginKey, {\n\t\t\ttype: \"update-state\",\n\t\t\tstate: {\n\t\t\t\tmapping,\n\t\t\t\tdocSubscription,\n\t\t\t\tsnapshot: null\n\t\t\t}\n\t\t});\n\t\tview.dispatch(tr);\n\t}\n}\nfunction updateNodeOnLoroEvent(view, event) {\n\tif (view.isDestroyed) return;\n\tconst state = loroSyncPluginKey.getState(view.state);\n\tstate.changedBy = event.by;\n\tif (event.by === \"local\" && event.origin !== \"undo\") return;\n\tconst mapping = state.mapping;\n\tclearChangedNodes(state.doc, event, mapping);\n\tconst node = createNodeFromLoroObj(view.state.schema, state.containerId ? state.doc.getContainerById(state.containerId) : state.doc.getMap(ROOT_DOC_KEY), mapping);\n\tconst { anchor, focus } = convertPmSelectionToCursors(view.state.doc, view.state.selection, state);\n\tlet tr = view.state.tr.replace(0, view.state.doc.content.size, new Slice(Fragment.from(node), 0, 0));\n\ttr.setMeta(loroSyncPluginKey, { type: \"non-local-updates\" });\n\tview.dispatch(tr);\n\tif (anchor == null) return;\n\tsetTimeout(() => {\n\t\tsyncCursorsToPmSelection(view, anchor, focus);\n\t});\n}\n/**\n* Update ProseMirror selection based on the given Loro cursors.\n*/\nfunction syncCursorsToPmSelection(view, anchor, focus) {\n\tif (view.isDestroyed) return;\n\tconst state = loroSyncPluginKey.getState(view.state);\n\tif (!state) return;\n\tconst { doc, mapping } = state;\n\tconst anchorPos = cursorToAbsolutePosition(anchor, doc, mapping)[0];\n\tconst focusPos = focus && cursorToAbsolutePosition(focus, doc, mapping)[0];\n\tif (anchorPos == null) return;\n\tsafeSetSelection(view, anchorPos, focusPos);\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.112.0/helpers/typeof.js\nfunction _typeof(o) {\n\t\"@babel/helpers - typeof\";\n\treturn _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function(o) {\n\t\treturn typeof o;\n\t} : function(o) {\n\t\treturn o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n\t}, _typeof(o);\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.112.0/helpers/toPrimitive.js\nfunction toPrimitive(t, r) {\n\tif (\"object\" != _typeof(t) || !t) return t;\n\tvar e = t[Symbol.toPrimitive];\n\tif (void 0 !== e) {\n\t\tvar i = e.call(t, r || \"default\");\n\t\tif (\"object\" != _typeof(i)) return i;\n\t\tthrow new TypeError(\"@@toPrimitive must return a primitive value.\");\n\t}\n\treturn (\"string\" === r ? String : Number)(t);\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.112.0/helpers/toPropertyKey.js\nfunction toPropertyKey(t) {\n\tvar i = toPrimitive(t, \"string\");\n\treturn \"symbol\" == _typeof(i) ? i : i + \"\";\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.112.0/helpers/defineProperty.js\nfunction _defineProperty(e, r, t) {\n\treturn (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n\t\tvalue: t,\n\t\tenumerable: !0,\n\t\tconfigurable: !0,\n\t\twritable: !0\n\t}) : e[r] = t, e;\n}\n\n//#endregion\n//#region src/cursor/ephemeral.ts\nvar CursorEphemeralStore = class extends EphemeralStore {\n\tconstructor(peer, timeout) {\n\t\tsuper(timeout);\n\t\t_defineProperty(this, \"peer\", void 0);\n\t\tthis.peer = peer;\n\t}\n\tsetLocal(state) {\n\t\tif (!state.anchor && !state.focus && !state.user) {\n\t\t\tthis.delete(this.peer);\n\t\t\treturn;\n\t\t}\n\t\tthis.set(this.peer, {\n\t\t\tanchor: state.anchor?.encode() ?? null,\n\t\t\tfocus: state.focus?.encode() ?? null,\n\t\t\tuser: state.user ?? null\n\t\t});\n\t}\n\tgetLocal() {\n\t\tconst state = this.get(this.peer);\n\t\tif (!state) return;\n\t\treturn {\n\t\t\tanchor: state.anchor ? Cursor.decode(state.anchor) : void 0,\n\t\t\tfocus: state.focus ? Cursor.decode(state.focus) : void 0,\n\t\t\tuser: state.user ?? void 0\n\t\t};\n\t}\n\tgetAll() {\n\t\tconst ans = {};\n\t\tfor (const [peer, state] of Object.entries(this.getAllStates())) {\n\t\t\tif (!state) continue;\n\t\t\tans[peer] = {\n\t\t\t\tanchor: state.anchor ? Cursor.decode(state.anchor) : void 0,\n\t\t\t\tfocus: state.focus ? Cursor.decode(state.focus) : void 0,\n\t\t\t\tuser: state.user ?? void 0\n\t\t\t};\n\t\t}\n\t\treturn ans;\n\t}\n\tsubscribeBy(listener) {\n\t\treturn super.subscribe((event) => listener(event.by));\n\t}\n};\nconst loroEphemeralCursorPluginKey = new PluginKey(\"loro-ephemeral-cursor\");\nconst LoroEphemeralCursorPlugin = (store, options) => createCursorPlugin(loroEphemeralCursorPluginKey, ephemeralStoreAdapter(store), options);\nconst ephemeralStoreAdapter = (store) => ({\n\tgetAll: () => store.getAll(),\n\tgetLocal: () => store.getLocal(),\n\tsetLocal: (state) => store.setLocal(state),\n\tsubscribe: (listener) => store.subscribeBy(listener)\n});\n\n//#endregion\n//#region src/cursor/awareness.ts\nvar CursorAwareness = class extends Awareness {\n\tconstructor(peer, timeout = 3e4) {\n\t\tsuper(peer, timeout);\n\t}\n\tgetAll() {\n\t\tconst ans = {};\n\t\tfor (const [peer, state] of Object.entries(this.getAllStates())) ans[peer] = {\n\t\t\tanchor: state.anchor ? Cursor.decode(state.anchor) : void 0,\n\t\t\tfocus: state.focus ? Cursor.decode(state.focus) : void 0,\n\t\t\tuser: state.user ? state.user : void 0\n\t\t};\n\t\treturn ans;\n\t}\n\tsetLocal(state) {\n\t\tthis.setLocalState({\n\t\t\tanchor: state.anchor?.encode() || null,\n\t\t\tfocus: state.focus?.encode() || null,\n\t\t\tuser: state.user || null\n\t\t});\n\t}\n\tgetLocal() {\n\t\tconst state = this.getLocalState();\n\t\tif (!state) return;\n\t\treturn {\n\t\t\tanchor: state.anchor && Cursor.decode(state.anchor),\n\t\t\tfocus: state.focus && Cursor.decode(state.focus),\n\t\t\tuser: state.user\n\t\t};\n\t}\n};\nconst loroCursorPluginKey = new PluginKey(\"loro-cursor\");\nconst awarenessAdapter = (awareness) => ({\n\tgetAll: () => awareness.getAll(),\n\tgetLocal: () => {\n\t\tconst state = awareness.getLocal();\n\t\tif (!state) return;\n\t\treturn {\n\t\t\tanchor: state.anchor ?? void 0,\n\t\t\tfocus: state.focus ?? void 0,\n\t\t\tuser: state.user ?? void 0\n\t\t};\n\t},\n\tsetLocal: (state) => awareness.setLocal(state),\n\tsubscribe: (listener) => {\n\t\tconst awarenessListener = (_, origin) => listener(origin === \"local\" ? \"local\" : \"import\");\n\t\tawareness.addListener(awarenessListener);\n\t\treturn () => awareness.removeListener(awarenessListener);\n\t}\n});\nconst LoroCursorPlugin = (awareness, options) => createCursorPlugin(loroCursorPluginKey, awarenessAdapter(awareness), options);\n\n//#endregion\n//#region src/undo-plugin.ts\nconst LoroUndoPlugin = (props) => {\n\tconst undoManager = props.undoManager || new UndoManager(props.doc, {});\n\tlet lastSelection = {\n\t\tanchor: null,\n\t\tfocus: null\n\t};\n\treturn new Plugin({\n\t\tkey: loroUndoPluginKey,\n\t\tstate: {\n\t\t\tinit: (_config, editorState) => {\n\t\t\t\tconfigLoroTextStyle(props.doc, editorState.schema);\n\t\t\t\tundoManager.addExcludeOriginPrefix(\"sys:init\");\n\t\t\t\treturn {\n\t\t\t\t\tundoManager,\n\t\t\t\t\tcanUndo: undoManager.canUndo(),\n\t\t\t\t\tcanRedo: undoManager.canRedo(),\n\t\t\t\t\tisUndoing: { current: false }\n\t\t\t\t};\n\t\t\t},\n\t\t\tapply: (_tr, state, oldEditorState, _newEditorState) => {\n\t\t\t\tconst undoState = loroUndoPluginKey.getState(oldEditorState);\n\t\t\t\tconst loroState = loroSyncPluginKey.getState(oldEditorState);\n\t\t\t\tif (!undoState || !loroState) return state;\n\t\t\t\tconst canUndo = undoState.undoManager.canUndo();\n\t\t\t\tconst canRedo = undoState.undoManager.canRedo();\n\t\t\t\t{\n\t\t\t\t\tconst { anchor, focus } = convertPmSelectionToCursors(oldEditorState.doc, oldEditorState.selection, loroState);\n\t\t\t\t\tlastSelection = {\n\t\t\t\t\t\tanchor: anchor ?? null,\n\t\t\t\t\t\tfocus: focus ?? null\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\t...state,\n\t\t\t\t\tcanUndo,\n\t\t\t\t\tcanRedo\n\t\t\t\t};\n\t\t\t}\n\t\t},\n\t\tview: (view) => {\n\t\t\tundoManager.setOnPush((isUndo, _counterRange) => {\n\t\t\t\tif (loroSyncPluginKey.getState(view.state)?.doc == null) return {\n\t\t\t\t\tvalue: null,\n\t\t\t\t\tcursors: []\n\t\t\t\t};\n\t\t\t\tconst cursors = [];\n\t\t\t\tlet selection = lastSelection;\n\t\t\t\tif (!isUndo) {\n\t\t\t\t\tconst loroState = loroSyncPluginKey.getState(view.state);\n\t\t\t\t\tif (loroState) {\n\t\t\t\t\t\tconst { anchor, focus } = convertPmSelectionToCursors(view.state.doc, view.state.selection, loroState);\n\t\t\t\t\t\tselection.anchor = anchor || null;\n\t\t\t\t\t\tselection.focus = focus || null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (selection.anchor) cursors.push(selection.anchor);\n\t\t\t\tif (selection.focus) cursors.push(selection.focus);\n\t\t\t\treturn {\n\t\t\t\t\tvalue: null,\n\t\t\t\t\tcursors\n\t\t\t\t};\n\t\t\t});\n\t\t\tundoManager.setOnPop((_isUndo, meta, _counterRange) => {\n\t\t\t\tif (loroSyncPluginKey.getState(view.state)?.doc == null) return;\n\t\t\t\tconst anchor = meta.cursors[0];\n\t\t\t\tconst focus = meta.cursors[1];\n\t\t\t\tif (anchor == null) return;\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tsyncCursorsToPmSelection(view, anchor, focus);\n\t\t\t\t}, 0);\n\t\t\t});\n\t\t\treturn { destroy: () => {\n\t\t\t\tundoManager.setOnPop();\n\t\t\t\tundoManager.setOnPush();\n\t\t\t} };\n\t\t}\n\t});\n};\nfunction canUndo(state) {\n\treturn loroUndoPluginKey.getState(state)?.undoManager.canUndo() || false;\n}\nfunction canRedo(state) {\n\treturn loroUndoPluginKey.getState(state)?.undoManager.canRedo() || false;\n}\nconst undo = (state, dispatch) => {\n\tconst undoState = loroUndoPluginKey.getState(state);\n\tif (!undoState) return false;\n\tif (!dispatch) return undoState.undoManager.canUndo();\n\tundoState.isUndoing.current = true;\n\tsetTimeout(() => {\n\t\tundoState.isUndoing.current = false;\n\t}, 0);\n\treturn undoState.undoManager.undo();\n};\nconst redo = (state, dispatch) => {\n\tconst undoState = loroUndoPluginKey.getState(state);\n\tif (!undoState) return false;\n\tif (!dispatch) return undoState.undoManager.canRedo();\n\tundoState.isUndoing.current = true;\n\tsetTimeout(() => {\n\t\tundoState.isUndoing.current = false;\n\t}, 0);\n\treturn undoState.undoManager.redo();\n};\n\n//#endregion\nexport { ATTRIBUTES_KEY, CHILDREN_KEY, CursorAwareness, CursorEphemeralStore, LoroCursorPlugin, LoroEphemeralCursorPlugin, LoroSyncPlugin, LoroUndoPlugin, NODE_NAME_KEY, ROOT_DOC_KEY, canRedo, canUndo, createNodeFromLoroObj, loroSyncPluginKey, loroUndoPluginKey, redo, undo, updateLoroToPmState };\n//# sourceMappingURL=index.js.map", + "import { Schema } from 'prosemirror-model';\n\nconst pDOM = [\"p\", 0], blockquoteDOM = [\"blockquote\", 0], hrDOM = [\"hr\"], preDOM = [\"pre\", [\"code\", 0]], brDOM = [\"br\"];\n/**\n[Specs](https://prosemirror.net/docs/ref/#model.NodeSpec) for the nodes defined in this schema.\n*/\nconst nodes = {\n /**\n NodeSpec The top level document node.\n */\n doc: {\n content: \"block+\"\n },\n /**\n A plain paragraph textblock. Represented in the DOM\n as a `

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

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

` to\n `

` elements.\n */\n heading: {\n attrs: { level: { default: 1, validate: \"number\" } },\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, 0]; }\n },\n /**\n 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    */\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() { return preDOM; }\n    },\n    /**\n    The text node.\n    */\n    text: {\n        group: \"inline\"\n    },\n    /**\n    An inline image (``) node. Supports `src`,\n    `alt`, and `href` attributes. The latter two default to the empty\n    string.\n    */\n    image: {\n        inline: true,\n        attrs: {\n            src: { validate: \"string\" },\n            alt: { default: null, validate: \"string|null\" },\n            title: { default: null, validate: \"string|null\" }\n        },\n        group: \"inline\",\n        draggable: true,\n        parseDOM: [{ tag: \"img[src]\", getAttrs(dom) {\n                    return {\n                        src: dom.getAttribute(\"src\"),\n                        title: dom.getAttribute(\"title\"),\n                        alt: dom.getAttribute(\"alt\")\n                    };\n                } }],\n        toDOM(node) { let { src, alt, title } = node.attrs; return [\"img\", { src, alt, title }]; }\n    },\n    /**\n    A hard line break, represented in the DOM as `
`.\n */\n hard_break: {\n inline: true,\n group: \"inline\",\n selectable: false,\n parseDOM: [{ tag: \"br\" }],\n toDOM() { return brDOM; }\n }\n};\nconst emDOM = [\"em\", 0], strongDOM = [\"strong\", 0], codeDOM = [\"code\", 0];\n/**\n[Specs](https://prosemirror.net/docs/ref/#model.MarkSpec) for the marks in the schema.\n*/\nconst marks = {\n /**\n A link. Has `href` and `title` attributes. `title`\n defaults to the empty string. Rendered and parsed as an ``\n element.\n */\n link: {\n attrs: {\n href: { validate: \"string\" },\n title: { default: null, validate: \"string|null\" }\n },\n inclusive: false,\n parseDOM: [{ tag: \"a[href]\", getAttrs(dom) {\n return { href: dom.getAttribute(\"href\"), title: dom.getAttribute(\"title\") };\n } }],\n toDOM(node) { let { href, title } = node.attrs; return [\"a\", { href, title }, 0]; }\n },\n /**\n An emphasis mark. Rendered as an `` element. Has parse rules\n that also match `` and `font-style: italic`.\n */\n em: {\n parseDOM: [\n { tag: \"i\" }, { tag: \"em\" },\n { style: \"font-style=italic\" },\n { style: \"font-style=normal\", clearMark: m => m.type.name == \"em\" }\n ],\n toDOM() { return emDOM; }\n },\n /**\n A strong mark. Rendered as ``, parse rules also match\n `` and `font-weight: bold`.\n */\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 { tag: \"b\", getAttrs: (node) => node.style.fontWeight != \"normal\" && null },\n { style: \"font-weight=400\", clearMark: m => m.type.name == \"strong\" },\n { style: \"font-weight\", getAttrs: (value) => /^(bold(er)?|[5-9]\\d{2,})$/.test(value) && null },\n ],\n toDOM() { return strongDOM; }\n },\n /**\n Code font mark. Represented as a `` element.\n */\n code: {\n code: true,\n parseDOM: [{ tag: \"code\" }],\n toDOM() { return codeDOM; }\n }\n};\n/**\nThis schema roughly corresponds to the document schema used by\n[CommonMark](http://commonmark.org/), minus the list elements,\nwhich are defined in the [`prosemirror-schema-list`](https://prosemirror.net/docs/ref/#schema-list)\nmodule.\n\nTo reuse elements from this schema, extend or read from its\n`spec.nodes` and `spec.marks` [properties](https://prosemirror.net/docs/ref/#model.Schema.spec).\n*/\nconst schema = new Schema({ nodes, marks });\n\nexport { marks, nodes, schema };\n", + "import { findWrapping, ReplaceAroundStep, canSplit, liftTarget, canJoin } from 'prosemirror-transform';\nimport { NodeRange, Fragment, Slice } from 'prosemirror-model';\nimport { Selection } from 'prosemirror-state';\n\nconst olDOM = [\"ol\", 0], ulDOM = [\"ul\", 0], liDOM = [\"li\", 0];\n/**\nAn ordered list [node spec](https://prosemirror.net/docs/ref/#model.NodeSpec). Has a single\nattribute, `order`, which determines the number at which the list\nstarts counting, and defaults to 1. Represented as an `
    `\nelement.\n*/\nconst orderedList = {\n attrs: { order: { default: 1, validate: \"number\" } },\n parseDOM: [{ tag: \"ol\", getAttrs(dom) {\n return { order: dom.hasAttribute(\"start\") ? +dom.getAttribute(\"start\") : 1 };\n } }],\n toDOM(node) {\n return node.attrs.order == 1 ? olDOM : [\"ol\", { start: node.attrs.order }, 0];\n }\n};\n/**\nA bullet list node spec, represented in the DOM as `
")) + } else { + Some(format!("
    \n{items}
")) + } +} + +fn code_block(node: &LoroMap) -> String { + let mut content = String::new(); + for child in children(node) { + match child { + Child::Text(t) => content.push_str(&plain_text(&t)), + Child::Node(m) if node_name(&m) == "hard_break" => content.push('\n'), + Child::Node(m) => content.push_str(&plain_node_text(&m)), + } + } + let content = content.trim_end_matches('\n'); + let lang = attr_str(node, "language").unwrap_or_default(); + let class = if lang.trim().is_empty() { + String::new() + } else { + format!(" class=\"language-{}\"", esc(lang.trim())) + }; + format!("
{}
", esc(content)) +} + +// --------------------------------------------------------------------------- +// Inline rendering +// --------------------------------------------------------------------------- + +/// Concatenated inline content of a node: text runs and inline child nodes. +fn inline_children(node: &LoroMap) -> String { + let mut out = String::new(); + for child in children(node) { + match child { + Child::Text(t) => out.push_str(&inline_text(&t)), + Child::Node(m) => out.push_str(&inline_node(&m)), + } + } + out +} + +fn inline_node(node: &LoroMap) -> String { + match node_name(node).as_str() { + "hard_break" => "
".to_string(), + "image" => image_html(node), + _ => inline_children(node), + } +} + +fn image_html(node: &LoroMap) -> String { + let alt = attr_str(node, "alt").unwrap_or_default(); + let src = attr_str(node, "src").unwrap_or_default(); + let Some(src) = safe_src(&src) else { + return esc(&alt); + }; + let title = attr_str(node, "title") + .filter(|t| !t.is_empty()) + .map(|t| format!(" title=\"{}\"", esc(&t))) + .unwrap_or_default(); + format!("\"{}\"{title}", esc(src), esc(&alt)) +} + +#[derive(PartialEq, Clone, Default)] +struct Marks { + strong: bool, + em: bool, + code: bool, + link: Option<(String, Option)>, +} + +/// Renders a LoroText as HTML, merging adjacent runs with identical marks. +fn inline_text(text: &LoroText) -> String { + let mut runs: Vec<(String, Marks)> = Vec::new(); + for delta in text.to_delta() { + let TextDelta::Insert { insert, attributes } = delta else { + continue; + }; + let attrs = attributes.unwrap_or_default(); + let on = |k: &str| attrs.get(k).is_some_and(|v| !matches!(v, LoroValue::Null)); + let link = attrs.get("link").map(|v| { + let href = v.get_by_key("href").and_then(value_str).unwrap_or_default(); + let title = v + .get_by_key("title") + .and_then(value_str) + .filter(|t| !t.is_empty()); + (href, title) + }); + let marks = Marks { + strong: on("strong"), + em: on("em"), + code: on("code"), + link, + }; + match runs.last_mut() { + Some((s, m)) if *m == marks => s.push_str(&insert), + _ => runs.push((insert, marks)), + } + } + runs.iter().map(|(s, m)| render_run(s, m)).collect() +} + +fn render_run(s: &str, m: &Marks) -> String { + let core = s.trim(); + if core.is_empty() { + return esc(s); + } + // Keep surrounding whitespace outside the tags. + let lead_len = s.len() - s.trim_start().len(); + let lead = &s[..lead_len]; + let trail = &s[lead_len + core.len()..]; + + let mut out = if m.code { + format!("{}", esc(core)) + } else { + esc(core) + }; + if m.em { + out = format!("{out}"); + } + if m.strong { + out = format!("{out}"); + } + if let Some((href, title)) = &m.link { + if let Some(href) = safe_href(href) { + let title = title + .as_deref() + .map(|t| format!(" title=\"{}\"", esc(t))) + .unwrap_or_default(); + out = format!("{out}", esc(href)); + } + } + format!("{}{out}{}", esc(lead), esc(trail)) +} diff --git a/src/hub.rs b/src/hub.rs new file mode 100644 index 0000000..f92b121 --- /dev/null +++ b/src/hub.rs @@ -0,0 +1,441 @@ +//! Per-note live state: one in-memory `LoroDoc` per note, shared by every +//! WebSocket connection editing that note. +//! +//! Wire protocol (binary frames, first byte is the tag): +//! - `0x01` SYNC_REQ: payload is an encoded `VersionVector`. The receiver +//! answers with an UPDATE containing what the requester is missing. +//! - `0x02` UPDATE: payload is Loro update bytes. Imported, persisted and +//! broadcast to the other connections when it changed the doc. +//! - `0x03` EPHEMERAL: opaque bytes, broadcast only, never persisted. + +use std::collections::HashMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; + +use loro::{ExportMode, Frontiers, LoroDoc, LoroList, LoroMap, VersionVector}; +use tokio::sync::{Mutex as AsyncMutex, broadcast}; +use topcoat::router::content::websocket::{Message, WebSocket}; + +use crate::export; +use crate::store::{Store, now_millis}; + +pub const SYNC_REQ: u8 = 0x01; +pub const UPDATE: u8 = 0x02; +pub const EPHEMERAL: u8 = 0x03; + +const SNAPSHOT_EVERY: u64 = 50; +/// Least time between two versions recorded while the note is being edited. +const VERSION_EVERY_MS: i64 = 10 * 60 * 1000; +/// Quiet time after the last applied update before the searchable text is written. +const TEXT_FLUSH_DELAY: Duration = Duration::from_secs(2); +const CHANNEL_CAPACITY: usize = 256; + +/// A broadcast item: the connection id that sent it, and the full frame. +type Frame = (u64, Vec); + +pub struct Hub { + rooms: Mutex>>, + next_conn: AtomicU64, +} + +impl Hub { + pub fn new() -> Self { + Self { + rooms: Mutex::new(HashMap::new()), + next_conn: AtomicU64::new(1), + } + } + + /// Returns the live room for `note_id`, loading it from the store on first use. + /// Rooms are kept in memory after their last connection leaves, so a room is + /// never orphaned while a connection still holds it. + pub async fn room(&self, store: &Store, note_id: &str) -> anyhow::Result> { + let existing = self + .rooms + .lock() + .unwrap() + .get(note_id) + .cloned(); + if let Some(room) = existing { + return Ok(room); + } + + // Load without holding the map lock: this awaits the store. + let doc = load_doc(store, note_id).await?; + let last_version = load_last_version(store, note_id).await?; + let room = std::sync::Arc::new(Room::new(note_id, doc, last_version)); + + // Another task may have loaded the same note meanwhile; keep the first one. + let mut rooms = self.rooms.lock().unwrap(); + Ok(rooms + .entry(note_id.to_owned()) + .or_insert(room) + .clone()) + } + + /// Drops the in-memory room for a deleted note. Connections still holding the + /// room keep working until they leave; nothing new is loaded for this id. + pub fn forget(&self, note_id: &str) { + self.rooms.lock().unwrap().remove(note_id); + } + + fn next_conn_id(&self) -> u64 { + self.next_conn.fetch_add(1, Ordering::Relaxed) + } +} + +impl Default for Hub { + fn default() -> Self { + Self::new() + } +} + +/// Update holding the root structure loro-prosemirror expects: a `doc` node with +/// one empty paragraph. Written once at note creation so clients never race to +/// initialise the root. +pub fn initial_note_update() -> anyhow::Result> { + let doc = LoroDoc::new(); + let root = doc.get_map("doc"); + root.insert("nodeName", "doc")?; + root.insert_container("attributes", LoroMap::new())?; + let children = root.insert_container("children", LoroList::new())?; + let paragraph = children.push_container(LoroMap::new())?; + paragraph.insert("nodeName", "paragraph")?; + paragraph.insert_container("attributes", LoroMap::new())?; + paragraph.insert_container("children", LoroList::new())?; + doc.commit(); + Ok(doc.export(ExportMode::all_updates())?) +} + +/// The newest recorded version of a note, with its time in millis. +async fn load_last_version(store: &Store, note_id: &str) -> anyhow::Result> { + match store.list_versions(note_id).await?.into_iter().next() { + Some((at, bytes)) => Ok(Some((at, Frontiers::decode(&bytes)?))), + None => Ok(None), + } +} + +pub async fn load_doc(store: &Store, note_id: &str) -> anyhow::Result { + let bytes = store.load_doc(note_id).await?; + let doc = LoroDoc::new(); + if let Some(snapshot) = bytes.snapshot { + doc.import(&snapshot)?; + } + for update in bytes.updates { + doc.import(&update)?; + } + Ok(doc) +} + +struct RoomState { + doc: LoroDoc, + /// Live WebSocket connections on this room. + conns: usize, + updates_since_snapshot: u64, + /// A searchable-text flush is scheduled and has not read the doc yet. + text_pending: bool, + /// Time in millis and frontiers of the newest recorded version. + last_version: Option<(i64, Frontiers)>, +} + +pub struct Room { + note_id: String, + tx: broadcast::Sender, + state: AsyncMutex, +} + +impl Room { + fn new(note_id: &str, doc: LoroDoc, last_version: Option<(i64, Frontiers)>) -> Self { + let (tx, _) = broadcast::channel(CHANNEL_CAPACITY); + Self { + note_id: note_id.to_owned(), + tx, + state: AsyncMutex::new(RoomState { + doc, + conns: 0, + updates_since_snapshot: 0, + text_pending: false, + last_version, + }), + } + } + + /// Registers a connection. The receiver is created under the same lock as the + /// connection count, so no broadcast can be missed between join and first recv. + async fn join(&self) -> broadcast::Receiver { + let mut state = self.state.lock().await; + state.conns += 1; + self.tx.subscribe() + } + + /// Records a version and persists a snapshot when the last connection leaves. + async fn leave(&self, store: &Store) { + let mut state = self.state.lock().await; + state.conns = state.conns.saturating_sub(1); + if state.conns == 0 { + if let Err(err) = record_version(&mut state, store, &self.note_id).await { + eprintln!("version record failed for note {}: {err:#}", self.note_id); + } + if let Err(err) = write_snapshot(&mut state, store, &self.note_id).await { + eprintln!("snapshot failed for note {}: {err:#}", self.note_id); + } + } + } + + /// Frame announcing our version vector, so the peer can send what we lack. + pub async fn sync_req_frame(&self) -> Vec { + let state = self.state.lock().await; + frame(SYNC_REQ, &state.doc.oplog_vv().encode()) + } + + /// Answers a SYNC_REQ payload with an UPDATE frame of what the peer lacks. + async fn sync_reply(&self, payload: &[u8]) -> anyhow::Result> { + let state = self.state.lock().await; + let vv = VersionVector::decode(payload)?; + let updates = state.doc.export(ExportMode::updates(&vv))?; + Ok(frame(UPDATE, &updates)) + } + + async fn all_updates_frame(&self) -> anyhow::Result> { + let state = self.state.lock().await; + Ok(frame(UPDATE, &state.doc.export(ExportMode::all_updates())?)) + } + + /// Imports an UPDATE payload. Returns `true` when it changed the doc, in which + /// case the update has been persisted and should be broadcast. + async fn apply_update(self: &std::sync::Arc, store: &std::sync::Arc, payload: &[u8]) -> anyhow::Result { + let mut state = self.state.lock().await; + let before = state.doc.oplog_vv(); + state.doc.import(payload)?; + if state.doc.oplog_vv() == before { + return Ok(false); + } + persist_update(self, &mut state, store, payload).await?; + Ok(true) + } + + /// The document as it was at `frontiers`, as HTML. The live doc is not changed. + pub async fn html_at(&self, frontiers: &Frontiers) -> anyhow::Result { + let state = self.state.lock().await; + let forked = state.doc.fork_at(frontiers)?; + Ok(export::to_html(&forked)) + } + + /// Makes the doc match an earlier version. The change is a new edit on top of the + /// history, so it is persisted and broadcast like a client update. The state before + /// and after the restore are both recorded as versions, so the restore can be undone. + pub async fn restore(self: &std::sync::Arc, store: &std::sync::Arc, frontiers: &Frontiers) -> anyhow::Result<()> { + let mut state = self.state.lock().await; + let vv_before = state.doc.oplog_vv(); + record_version(&mut state, store, &self.note_id).await?; + state.doc.revert_to(frontiers)?; + state.doc.commit(); + if state.doc.oplog_vv() == vv_before { + return Ok(()); + } + let update = state.doc.export(ExportMode::updates(&vv_before))?; + persist_update(self, &mut state, store, &update).await?; + // Connection 0 never exists, so every connection receives the restore. + self.broadcast(0, frame(UPDATE, &update)); + record_version(&mut state, store, &self.note_id).await + } + + fn broadcast(&self, conn_id: u64, frame: Vec) { + // Err only means there are no receivers, which is fine. + let _ = self.tx.send((conn_id, frame)); + } + + /// Live markdown of the in-memory doc, with note links written as `[[Title]]`. + /// `titles` maps note ids to their titles. + pub async fn markdown_with(&self, titles: HashMap) -> String { + let state = self.state.lock().await; + let resolve = |id: &str| titles.get(id).cloned(); + export::to_markdown_with(&state.doc, &resolve) + } + + pub async fn html(&self) -> String { + let state = self.state.lock().await; + export::to_html(&state.doc) + } +} + +/// Stores a changed update, counts it towards the next snapshot, and schedules the +/// searchable-text flush. The caller has already imported the update into `state`. +async fn persist_update( + room: &std::sync::Arc, + state: &mut RoomState, + store: &std::sync::Arc, + payload: &[u8], +) -> anyhow::Result<()> { + store.append_update(&room.note_id, payload).await?; + state.updates_since_snapshot += 1; + if state.updates_since_snapshot >= SNAPSHOT_EVERY { + write_snapshot(state, store, &room.note_id).await?; + } + if !state.text_pending { + state.text_pending = true; + tokio::spawn(flush_text(room.clone(), store.clone())); + } + Ok(()) +} + +/// Records the doc's current frontiers as a version, unless they are the same as the +/// newest recorded version. +async fn record_version(state: &mut RoomState, store: &Store, note_id: &str) -> anyhow::Result<()> { + let frontiers = state.doc.oplog_frontiers(); + if state.last_version.as_ref().is_some_and(|(_, last)| *last == frontiers) { + return Ok(()); + } + let at = now_millis(); + store.add_version(note_id, at, &frontiers.encode()).await?; + state.last_version = Some((at, frontiers)); + Ok(()) +} + +/// Writes the note's title and searchable text after typing pauses. The flag is +/// cleared before the doc is read, so an update that arrives during the write +/// schedules a new flush. A version is recorded when the last one is 10 minutes old. +async fn flush_text(room: std::sync::Arc, store: std::sync::Arc) { + tokio::time::sleep(TEXT_FLUSH_DELAY).await; + let (title, body, links) = { + let mut state = room.state.lock().await; + state.text_pending = false; + let due = state + .last_version + .as_ref() + .is_none_or(|(at, _)| now_millis() - at >= VERSION_EVERY_MS); + if due { + if let Err(err) = record_version(&mut state, &store, &room.note_id).await { + eprintln!("version record failed for note {}: {err:#}", room.note_id); + } + } + ( + export::title(&state.doc), + export::to_markdown(&state.doc), + export::note_links(&state.doc), + ) + }; + if let Err(err) = store.set_title(&room.note_id, &title).await { + eprintln!("title write failed for note {}: {err:#}", room.note_id); + } + if let Err(err) = store.put_text(&room.note_id, &title, &body).await { + eprintln!("text write failed for note {}: {err:#}", room.note_id); + } + if let Err(err) = store.set_links(&room.note_id, &links).await { + eprintln!("link index write failed for note {}: {err:#}", room.note_id); + } +} + +async fn write_snapshot( + state: &mut RoomState, + store: &Store, + note_id: &str, +) -> anyhow::Result<()> { + let snapshot = state.doc.export(ExportMode::Snapshot)?; + let markdown = export::to_markdown(&state.doc); + let title = export::title(&state.doc); + store + .put_snapshot(note_id, &snapshot, &markdown, &title) + .await?; + store + .set_links(note_id, &export::note_links(&state.doc)) + .await?; + state.updates_since_snapshot = 0; + Ok(()) +} + +fn frame(tag: u8, payload: &[u8]) -> Vec { + let mut out = Vec::with_capacity(payload.len() + 1); + out.push(tag); + out.extend_from_slice(payload); + out +} + +/// Drives one WebSocket connection until either side closes it. +pub async fn serve_socket(hub: std::sync::Arc, store: std::sync::Arc, room: std::sync::Arc, mut socket: WebSocket) { + let conn_id = hub.next_conn_id(); + let mut rx = room.join().await; + + if socket + .send(Message::binary(room.sync_req_frame().await)) + .await + .is_err() + { + room.leave(&store).await; + return; + } + + loop { + tokio::select! { + incoming = socket.recv() => { + let message = match incoming { + Some(Ok(message)) => message, + _ => break, + }; + match message { + Message::Binary(bytes) => { + if !handle_frame(&room, &store, conn_id, &bytes, &mut socket).await { + break; + } + } + Message::Close(_) => break, + // Text frames are not part of the protocol; ping/pong are handled by topcoat. + _ => {} + } + } + event = rx.recv() => match event { + Ok((from, frame)) => { + if from != conn_id && socket.send(Message::binary(frame)).await.is_err() { + break; + } + } + Err(broadcast::error::RecvError::Lagged(_)) => { + // Missed frames: push every update; importing known ops is a no-op. + let Ok(frame) = room.all_updates_frame().await else { break }; + if socket.send(Message::binary(frame)).await.is_err() { + break; + } + } + Err(broadcast::error::RecvError::Closed) => break, + } + } + } + + room.leave(&store).await; +} + +/// Handles one inbound binary frame. Returns `false` when the socket is unusable. +async fn handle_frame( + room: &std::sync::Arc, + store: &std::sync::Arc, + conn_id: u64, + bytes: &[u8], + socket: &mut WebSocket, +) -> bool { + let Some((&tag, payload)) = bytes.split_first() else { + return true; + }; + match tag { + SYNC_REQ => match room.sync_reply(payload).await { + Ok(reply) => socket.send(Message::binary(reply)).await.is_ok(), + Err(err) => { + eprintln!("bad sync request on note {}: {err:#}", room.note_id); + true + } + }, + UPDATE => { + match room.apply_update(store, payload).await { + Ok(true) => room.broadcast(conn_id, frame(UPDATE, payload)), + Ok(false) => {} + Err(err) => eprintln!("bad update on note {}: {err:#}", room.note_id), + } + true + } + EPHEMERAL => { + room.broadcast(conn_id, frame(EPHEMERAL, payload)); + true + } + _ => true, + } +} diff --git a/src/i18n.rs b/src/i18n.rs new file mode 100644 index 0000000..dc94564 --- /dev/null +++ b/src/i18n.rs @@ -0,0 +1,414 @@ +//! Localization: the supported languages, the message catalogue, count and date +//! formatting, and language resolution from the request. +//! +//! Every message is one arm of [`t`]'s single `match` over [`Msg`], and each arm gives +//! both languages. A message without a Turkish text does not compile. + +use topcoat::{ + context::Cx, + cookie::{Cookie, Cookies, SameSite, cookies, time::Duration}, + router::request::headers, +}; + +/// Name of the cookie that stores the language choice. +pub const LANG_COOKIE: &str = "lang"; + +/// How long the language choice is remembered. +pub const LANG_COOKIE_DAYS: i64 = 365; + +/// A supported interface language. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Lang { + En, + Tr, +} + +impl Lang { + /// The value stored in the cookie and used in the `lang` attribute of ``. + pub fn code(self) -> &'static str { + match self { + Self::En => "en", + Self::Tr => "tr", + } + } + + /// Parses a cookie or form value. Returns `None` for unsupported languages. + pub fn from_code(code: &str) -> Option { + match code { + "en" => Some(Self::En), + "tr" => Some(Self::Tr), + _ => None, + } + } +} + +/// Every interface message. Add a variant here, then its texts in [`t`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Msg { + AppName, + MainNavigation, + SkipToContent, + Search, + SearchLabel, + SearchPlaceholder, + NewNote, + NewNotebook, + NewNotebookLabel, + Add, + AllNotes, + Unfiled, + Trash, + Notebooks, + Theme, + ThemeLight, + ThemeDark, + ThemeSystem, + ColorScheme, + Language, + LanguageEnglish, + LanguageTurkish, + HideSidebar, + ShowSidebar, + OpenMenu, + CloseMenu, + Undo, + Dismiss, + ToastTrashed, + ToastRestored, + ToastNotebookCreated, + ToastNotebookDeleted, + ToastMoved, + Untitled, + JustNow, + Yesterday, + NoNotesYet, + CreateOneHint, + EmptyNotebook, + EmptyUnfiled, + EmptyTrash, + SelectNote, + GroupToday, + GroupPrevious7, + GroupEarlier, + BackToList, + MoveToNotebook, + AlreadyHere, + ExportAs, + ExportMarkdown, + ExportHtml, + ExportPdf, + ExportAll, + MoveToTrash, + InTrash, + AlreadyInTrash, + RestoreFirst, + Restore, + DeleteForever, + EmptyTrashAction, + TrashRetention, + Trashed, + ConfirmEmptyTrashTitle, + ConfirmForeverTitle, + CannotUndo, + Cancel, + Rename, + RenameNotebook, + NotebookOptions, + DeleteNotebook, + DeleteNotebookTitle, + DeleteNotebookBody, + Breadcrumb, + NoMatches, + GuestName, + GuestSubtitle, + AccountMenu, + SearchOptions, + MatchCase, + WholeWord, + ExactPhrase, + RegexSearch, + InvalidRegex, + InvalidRegexHint, + CheckSpelling, + NoteActions, + VersionHistory, + CurrentVersion, + NoVersionsYet, + RestoreVersion, + BackToNote, + ToastVersionRestored, + Import, + ImportMarkdown, + ImportHelp, + ChooseFiles, + ChooseFolder, + ImportProgress, + ImportDoneOne, + ImportDoneMany, + ImportFailed, + ImportNoFiles, + ImportGoToNotes, + LinkedFrom, + NoNoteNamed, + CreateNote, +} + +/// The text of `msg` in `lang`. +pub fn t(lang: Lang, msg: Msg) -> &'static str { + // (English, Turkish) for every message. + let (en, tr) = match msg { + Msg::AppName => ("Notes", "Notlar"), + Msg::MainNavigation => ("Main navigation", "Ana gezinme"), + Msg::SkipToContent => ("Skip to content", "İçeriğe geç"), + Msg::Search => ("Search", "Ara"), + Msg::SearchLabel => ("Search notes", "Notlarda ara"), + Msg::SearchPlaceholder => ("Search notes", "Notlarda ara"), + Msg::NewNote => ("New note", "Yeni not"), + Msg::NewNotebook => ("New notebook", "Yeni defter"), + Msg::NewNotebookLabel => ("Notebook name", "Defter adı"), + Msg::Add => ("Add", "Ekle"), + Msg::AllNotes => ("All notes", "Tüm notlar"), + Msg::Unfiled => ("Unfiled", "Dosyalanmamış"), + Msg::Trash => ("Trash", "Çöp kutusu"), + Msg::Notebooks => ("Notebooks", "Defterler"), + Msg::Theme => ("Theme", "Tema"), + Msg::ThemeLight => ("Light", "Açık"), + Msg::ThemeDark => ("Dark", "Koyu"), + Msg::ThemeSystem => ("System", "Sistem"), + Msg::ColorScheme => ("Color scheme", "Renk şeması"), + Msg::Language => ("Language", "Dil"), + Msg::LanguageEnglish => ("English", "English"), + Msg::LanguageTurkish => ("Türkçe", "Türkçe"), + Msg::HideSidebar => ("Hide sidebar", "Kenar çubuğunu gizle"), + Msg::ShowSidebar => ("Show sidebar", "Kenar çubuğunu göster"), + Msg::OpenMenu => ("Open menu", "Menüyü aç"), + Msg::CloseMenu => ("Close menu", "Menüyü kapat"), + Msg::Undo => ("Undo", "Geri al"), + Msg::Dismiss => ("Dismiss", "Kapat"), + Msg::ToastTrashed => ("Note moved to trash.", "Not çöp kutusuna taşındı."), + Msg::ToastRestored => ("Note restored.", "Not geri yüklendi."), + Msg::ToastNotebookCreated => ("Notebook created.", "Defter oluşturuldu."), + Msg::ToastNotebookDeleted => ("Notebook deleted.", "Defter silindi."), + Msg::ToastMoved => ("Note moved.", "Not taşındı."), + Msg::Untitled => ("Untitled", "Adsız"), + Msg::JustNow => ("Just now", "Az önce"), + Msg::Yesterday => ("Yesterday", "Dün"), + Msg::NoNotesYet => ("No notes yet.", "Henüz not yok."), + Msg::CreateOneHint => ("to create one.", "ile yeni not oluştur."), + Msg::EmptyNotebook => ("Nothing in this notebook.", "Bu defterde not yok."), + Msg::EmptyUnfiled => ("Nothing unfiled.", "Dosyalanmamış not yok."), + Msg::EmptyTrash => ("Trash is empty.", "Çöp kutusu boş."), + Msg::SelectNote => ("Select a note", "Bir not seçin"), + Msg::GroupToday => ("Today", "Bugün"), + Msg::GroupPrevious7 => ("Previous 7 days", "Önceki 7 gün"), + Msg::GroupEarlier => ("Earlier", "Daha önce"), + Msg::BackToList => ("Back to list", "Listeye dön"), + Msg::MoveToNotebook => ("Move to notebook", "Defterine taşı"), + Msg::AlreadyHere => ("Already in this notebook.", "Zaten bu defterde."), + Msg::ExportAs => ("Export as", "Şu biçimde dışa aktar"), + Msg::ExportMarkdown => ("Markdown (.md)", "Markdown (.md)"), + Msg::ExportHtml => ("HTML (.html)", "HTML (.html)"), + Msg::ExportPdf => ("PDF (print)", "PDF (yazdır)"), + Msg::ExportAll => ("Export all notes (.zip)", "Tüm notları dışa aktar (.zip)"), + Msg::MoveToTrash => ("Move to trash", "Çöp kutusuna taşı"), + Msg::InTrash => ("This note is in the trash.", "Bu not çöp kutusunda."), + Msg::AlreadyInTrash => ("Already in the trash.", "Zaten çöp kutusunda."), + Msg::RestoreFirst => ("Restore the note to move it.", "Notu taşımak için geri yükleyin."), + Msg::Restore => ("Restore", "Geri yükle"), + Msg::DeleteForever => ("Delete forever", "Kalıcı olarak sil"), + Msg::EmptyTrashAction => ("Empty trash", "Çöp kutusunu boşalt"), + Msg::TrashRetention => ( + "Notes in the trash are deleted after 30 days.", + "Çöp kutusundaki notlar 30 gün sonra silinir.", + ), + Msg::Trashed => ("Trashed", "Çöpe taşındı"), + Msg::ConfirmEmptyTrashTitle => ("Empty trash?", "Çöp kutusu boşaltılsın mı?"), + Msg::ConfirmForeverTitle => ("Delete this note forever?", "Bu not kalıcı olarak silinsin mi?"), + Msg::CannotUndo => ("This cannot be undone.", "Bu işlem geri alınamaz."), + Msg::Cancel => ("Cancel", "İptal"), + Msg::Rename => ("Rename", "Yeniden adlandır"), + Msg::RenameNotebook => ("Rename notebook", "Defteri yeniden adlandır"), + Msg::NotebookOptions => ("Notebook options", "Defter seçenekleri"), + Msg::DeleteNotebook => ("Delete notebook", "Defteri sil"), + Msg::DeleteNotebookTitle => ("Delete notebook?", "Defter silinsin mi?"), + Msg::DeleteNotebookBody => ("Its notes move to Unfiled.", "Notları Dosyalanmamış bölümüne taşınır."), + Msg::Breadcrumb => ("Breadcrumb", "Konum"), + Msg::NoMatches => ("No notes match.", "Eşleşen not yok."), + Msg::GuestName => ("Guest", "Misafir"), + Msg::GuestSubtitle => ("Personal library", "Kişisel kitaplık"), + Msg::AccountMenu => ("Account menu", "Hesap menüsü"), + Msg::SearchOptions => ("Search options", "Arama seçenekleri"), + Msg::MatchCase => ("Match case", "Büyük/küçük harfe duyarlı"), + Msg::WholeWord => ("Whole word", "Tam kelime"), + Msg::ExactPhrase => ("Exact phrase", "Tam ifade"), + Msg::RegexSearch => ("Regular expression", "Düzenli ifade"), + Msg::InvalidRegex => ("Not a valid regular expression.", "Geçerli bir düzenli ifade değil."), + Msg::InvalidRegexHint => ("Check the brackets and escapes.", "Parantezleri ve kaçış karakterlerini kontrol edin."), + Msg::CheckSpelling => ( + "Check the spelling or try fewer words.", + "Yazımı kontrol edin ya da daha az kelime deneyin.", + ), + Msg::NoteActions => ("Note actions", "Not işlemleri"), + Msg::Import => ("Import Markdown", "Markdown içe aktar"), + Msg::ImportMarkdown => ("Import Markdown…", "Markdown içe aktar…"), + Msg::ImportHelp => ( + "Import .md files or a whole folder (e.g. an Obsidian vault). Each subfolder becomes a notebook.", + "Tek tek .md dosyaları ya da bütün bir klasörü (ör. bir Obsidian kasası) içe aktarın. Her alt klasör bir deftere dönüşür.", + ), + Msg::ChooseFiles => ("Choose files", "Dosya seç"), + Msg::ChooseFolder => ("Choose folder", "Klasör seç"), + Msg::ImportProgress => ("Importing {done} of {total}…", "{done} / {total} içe aktarılıyor…"), + Msg::ImportDoneOne => ("Imported {n} note.", "{n} not içe aktarıldı."), + Msg::ImportDoneMany => ("Imported {n} notes.", "{n} not içe aktarıldı."), + Msg::ImportFailed => ("{m} failed.", "{m} başarısız."), + Msg::ImportNoFiles => ( + "No .md, .markdown or .txt files found.", + ".md, .markdown ya da .txt dosyası bulunamadı.", + ), + Msg::ImportGoToNotes => ("Go to notes", "Notlara git"), + Msg::LinkedFrom => ("Linked from", "Bağlantı veren notlar"), + Msg::NoNoteNamed => ("No note named \u{201c}{title}\u{201d}.", "\u{201c}{title}\u{201d} adlı not yok."), + Msg::CreateNote => ("Create note", "Not oluştur"), + Msg::VersionHistory => ("Version history", "Sürüm geçmişi"), + Msg::CurrentVersion => ("Current version", "Güncel sürüm"), + Msg::NoVersionsYet => ( + "No earlier versions yet. Versions are saved every 10 minutes while you write.", + "Henüz önceki sürüm yok. Yazarken sürümler her 10 dakikada bir kaydedilir.", + ), + Msg::RestoreVersion => ("Restore this version", "Bu sürümü geri yükle"), + Msg::BackToNote => ("Back to note", "Nota dön"), + Msg::ToastVersionRestored => ("Version restored.", "Sürüm geri yüklendi."), + }; + match lang { + Lang::En => en, + Lang::Tr => tr, + } +} + +/// "1 note" / "3 notes". Turkish does not inflect the noun after a number: "1 not", "3 not". +pub fn notes_count(lang: Lang, n: usize) -> String { + match lang { + Lang::En if n == 1 => "1 note".to_owned(), + Lang::En => format!("{n} notes"), + Lang::Tr => format!("{n} not"), + } +} + +/// "1 result for “rust”" / "3 results for “rust”", or the Turkish "3 sonuç “rust” için". +pub fn results_for(lang: Lang, n: usize, query: &str) -> String { + match lang { + Lang::En if n == 1 => format!("1 result for \u{201c}{query}\u{201d}"), + Lang::En => format!("{n} results for \u{201c}{query}\u{201d}"), + Lang::Tr => format!("{n} sonuç \u{201c}{query}\u{201d} için"), + } +} + +/// The consequence line of the empty-trash dialog: "This deletes 3 notes forever." / +/// "3 not kalıcı olarak silinecek." +pub fn forever_count(lang: Lang, n: usize) -> String { + match lang { + Lang::En => format!("This deletes {} forever.", notes_count(lang, n)), + Lang::Tr => format!("{} kalıcı olarak silinecek.", notes_count(lang, n)), + } +} + +/// A relative time such as "5 min ago" or "5 dk önce", a day name, or a date for older +/// times. `now_ms` is the current time in Unix milliseconds. +pub fn relative_time(lang: Lang, updated_ms: i64, now_ms: i64) -> String { + let secs = (now_ms - updated_ms).max(0) / 1000; + let mins = secs / 60; + let hours = secs / 3600; + let days = secs / 86_400; + if secs < 60 { + t(lang, Msg::JustNow).to_owned() + } else if secs < 3600 { + match lang { + Lang::En => format!("{mins} min ago"), + Lang::Tr => format!("{mins} dk önce"), + } + } else if secs < 86_400 { + match lang { + Lang::En => format!("{hours} h ago"), + Lang::Tr => format!("{hours} sa önce"), + } + } else if days == 1 { + t(lang, Msg::Yesterday).to_owned() + } else if days < 7 { + match lang { + Lang::En => format!("{days} days ago"), + Lang::Tr => format!("{days} gün önce"), + } + } else { + date(lang, updated_ms) + } +} + +/// A calendar date in UTC: "Oct 27, 2026" in English, "27 Eki 2026" in Turkish. +pub fn date(lang: Lang, ms: i64) -> String { + const EN: [&str; 12] = [ + "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", + ]; + const TR: [&str; 12] = [ + "Oca", "Şub", "Mar", "Nis", "May", "Haz", "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara", + ]; + // Civil-from-days (Howard Hinnant's algorithm). + let z = ms.div_euclid(86_400_000) + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + if month <= 2 { 1 } else { 0 }; + let idx = (month - 1) as usize; + match lang { + Lang::En => format!("{} {}, {}", EN[idx], day, year), + Lang::Tr => format!("{} {} {}", day, TR[idx], year), + } +} + +/// A date and UTC time: "Oct 27, 2026 14:05" in English, "27 Eki 2026 14:05" in Turkish. +pub fn date_time(lang: Lang, ms: i64) -> String { + let minutes = ms.rem_euclid(86_400_000) / 60_000; + format!("{} {:02}:{:02}", date(lang, ms), minutes / 60, minutes % 60) +} + +/// Picks the language from an `Accept-Language` header: the first listed language that is +/// English or Turkish. Anything else falls back to English. +pub fn from_accept_language(header: &str) -> Lang { + for part in header.split(',') { + let tag = part.split(';').next().unwrap_or("").trim().to_ascii_lowercase(); + if tag.starts_with("tr") { + return Lang::Tr; + } + if tag.starts_with("en") { + return Lang::En; + } + } + Lang::En +} + +/// The language of this request. The `lang` cookie wins; without it, the browser's +/// `Accept-Language` decides; otherwise English. +pub fn lang(cx: &Cx) -> Lang { + if let Some(cookie) = cookies(cx).get(LANG_COOKIE) { + if let Some(lang) = Lang::from_code(cookie.value()) { + return lang; + } + } + let header = headers(cx) + .get("accept-language") + .and_then(|value| value.to_str().ok()) + .unwrap_or(""); + from_accept_language(header) +} + +/// The cookie that remembers `lang` for a year. +pub fn lang_cookie(lang: Lang) -> Cookie<'static> { + Cookie::build((LANG_COOKIE, lang.code())) + .path("/") + .same_site(SameSite::Lax) + .max_age(Duration::days(LANG_COOKIE_DAYS)) + .build() +} diff --git a/src/import.rs b/src/import.rs new file mode 100644 index 0000000..6121990 --- /dev/null +++ b/src/import.rs @@ -0,0 +1,743 @@ +//! Markdown import: the inverse of `export.rs`. Parses CommonMark into a +//! loro-prosemirror shaped LoroDoc (same layout as `export::to_markdown` reads). +//! +//! Degradations (GFM bits that the schema cannot represent): +//! - strikethrough: content kept, no mark +//! - tables: one paragraph per row, cells joined with " | " +//! - task list items: normal list items with a "[ ] " / "[x] " text prefix +//! - raw HTML (block or inline): its text, as plain text +//! - footnotes: not enabled, so `[^x]` stays literal text +//! - soft breaks become a space, hard breaks become `hard_break` nodes +//! - wiki links `[[Title]]`, `[[Title|text]]`, `[[Title#heading]]` in plain text become +//! links to `/notes/by-title/`; embeds `![[...]]` stay plain text + +use std::collections::HashMap; + +use anyhow::Result; +use loro::{ + ExpandType, ExportMode, LoroDoc, LoroList, LoroMap, LoroResult, LoroText, LoroValue, + StyleConfig, StyleConfigMap, +}; +use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag}; + +/// Parses markdown into a fresh LoroDoc with the note layout. +pub fn markdown_to_doc(md: &str) -> Result<LoroDoc> { + let body = strip_front_matter(md); + let mut options = Options::empty(); + options.insert(Options::ENABLE_STRIKETHROUGH); + options.insert(Options::ENABLE_TABLES); + options.insert(Options::ENABLE_TASKLISTS); + let events: Vec<Event> = Parser::new_ext(body, options).collect(); + let mut pos = 0; + let blocks = parse_blocks(&events, &mut pos, false); + build(&blocks) +} + +/// Same as `markdown_to_doc`, exported as a full Loro update. +pub fn markdown_to_update(md: &str) -> Result<Vec<u8>> { + let doc = markdown_to_doc(md)?; + Ok(doc.export(ExportMode::all_updates())?) +} + +/// A relative link to a `.md` file (`[text](Some%20Note.md)`, also what export writes for +/// note links with mixed formatting) becomes a link to the note with that file's name. +/// Any other destination is kept. +fn note_file_href(dest: &str) -> String { + let path = dest.split('#').next().unwrap_or(dest); + let relative = !path.contains("://") && !path.starts_with(['/', '?']) && !path.starts_with("mailto:"); + let Some(stem) = path.strip_suffix(".md").filter(|_| relative) else { + return dest.to_string(); + }; + let decoded = crate::export::percent_decode(stem); + let title = decoded.rsplit('/').next().unwrap_or(&decoded).trim(); + if title.is_empty() { + return dest.to_string(); + } + format!("/notes/by-title/{}", crate::export::percent_encode(title)) +} + +/// Drops a leading `---` ... `---` YAML block. Unclosed blocks are kept as text. +pub fn strip_front_matter(md: &str) -> &str { + let mut lines = md.split_inclusive('\n'); + let Some(first) = lines.next() else { + return md; + }; + if first.trim_end() != "---" { + return md; + } + let mut offset = first.len(); + for line in lines { + offset += line.len(); + if line.trim_end() == "---" { + return &md[offset..]; + } + } + md +} + +// --------------------------------------------------------------------------- +// Intermediate tree +// --------------------------------------------------------------------------- + +#[derive(Clone, Default, PartialEq)] +struct Marks { + strong: bool, + em: bool, + code: bool, + link: Option<(String, Option<String>)>, +} + +#[derive(Clone)] +enum Inline { + Text(String, Marks), + HardBreak, + Image { + src: String, + alt: String, + title: Option<String>, + }, +} + +enum Block { + Paragraph(Vec<Inline>), + Heading(i64, Vec<Inline>), + Quote(Vec<Block>), + Code { lang: Option<String>, text: String }, + Rule, + List { + ordered: bool, + start: i64, + items: Vec<Vec<Block>>, + }, +} + +// --------------------------------------------------------------------------- +// Event -> tree +// --------------------------------------------------------------------------- + +/// Parses block events starting at `pos`. In `nested` mode it returns after +/// consuming the End event of its container. +fn parse_blocks(ev: &[Event<'_>], pos: &mut usize, nested: bool) -> Vec<Block> { + let mut out = Vec::new(); + while let Some(event) = ev.get(*pos) { + match event { + Event::End(_) => { + *pos += 1; + if nested { + break; + } + } + Event::Start(Tag::Paragraph) => { + *pos += 1; + let inl = inlines(ev, pos); + skip_end(ev, pos); + out.push(Block::Paragraph(inl)); + } + Event::Start(Tag::Heading { level, .. }) => { + *pos += 1; + let inl = inlines(ev, pos); + skip_end(ev, pos); + out.push(Block::Heading(heading_level(*level), inl)); + } + Event::Start(Tag::BlockQuote(_)) => { + *pos += 1; + let inner = parse_blocks(ev, pos, true); + out.push(Block::Quote(inner)); + } + Event::Start(Tag::CodeBlock(kind)) => { + let lang = match kind { + CodeBlockKind::Fenced(info) => { + info.split_whitespace().next().map(str::to_owned) + } + CodeBlockKind::Indented => None, + }; + *pos += 1; + let mut text = String::new(); + while let Some(e) = ev.get(*pos) { + *pos += 1; + match e { + Event::End(_) => break, + Event::Text(t) => text.push_str(t), + _ => {} + } + } + out.push(Block::Code { + lang, + text: text.trim_end_matches('\n').to_owned(), + }); + } + Event::Start(Tag::HtmlBlock) => { + *pos += 1; + let mut text = String::new(); + while let Some(e) = ev.get(*pos) { + *pos += 1; + match e { + Event::End(_) => break, + Event::Html(t) | Event::Text(t) => text.push_str(t), + _ => {} + } + } + let t = text.trim(); + if !t.is_empty() { + out.push(Block::Paragraph(vec![Inline::Text( + t.to_owned(), + Marks::default(), + )])); + } + } + Event::Start(Tag::List(start)) => { + *pos += 1; + let mut items = Vec::new(); + while let Some(e) = ev.get(*pos) { + match e { + Event::End(_) => { + *pos += 1; + break; + } + Event::Start(Tag::Item) => { + *pos += 1; + let mut blocks = parse_blocks(ev, pos, true); + // Schema: list_item content is "paragraph block*". + if !matches!(blocks.first(), Some(Block::Paragraph(_))) { + blocks.insert(0, Block::Paragraph(Vec::new())); + } + items.push(blocks); + } + _ => *pos += 1, + } + } + out.push(Block::List { + ordered: start.is_some(), + start: (*start).unwrap_or(1) as i64, + items, + }); + } + Event::Start(Tag::Table(_)) => { + *pos += 1; + parse_table(ev, pos, &mut out); + } + Event::Start(Tag::Item) => { + // Item outside a list: keep its content. + *pos += 1; + out.extend(parse_blocks(ev, pos, true)); + } + Event::Rule => { + out.push(Block::Rule); + *pos += 1; + } + // Inline content outside a paragraph (tight list items, table-less + // loose text): wrap the run in a paragraph. + Event::Text(_) + | Event::Code(_) + | Event::SoftBreak + | Event::HardBreak + | Event::InlineHtml(_) + | Event::Html(_) + | Event::TaskListMarker(_) + | Event::FootnoteReference(_) + | Event::InlineMath(_) + | Event::DisplayMath(_) + | Event::Start( + Tag::Emphasis + | Tag::Strong + | Tag::Strikethrough + | Tag::Superscript + | Tag::Subscript + | Tag::Link { .. } + | Tag::Image { .. }, + ) => { + let inl = inlines(ev, pos); + if !is_blank(&inl) { + out.push(Block::Paragraph(inl)); + } + } + // Unknown containers (footnote definitions, metadata, ...): keep content. + Event::Start(_) => { + *pos += 1; + out.extend(parse_blocks(ev, pos, true)); + } + } + } + out +} + +/// Tables: each row becomes a paragraph with cells joined by " | ". +/// Assumes `pos` is just past `Start(Table)`; consumes the table's End. +fn parse_table(ev: &[Event<'_>], pos: &mut usize, out: &mut Vec<Block>) { + while let Some(e) = ev.get(*pos) { + match e { + Event::End(_) => { + *pos += 1; + break; + } + Event::Start(Tag::TableHead | Tag::TableRow) => { + *pos += 1; + let mut cells = Vec::new(); + while let Some(c) = ev.get(*pos) { + match c { + Event::End(_) => { + *pos += 1; + break; + } + Event::Start(Tag::TableCell) => { + *pos += 1; + let mut inl = Vec::new(); + parse_inlines(ev, pos, &Marks::default(), &mut inl, true); + cells.push(inl); + } + _ => *pos += 1, + } + } + out.extend(table_row(cells)); + } + _ => *pos += 1, + } + } +} + +fn table_row(cells: Vec<Vec<Inline>>) -> Option<Block> { + let mut inl = Vec::new(); + for (i, cell) in cells.into_iter().enumerate() { + if i > 0 { + inl.push(Inline::Text(" | ".to_owned(), Marks::default())); + } + inl.extend(cell); + } + if is_blank(&inl) { + None + } else { + Some(Block::Paragraph(inl)) + } +} + +fn inlines(ev: &[Event<'_>], pos: &mut usize) -> Vec<Inline> { + let mut out = Vec::new(); + parse_inlines(ev, pos, &Marks::default(), &mut out, false); + out +} + +/// Collects inline content. With `closing`, it also consumes the End event that +/// closes the current inline span. Without it, it stops before the first +/// non-inline event (the caller handles that event). +fn parse_inlines( + ev: &[Event<'_>], + pos: &mut usize, + marks: &Marks, + out: &mut Vec<Inline>, + closing: bool, +) { + while let Some(event) = ev.get(*pos) { + match event { + Event::End(_) => { + if closing { + *pos += 1; + } + return; + } + Event::Text(s) + | Event::Html(s) + | Event::InlineHtml(s) + | Event::InlineMath(s) + | Event::DisplayMath(s) => { + out.push(Inline::Text(s.to_string(), marks.clone())); + *pos += 1; + } + Event::FootnoteReference(s) => { + out.push(Inline::Text(format!("[^{s}]"), marks.clone())); + *pos += 1; + } + Event::Code(s) => { + let mut m = marks.clone(); + m.code = true; + out.push(Inline::Text(s.to_string(), m)); + *pos += 1; + } + Event::SoftBreak => { + out.push(Inline::Text(" ".to_owned(), marks.clone())); + *pos += 1; + } + Event::HardBreak => { + out.push(Inline::HardBreak); + *pos += 1; + } + Event::TaskListMarker(done) => { + let s = if *done { "[x] " } else { "[ ] " }; + out.push(Inline::Text(s.to_owned(), Marks::default())); + *pos += 1; + } + Event::Start(Tag::Emphasis) => { + *pos += 1; + let mut m = marks.clone(); + m.em = true; + parse_inlines(ev, pos, &m, out, true); + } + Event::Start(Tag::Strong) => { + *pos += 1; + let mut m = marks.clone(); + m.strong = true; + parse_inlines(ev, pos, &m, out, true); + } + // Degraded: content kept, no mark. + Event::Start(Tag::Strikethrough | Tag::Superscript | Tag::Subscript) => { + *pos += 1; + parse_inlines(ev, pos, marks, out, true); + } + Event::Start(Tag::Link { + dest_url, title, .. + }) => { + *pos += 1; + let mut m = marks.clone(); + let title = (!title.is_empty()).then(|| title.to_string()); + m.link = Some((note_file_href(&dest_url), title)); + parse_inlines(ev, pos, &m, out, true); + } + Event::Start(Tag::Image { + dest_url, title, .. + }) => { + *pos += 1; + let mut alt = Vec::new(); + parse_inlines(ev, pos, marks, &mut alt, true); + let title = (!title.is_empty()).then(|| title.to_string()); + out.push(Inline::Image { + src: dest_url.to_string(), + alt: plain(&alt), + title, + }); + } + // Block-level event: the inline run ends here. + _ => return, + } + } +} + +fn skip_end(ev: &[Event<'_>], pos: &mut usize) { + if matches!(ev.get(*pos), Some(Event::End(_))) { + *pos += 1; + } +} + +fn is_blank(inl: &[Inline]) -> bool { + inl.iter() + .all(|i| matches!(i, Inline::Text(s, _) if s.trim().is_empty())) +} + +fn plain(inl: &[Inline]) -> String { + inl.iter() + .map(|i| match i { + Inline::Text(s, _) => s.as_str(), + Inline::HardBreak => " ", + Inline::Image { alt, .. } => alt.as_str(), + }) + .collect() +} + +fn heading_level(level: HeadingLevel) -> i64 { + match level { + HeadingLevel::H1 => 1, + HeadingLevel::H2 => 2, + HeadingLevel::H3 => 3, + HeadingLevel::H4 => 4, + HeadingLevel::H5 => 5, + HeadingLevel::H6 => 6, + } +} + +// --------------------------------------------------------------------------- +// Tree -> LoroDoc +// --------------------------------------------------------------------------- + +/// Builds the document. Mirrors `hub::initial_note_update`: an empty input +/// yields a single empty paragraph. +fn build(blocks: &[Block]) -> Result<LoroDoc> { + let doc = LoroDoc::new(); + + // Same expand rules as loro-prosemirror's getLoroTextStyle. + let mut styles = StyleConfigMap::new(); + styles.insert( + "strong".into(), + StyleConfig::new().expand(ExpandType::After), + ); + styles.insert("em".into(), StyleConfig::new().expand(ExpandType::After)); + styles.insert("code".into(), StyleConfig::new().expand(ExpandType::After)); + styles.insert("link".into(), StyleConfig::new().expand(ExpandType::None)); + doc.config_text_style(styles); + + let root = doc.get_map("doc"); + root.insert("nodeName", "doc")?; + root.insert_container("attributes", LoroMap::new())?; + let children = root.insert_container("children", LoroList::new())?; + if blocks.is_empty() { + push_node(&children, "paragraph", Vec::new())?; + } else { + for block in blocks { + write_block(&children, block)?; + } + } + doc.commit(); + Ok(doc) +} + +/// Appends a node to `list` and returns its `children` list. Null attributes +/// are not written. +fn push_node(list: &LoroList, name: &str, attrs: Vec<(&str, LoroValue)>) -> LoroResult<LoroList> { + let node = list.push_container(LoroMap::new())?; + node.insert("nodeName", name)?; + let attributes = node.insert_container("attributes", LoroMap::new())?; + for (key, value) in attrs { + attributes.insert(key, value)?; + } + node.insert_container("children", LoroList::new()) +} + +fn write_block(list: &LoroList, block: &Block) -> LoroResult<()> { + match block { + Block::Paragraph(inl) => { + let children = push_node(list, "paragraph", Vec::new())?; + write_inlines(&children, inl)?; + } + Block::Heading(level, inl) => { + let children = push_node(list, "heading", vec![("level", (*level).into())])?; + write_inlines(&children, inl)?; + } + Block::Quote(blocks) => { + let children = push_node(list, "blockquote", Vec::new())?; + for b in blocks { + write_block(&children, b)?; + } + } + Block::Code { lang, text } => { + let attrs: Vec<(&str, LoroValue)> = lang + .iter() + .map(|l| ("language", LoroValue::from(l.as_str()))) + .collect(); + let children = push_node(list, "code_block", attrs)?; + if !text.is_empty() { + let t = children.push_container(LoroText::new())?; + t.insert(0, text)?; + } + } + Block::Rule => { + push_node(list, "horizontal_rule", Vec::new())?; + } + Block::List { + ordered, + start, + items, + } => { + let children = if *ordered { + push_node(list, "ordered_list", vec![("order", (*start).into())])? + } else { + push_node(list, "bullet_list", Vec::new())? + }; + for item in items { + let item_children = push_node(&children, "list_item", Vec::new())?; + for b in item { + write_block(&item_children, b)?; + } + } + } + } + Ok(()) +} + +/// Consecutive text runs share one LoroText; inline nodes get their own child. +fn write_inlines(list: &LoroList, inl: &[Inline]) -> LoroResult<()> { + let owned = wikilinks(inl); + let inl = owned.as_slice(); + let mut i = 0; + while let Some(item) = inl.get(i) { + match item { + Inline::Text(..) => { + let mut j = i; + let mut full = String::new(); + let mut spans: Vec<(std::ops::Range<usize>, Marks)> = Vec::new(); + while let Some(Inline::Text(s, m)) = inl.get(j) { + let start = full.chars().count(); + full.push_str(s); + let end = full.chars().count(); + if end > start { + spans.push((start..end, m.clone())); + } + j += 1; + } + if !full.is_empty() { + let text = list.push_container(LoroText::new())?; + text.insert(0, &full)?; + for (range, marks) in spans { + apply_marks(&text, range, &marks)?; + } + } + i = j; + } + Inline::HardBreak => { + push_node(list, "hard_break", Vec::new())?; + i += 1; + } + Inline::Image { src, alt, title } => { + let mut attrs: Vec<(&str, LoroValue)> = + vec![("src", LoroValue::from(src.as_str())), ("alt", LoroValue::from(alt.as_str()))]; + if let Some(t) = title { + attrs.push(("title", LoroValue::from(t.as_str()))); + } + push_node(list, "image", attrs)?; + i += 1; + } + } + } + Ok(()) +} + +/// Turns `[[Title]]`, `[[Title|text]]` and `[[Title#heading]]` in plain text into links +/// to `/notes/by-title/<Title>`, showing the text (or the title). Code, existing links and +/// embeds (`![[...]]`, kept as text) are left alone. +fn wikilinks(inl: &[Inline]) -> Vec<Inline> { + // Adjacent runs with the same marks are joined first, since a `[[` can be split + // across parser events. + let mut merged: Vec<Inline> = Vec::new(); + for item in inl { + if let Inline::Text(s, m) = item { + if let Some(Inline::Text(prev, pm)) = merged.last_mut() { + if *pm == *m { + prev.push_str(s); + continue; + } + } + } + merged.push(item.clone()); + } + + let mut out = Vec::with_capacity(merged.len()); + for item in merged { + match item { + Inline::Text(s, m) if !m.code && m.link.is_none() => split_wikilinks(&s, &m, &mut out), + other => out.push(other), + } + } + out +} + +fn split_wikilinks(s: &str, marks: &Marks, out: &mut Vec<Inline>) { + let mut rest = s; + while let Some(open) = rest.find("[[") { + let after = &rest[open + 2..]; + let embed = rest[..open].ends_with('!'); + let parsed = after + .find("]]") + .and_then(|close| wikilink_parts(&after[..close]).map(|parts| (close, parts))); + match parsed { + Some((close, (target, text))) if !embed => { + push_text(out, &rest[..open], marks); + let href = format!("/notes/by-title/{}", crate::export::percent_encode(&target)); + let link = Marks { + link: Some((href, None)), + ..marks.clone() + }; + out.push(Inline::Text(text, link)); + rest = &after[close + 2..]; + } + _ => { + push_text(out, &rest[..open + 2], marks); + rest = after; + } + } + } + push_text(out, rest, marks); +} + +fn push_text(out: &mut Vec<Inline>, s: &str, marks: &Marks) { + if !s.is_empty() { + out.push(Inline::Text(s.to_owned(), marks.clone())); + } +} + +/// The target title and the shown text of a wiki link's inside. The heading part of +/// the target is dropped, and the text falls back to the target. +fn wikilink_parts(inner: &str) -> Option<(String, String)> { + if inner.contains(['\n', '[', ']']) { + return None; + } + let (target_part, alias) = match inner.split_once('|') { + Some((target, alias)) => (target, Some(alias.trim())), + None => (inner, None), + }; + let target = target_part.split('#').next().unwrap_or_default().trim(); + if target.is_empty() { + return None; + } + let text = match alias { + Some(alias) if !alias.is_empty() => alias, + _ => target, + }; + Some((target.to_owned(), text.to_owned())) +} + +fn apply_marks(text: &LoroText, range: std::ops::Range<usize>, marks: &Marks) -> LoroResult<()> { + if marks.strong { + text.mark(range.clone(), "strong", empty_map())?; + } + if marks.em { + text.mark(range.clone(), "em", empty_map())?; + } + if marks.code { + text.mark(range.clone(), "code", empty_map())?; + } + if let Some((href, title)) = &marks.link { + let mut map: HashMap<String, LoroValue> = HashMap::new(); + map.insert("href".to_owned(), LoroValue::from(href.as_str())); + let title_value = match title { + Some(t) => LoroValue::from(t.as_str()), + None => LoroValue::Null, + }; + map.insert("title".to_owned(), title_value); + text.mark(range, "link", LoroValue::from(map))?; + } + Ok(()) +} + +fn empty_map() -> LoroValue { + LoroValue::from(HashMap::<String, LoroValue>::new()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const SAMPLE: &str = r#"# Title + +Some **bold**, *italic*, `code` and [link](https://example.com "Example"). + +- Bullet one + - Nested bullet +- Bullet two + +1. First +2. Second + +> A quoted line + +```rust +fn main() {} +``` + +--- + +![A cat](https://example.com/cat.png) + +line one\ +line two +"#; + + #[test] + fn round_trip_and_front_matter() { + let doc = markdown_to_doc(SAMPLE).unwrap(); + assert_eq!(crate::export::to_markdown(&doc), SAMPLE); + + let with_front_matter = format!("---\ntitle: Test\ntags: [a]\n---\n\n{SAMPLE}"); + let doc = markdown_to_doc(&with_front_matter).unwrap(); + assert_eq!(crate::export::to_markdown(&doc), SAMPLE); + + let wiki = "See **[[Alpha]]**, [**Be**ta](My%20Beta.md) and [[Gamma|g]].\n"; + let doc = markdown_to_doc(wiki).unwrap(); + assert_eq!(crate::export::to_markdown_with(&doc, &|_| None), wiki); + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..d110f01 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,46 @@ +mod app; +mod components; +mod export; +mod hub; +mod i18n; +mod matcher; +mod import; +mod scheme; +mod store; + +use std::sync::Arc; +use std::time::Duration; + +/// Notes stay in the trash this long before they are deleted for good. +const TRASH_RETENTION_MS: i64 = 30 * 24 * 60 * 60 * 1000; +/// How often expired trash is purged. +const PURGE_EVERY: Duration = Duration::from_secs(60 * 60); + +/// Deletes notes that have been in the trash for 30 days, hourly, and drops their live +/// rooms. The first run happens at startup. +fn spawn_trash_purge(store: Arc<store::Store>, hub: Arc<hub::Hub>) { + tokio::spawn(async move { + let mut tick = tokio::time::interval(PURGE_EVERY); + loop { + tick.tick().await; + match store.purge_trash(TRASH_RETENTION_MS).await { + Ok(ids) => { + for id in ids { + hub.forget(&id); + } + } + Err(err) => eprintln!("trash purge failed: {err:#}"), + } + } + }); +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let db_path = std::env::var("NOTE_DB").unwrap_or_else(|_| "notes.db".to_owned()); + let store = Arc::new(store::Store::open(&db_path).await?); + let hub = Arc::new(hub::Hub::new()); + spawn_trash_purge(store.clone(), hub.clone()); + topcoat::start(app::router(store, hub)).await?; + Ok(()) +} diff --git a/src/matcher.rs b/src/matcher.rs new file mode 100644 index 0000000..be10cd3 --- /dev/null +++ b/src/matcher.rs @@ -0,0 +1,320 @@ +//! Matching a search query against note text: case and Turkish-letter folding, typo +//! tolerance, and the search filters (match case, whole word, exact phrase, regex). +//! +//! Positions are char indices into the original text. Folding maps one char to one +//! char, so they line up. + +use regex::{Regex, RegexBuilder}; + +/// Most words used from one query; longer queries are cut down. +const MAX_TERMS: usize = 16; +/// Longest word kept from a query. +const MAX_TERM_CHARS: usize = 64; +/// Longest query kept as an exact phrase or a regular expression. +const MAX_PATTERN_CHARS: usize = 256; + +/// The search filters. All off is the forgiving default: any case, Turkish letters as +/// plain ones, inside words, typos allowed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Options { + /// Letters must match in case (and Turkish letters exactly). + pub case: bool, + /// Matches must be whole words. + pub word: bool, + /// The query is one phrase, matched as written. No typos. + pub exact: bool, + /// The query is a regular expression. + pub regex: bool, +} + +impl Options { + /// Typos are only forgiven with every filter off; any filter asks for precision. + fn typos(self) -> bool { + !(self.case || self.word || self.exact) + } +} + +/// A compiled query. +pub enum Matcher { + Terms { terms: Vec<Vec<char>>, opts: Options }, + Regex(Regex), +} + +/// The query is not a valid regular expression. +#[derive(Debug)] +pub struct InvalidRegex; + +impl Matcher { + /// None when the query holds nothing to search for. + pub fn new(query: &str, opts: Options) -> Result<Option<Self>, InvalidRegex> { + let query = query.trim(); + if query.is_empty() { + return Ok(None); + } + if opts.regex { + let pattern: String = query.chars().take(MAX_PATTERN_CHARS).collect(); + let pattern = if opts.word { + format!(r"\b(?:{pattern})\b") + } else { + pattern + }; + return RegexBuilder::new(&pattern) + .case_insensitive(!opts.case) + .size_limit(1 << 20) + .build() + .map(|re| Some(Self::Regex(re))) + .map_err(|_| InvalidRegex); + } + let fold = |c: char| if opts.case { c } else { match_fold(c) }; + let mut terms: Vec<Vec<char>> = if opts.exact { + let phrase = query.split_whitespace().collect::<Vec<_>>().join(" "); + vec![phrase.chars().take(MAX_PATTERN_CHARS).map(fold).collect()] + } else { + query + .split(|c: char| !c.is_alphanumeric()) + .filter(|w| !w.is_empty()) + .map(|w| w.chars().take(MAX_TERM_CHARS).map(fold).collect()) + .collect() + }; + terms.sort(); + terms.dedup(); + terms.truncate(MAX_TERMS); + Ok((!terms.is_empty()).then_some(Self::Terms { terms, opts })) + } + + /// The default matcher for `query`, as the palette and `[[` use it. + pub fn simple(query: &str) -> Option<Self> { + Self::new(query, Options::default()).ok().flatten() + } + + /// The cheapest match of each term in `text`, by term (None where it doesn't occur). + /// See [`occurrences`] for costs. + pub fn term_costs(&self, text: &str) -> Vec<Option<usize>> { + match self { + Self::Terms { terms, opts } => { + let hay = fold_text(text, *opts); + terms + .iter() + .map(|t| occurrences(&hay, t, *opts).into_iter().map(|o| o.2).min()) + .collect() + } + Self::Regex(re) => vec![re.find_iter(text).any(|m| !m.is_empty()).then_some(0)], + } + } + + /// The summed cost of every term in `text`, or None if some term doesn't occur. + pub fn cost(&self, text: &str) -> Option<usize> { + self.term_costs(text).into_iter().sum() + } + + /// Char ranges `(start, end)` of the matches in `text`, merged and sorted. + pub fn ranges(&self, text: &str) -> Vec<(usize, usize)> { + let mut ranges: Vec<(usize, usize)> = match self { + Self::Terms { terms, opts } => { + let hay = fold_text(text, *opts); + terms + .iter() + .flat_map(|t| occurrences(&hay, t, *opts)) + .map(|(s, e, _)| (s, e)) + .collect() + } + Self::Regex(re) => { + // Byte offsets to char indices. + let mut ranges = Vec::new(); + for m in re.find_iter(text).filter(|m| !m.is_empty()) { + let start = text[..m.start()].chars().count(); + ranges.push((start, start + m.as_str().chars().count())); + } + ranges + } + }; + ranges.sort_unstable(); + let mut merged: Vec<(usize, usize)> = Vec::new(); + for (start, end) in ranges { + match merged.last_mut() { + Some(last) if start <= last.1 => last.1 = last.1.max(end), + _ => merged.push((start, end)), + } + } + merged + } +} + +/// Lowercase form of one char. +fn fold(c: char) -> char { + c.to_lowercase().next().unwrap_or(c) +} + +/// One char as the default search compares it: lowercase, Turkish letters as plain ones. +fn match_fold(c: char) -> char { + match fold(c) { + 'ı' => 'i', + 'ş' => 's', + 'ğ' => 'g', + 'ç' => 'c', + 'ö' => 'o', + 'ü' => 'u', + c => c, + } +} + +/// A title folded for matching: lowercase, with Turkish letters as their plain forms, +/// so "izmir" finds "İzmir" and "isik", "ışık" and "Işık" find each other. +pub fn title_fold(title: &str) -> String { + title.chars().map(match_fold).collect() +} + +fn fold_text(text: &str, opts: Options) -> Vec<char> { + if opts.case { + text.chars().collect() + } else { + text.chars().map(match_fold).collect() + } +} + +/// Typos a term of `len` chars may have and still match: none up to 4 chars (except one +/// swap of neighbours, see [`occurrences`]), one up to 8, two beyond. Short words with any +/// other typo match too much else. +fn max_typos(len: usize) -> usize { + match len { + 0..=4 => 0, + 5..=8 => 1, + _ => 2, + } +} + +/// Where `term` occurs in `hay` (both already folded). Exact occurrences (whole words +/// only with `opts.word`), or, when there are none and typos are allowed, word +/// beginnings within [`max_typos`] edits of the term (insertions, deletions, +/// substitutions and swapped neighbours). The `usize` is the match's cost: 0 exact at a +/// word start, 1 exact inside a word, 1 + typos otherwise. +fn occurrences(hay: &[char], term: &[char], opts: Options) -> Vec<(usize, usize, usize)> { + let n = term.len(); + if n == 0 { + return Vec::new(); + } + let word_start = |i: usize| i == 0 || !hay[i - 1].is_alphanumeric(); + let word_end = |i: usize| i == hay.len() || !hay[i].is_alphanumeric(); + let mut found = Vec::new(); + if n <= hay.len() { + for start in 0..=hay.len() - n { + let end = start + n; + if hay[start..end] != term[..] { + continue; + } + if opts.word && !(word_start(start) && word_end(end)) { + continue; + } + found.push((start, end, usize::from(!word_start(start)))); + } + } + if !found.is_empty() || !opts.typos() { + return found; + } + let d = max_typos(n); + // Short words only forgive swapped neighbours: "mlik" finds "milk". + let swap_only = d == 0; + if swap_only && n < 3 { + return found; + } + let mut i = 0; + while i < hay.len() { + if !hay[i].is_alphanumeric() { + i += 1; + continue; + } + let mut end = i; + while end < hay.len() && hay[end].is_alphanumeric() { + end += 1; + } + if swap_only { + let word = &hay[i..end]; + let swapped = word.len() >= n + && (1..n).any(|k| { + word[k - 1] == term[k] + && word[k] == term[k - 1] + && term[k] != term[k - 1] + && (0..n).all(|x| x == k || x == k - 1 || word[x] == term[x]) + }); + if swapped { + found.push((i, i + n, 2)); + } + } else if let Some((typos, len)) = prefix_distance(term, &hay[i..end.min(i + n + d)], d) { + found.push((i, i + len, 1 + typos)); + } + i = end; + } + found +} + +/// The fewest edits turning `term` into some prefix of `word`, and that prefix's length, +/// if at most `max`. Optimal string alignment distance, so a swap counts as one edit. +fn prefix_distance(term: &[char], word: &[char], max: usize) -> Option<(usize, usize)> { + let (n, m) = (term.len(), word.len()); + if m + max < n { + return None; + } + let mut d = vec![vec![0usize; m + 1]; n + 1]; + for (i, row) in d.iter_mut().enumerate() { + row[0] = i; + } + for j in 0..=m { + d[0][j] = j; + } + for i in 1..=n { + for j in 1..=m { + let cost = usize::from(term[i - 1] != word[j - 1]); + let mut v = (d[i - 1][j] + 1).min(d[i][j - 1] + 1).min(d[i - 1][j - 1] + cost); + if i > 1 && j > 1 && term[i - 1] == word[j - 2] && term[i - 2] == word[j - 1] { + v = v.min(d[i - 2][j - 2] + 1); + } + d[i][j] = v; + } + } + (n.saturating_sub(max).max(1)..=m) + .map(|j| (d[n][j], j)) + .min_by_key(|&(dist, j)| (dist, j.abs_diff(n))) + .filter(|&(dist, _)| dist <= max) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cost(text: &str, q: &str, opts: Options) -> Option<usize> { + Matcher::new(q, opts).unwrap().unwrap().cost(text) + } + + #[test] + fn typo_tolerance() { + let d = Options::default(); + assert_eq!(cost("Groceries list", "groc", d), Some(0)); + assert_eq!(cost("Groceries list", "grcoeries", d), Some(2)); // swapped letters + assert_eq!(cost("Groceries list", "grocerues", d), Some(2)); // one substitution + assert_eq!(cost("Project kickoff", "porject kikcoff", d), Some(4)); + assert_eq!(cost("İzmir gezisi", "izmr", d), None); // 4 chars: only a swap + assert_eq!(cost("Plan", "plna", d), Some(2)); + assert_eq!(cost("Plan", "plen", d), None); + assert_eq!(cost("Işık listesi", "isik listsi", d), Some(2)); + } + + #[test] + fn filters() { + let case = Options { case: true, ..Default::default() }; + let word = Options { word: true, ..Default::default() }; + let exact = Options { exact: true, ..Default::default() }; + let regex = Options { regex: true, ..Default::default() }; + assert_eq!(cost("Groceries", "groceries", case), None); + assert_eq!(cost("Groceries", "Groceries", case), Some(0)); + assert_eq!(cost("Groceries", "Groc", word), None); + assert_eq!(cost("milk, eggs", "milk", word), Some(0)); + assert_eq!(cost("buy milk and eggs", "milk eggs", exact), None); + assert_eq!(cost("buy milk and eggs", "milk and", exact), None); // text not collapsed + assert_eq!(cost("buy milk and eggs", "MILK AND", exact), Some(0)); + assert_eq!(cost("Groceries", "grcoeries", exact), None); // no typos + assert_eq!(cost("order #42", r"#\d+", regex), Some(0)); + assert!(Matcher::new("(", regex).is_err()); + let m = Matcher::new("ş", Options::default()).unwrap().unwrap(); + assert_eq!(m.ranges("Işık"), vec![(1, 2)]); + } +} diff --git a/src/scheme.rs b/src/scheme.rs new file mode 100644 index 0000000..f8e8b91 --- /dev/null +++ b/src/scheme.rs @@ -0,0 +1,117 @@ +//! Color schemes: the nine palettes the user can pick, the cookie that remembers the +//! choice, and the swatch colors the picker shows. The palettes themselves are CSS +//! custom properties in `styles.css`, keyed by `<html data-scheme="...">`. + +use topcoat::{ + context::Cx, + cookie::{Cookie, Cookies, SameSite, cookies, time::Duration}, +}; + +/// Name of the cookie that stores the color scheme. +pub const SCHEME_COOKIE: &str = "scheme"; + +/// How long the color scheme choice is remembered. +pub const SCHEME_COOKIE_DAYS: i64 = 365; + +/// A color scheme. Each one is a palette of light and dark tokens in `styles.css`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Scheme { + Graphite, + Cobalt, + Oxblood, + Teal, + Plum, + Mono, + Tangerine, + Sage, + Spark, +} + +/// Every scheme, in the order the picker lists them. +pub const ALL: [Scheme; 9] = [ + Scheme::Graphite, + Scheme::Cobalt, + Scheme::Oxblood, + Scheme::Teal, + Scheme::Plum, + Scheme::Mono, + Scheme::Tangerine, + Scheme::Sage, + Scheme::Spark, +]; + +/// The scheme used when no valid cookie is set. +pub const DEFAULT: Scheme = Scheme::Sage; + +impl Scheme { + /// The value stored in the cookie and in `data-scheme` on `<html>`. + pub fn id(self) -> &'static str { + match self { + Self::Graphite => "graphite", + Self::Cobalt => "cobalt", + Self::Oxblood => "oxblood", + Self::Teal => "teal", + Self::Plum => "plum", + Self::Mono => "mono", + Self::Tangerine => "tangerine", + Self::Sage => "sage", + Self::Spark => "spark", + } + } + + /// Parses a cookie or form value. Returns `None` for unknown schemes. + pub fn from_id(id: &str) -> Option<Self> { + ALL.into_iter().find(|s| s.id() == id) + } + + /// The proper name of the scheme. Names are not translated. + pub fn name(self) -> &'static str { + match self { + Self::Graphite => "Graphite & Highlighter", + Self::Cobalt => "Cobalt Ink", + Self::Oxblood => "Oxblood", + Self::Teal => "Teal Ledger", + Self::Plum => "Plum", + Self::Mono => "Monochrome", + Self::Tangerine => "Tangerine", + Self::Sage => "Sage", + Self::Spark => "Spark", + } + } + + /// Three swatch colors as `(light, dark)` pairs: the sidebar, the accent, and the + /// active row. The picker draws them as dots. + pub fn dots(self) -> [(&'static str, &'static str); 3] { + match self { + // @dots:begin + Self::Graphite => [("#eceef2", "#1d2026"), ("#f2b600", "#ffc93c"), ("#ffe08a", "#5c4700")], + Self::Cobalt => [("#eef3fb", "#121a2c"), ("#1f4fd1", "#5b8bff"), ("#dce7ff", "#1d2f5c")], + Self::Oxblood => [("#eeeae8", "#1c1818"), ("#8e1b22", "#d85c63"), ("#f8dcd9", "#4a1d21")], + Self::Teal => [("#e8f0f0", "#121d1c"), ("#0f5e5a", "#3fb3a6"), ("#cdeee9", "#15403b")], + Self::Plum => [("#efeaf3", "#1a1620"), ("#7b2d6e", "#d27ac4"), ("#f1d9ee", "#4a2446")], + Self::Mono => [("#f0f0f0", "#161616"), ("#111111", "#f2f2f2"), ("#e4e4e4", "#2e2e2e")], + Self::Tangerine => [("#eceef0", "#16191c"), ("#f59e0b", "#ffb347"), ("#fde9c4", "#4f3412")], + Self::Sage => [("#e9efe6", "#111211"), ("#567752", "#4a6847"), ("#d9ebd3", "#233024")], + Self::Spark => [("#eeeef0", "#1a1512"), ("#ff8205", "#ff9a2e"), ("#ffe8c7", "#58320a")], + // @dots:end + } + } +} + +/// The scheme of this request. The `scheme` cookie wins; an unknown or missing value +/// means the default. +pub fn scheme(cx: &Cx) -> Scheme { + cookies(cx) + .get(SCHEME_COOKIE) + .and_then(|cookie| Scheme::from_id(cookie.value())) + .unwrap_or(DEFAULT) +} + +/// The cookie that remembers `scheme` for a year. +pub fn scheme_cookie(scheme: Scheme) -> Cookie<'static> { + Cookie::build((SCHEME_COOKIE, scheme.id())) + .path("/") + .same_site(SameSite::Lax) + .max_age(Duration::days(SCHEME_COOKIE_DAYS)) + .build() +} diff --git a/src/store.rs b/src/store.rs new file mode 100644 index 0000000..3956b68 --- /dev/null +++ b/src/store.rs @@ -0,0 +1,976 @@ +//! Persistence. The only module that talks to turso. + +use std::collections::HashMap; +use std::time::{SystemTime, UNIX_EPOCH}; + +use anyhow::{Context, anyhow}; + +use crate::matcher::Matcher; +use tokio::sync::Mutex; + +use crate::export::LinkTarget; + +pub struct NoteMeta { + pub id: String, + pub title: String, + pub created_at: i64, + pub updated_at: i64, + /// `None` when the note is not in any notebook. + pub notebook_id: Option<String>, + /// `None` when the note is not in the trash. Millis when it was trashed. + pub trashed_at: Option<i64>, +} + +pub struct Notebook { + pub id: String, + pub name: String, + pub created_at: i64, +} + +/// Snapshot (if any) plus every update stored after it, in insertion order. +pub struct DocBytes { + pub snapshot: Option<Vec<u8>>, + pub updates: Vec<Vec<u8>>, +} + +pub struct Store { + /// Single connection shared by all tasks. Calls are serialized by the mutex, + /// which also keeps transactions from interleaving on one connection. + conn: Mutex<turso::Connection>, + /// Keeps the database handle alive for as long as the connection is used. + _db: turso::Database, +} + +pub(crate) fn now_millis() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0) +} + +/// The form of a title that links match on: whitespace collapsed and lowercased. +pub fn title_key(title: &str) -> String { + title + .split_whitespace() + .collect::<Vec<_>>() + .join(" ") + .to_lowercase() +} + +fn text_col(row: &turso::Row, idx: usize) -> anyhow::Result<String> { + match row.get_value(idx)? { + turso::Value::Text(s) => Ok(s), + other => Err(anyhow!("column {idx}: expected TEXT, got {other:?}")), + } +} + +fn opt_text_col(row: &turso::Row, idx: usize) -> anyhow::Result<Option<String>> { + match row.get_value(idx)? { + turso::Value::Null => Ok(None), + turso::Value::Text(s) => Ok(Some(s)), + other => Err(anyhow!("column {idx}: expected TEXT or NULL, got {other:?}")), + } +} + +fn int_col(row: &turso::Row, idx: usize) -> anyhow::Result<i64> { + match row.get_value(idx)? { + turso::Value::Integer(i) => Ok(i), + other => Err(anyhow!("column {idx}: expected INTEGER, got {other:?}")), + } +} + +fn opt_int_col(row: &turso::Row, idx: usize) -> anyhow::Result<Option<i64>> { + match row.get_value(idx)? { + turso::Value::Null => Ok(None), + turso::Value::Integer(i) => Ok(Some(i)), + other => Err(anyhow!("column {idx}: expected INTEGER or NULL, got {other:?}")), + } +} + +fn blob_col(row: &turso::Row, idx: usize) -> anyhow::Result<Vec<u8>> { + match row.get_value(idx)? { + turso::Value::Blob(b) => Ok(b), + other => Err(anyhow!("column {idx}: expected BLOB, got {other:?}")), + } +} + +fn note_from_row(row: &turso::Row) -> anyhow::Result<NoteMeta> { + Ok(NoteMeta { + id: text_col(row, 0)?, + title: text_col(row, 1)?, + created_at: int_col(row, 2)?, + updated_at: int_col(row, 3)?, + notebook_id: opt_text_col(row, 4)?, + trashed_at: opt_int_col(row, 5)?, + }) +} + +/// Deletes one note's rows inside an open transaction. +async fn delete_note_rows( + tx: &turso::transaction::Transaction<'_>, + note_id: &str, +) -> anyhow::Result<()> { + tx.execute("DELETE FROM updates WHERE note_id = ?1", (note_id.to_string(),)) + .await?; + tx.execute("DELETE FROM snapshots WHERE note_id = ?1", (note_id.to_string(),)) + .await?; + tx.execute("DELETE FROM note_text WHERE note_id = ?1", (note_id.to_string(),)) + .await?; + tx.execute("DELETE FROM note_versions WHERE note_id = ?1", (note_id.to_string(),)) + .await?; + tx.execute("DELETE FROM note_links WHERE src = ?1", (note_id.to_string(),)) + .await?; + tx.execute("DELETE FROM notes WHERE id = ?1", (note_id.to_string(),)) + .await?; + Ok(()) +} + +fn notebook_from_row(row: &turso::Row) -> anyhow::Result<Notebook> { + Ok(Notebook { + id: text_col(row, 0)?, + name: text_col(row, 1)?, + created_at: int_col(row, 2)?, + }) +} + +/// A note matched by [`Store::search`], with a plain-text excerpt of its body. +pub struct SearchHit { + pub note: NoteMeta, + pub snippet: String, +} + +/// Characters of body text shown around the first match. +const SNIPPET_CHARS: usize = 160; +/// Characters of body text shown as a note's preview in a list. +const PREVIEW_CHARS: usize = 140; +/// Markdown as plain text. Code fences are dropped, block markers (headings, quotes, +/// list and task markers, rules) and inline syntax (emphasis, code spans, escapes) are +/// removed, link and image text is kept, and lines are joined with single spaces. +fn plain_text(markdown: &str) -> String { + let mut lines: Vec<String> = Vec::new(); + let mut in_fence = false; + for line in markdown.lines() { + let trimmed = line.trim(); + if trimmed.starts_with("```") || trimmed.starts_with("~~~") { + in_fence = !in_fence; + continue; + } + let text = if in_fence { + trimmed.to_owned() + } else { + strip_inline(strip_block(trimmed)) + }; + if !text.trim().is_empty() { + lines.push(text); + } + } + lines.join(" ").split_whitespace().collect::<Vec<_>>().join(" ") +} + +/// Removes the block syntax at the start of one trimmed line: quote marks, heading +/// hashes, list and task markers, and thematic breaks. +fn strip_block(line: &str) -> &str { + let mut s = line; + if s.len() >= 3 && s.chars().all(|c| matches!(c, '-' | '*' | '_' | ' ')) { + return ""; + } + while let Some(rest) = s.strip_prefix('>') { + s = rest.trim_start(); + } + let hashes = s.len() - s.trim_start_matches('#').len(); + if hashes > 0 && (hashes == s.len() || s[hashes..].starts_with(' ')) { + s = s[hashes..].trim_start(); + } + if let Some(rest) = s.strip_prefix(['-', '*', '+']) { + if rest.is_empty() || rest.starts_with(' ') { + s = rest.trim_start(); + } + } + let digits = s.len() - s.trim_start_matches(|c: char| c.is_ascii_digit()).len(); + if digits > 0 { + if let Some(rest) = s[digits..].strip_prefix(['.', ')']) { + if rest.is_empty() || rest.starts_with(' ') { + s = rest.trim_start(); + } + } + } + for checkbox in ["[ ]", "[x]", "[X]"] { + if let Some(rest) = s.strip_prefix(checkbox) { + s = rest.trim_start(); + break; + } + } + s +} + +/// Removes inline syntax from one line: `[text](url)` and `![alt](url)` become their +/// text, emphasis and code markers are dropped, `_` is kept inside words only, and a +/// backslash escape yields the escaped character. +fn strip_inline(text: &str) -> String { + let chars: Vec<char> = text.chars().collect(); + let mut out = String::with_capacity(text.len()); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + if c == '!' && chars.get(i + 1) == Some(&'[') { + if let Some((label, end)) = link_at(&chars, i + 1) { + out.push_str(&label); + i = end; + continue; + } + } + if c == '[' { + if let Some((label, end)) = link_at(&chars, i) { + out.push_str(&label); + i = end; + continue; + } + } + if c == '\\' && chars.get(i + 1).is_some_and(|next| next.is_ascii_punctuation()) { + out.push(chars[i + 1]); + i += 2; + continue; + } + match c { + '*' | '`' | '~' => {} + '_' => { + let inside_word = i > 0 + && chars[i - 1].is_alphanumeric() + && chars.get(i + 1).is_some_and(|next| next.is_alphanumeric()); + if inside_word { + out.push(c); + } + } + _ => out.push(c), + } + i += 1; + } + out +} + +/// Parses `[label](target)` whose `[` is at `open`. Returns the label and the index just +/// after the closing `)`. +fn link_at(chars: &[char], open: usize) -> Option<(String, usize)> { + let close = open + 1 + chars[open + 1..].iter().position(|&c| c == ']')?; + if chars.get(close + 1) != Some(&'(') { + return None; + } + let end = close + 2 + chars[close + 2..].iter().position(|&c| c == ')')?; + Some((chars[open + 1..close].iter().collect(), end + 1)) +} + +/// The first `PREVIEW_CHARS` characters of a note's text after its title. The first +/// non-blank line of the markdown is the title, so it is skipped. +fn preview(markdown: &str) -> String { + let body = markdown + .lines() + .skip_while(|line| line.trim().is_empty()) + .skip(1) + .collect::<Vec<_>>() + .join("\n"); + plain_text(&body).chars().take(PREVIEW_CHARS).collect() +} + +/// About `SNIPPET_CHARS` characters of plain text around the first term match. +/// Cut ends get an ellipsis. +fn snippet(markdown: &str, matcher: &Matcher) -> String { + let plain = plain_text(markdown); + let chars: Vec<char> = plain.chars().collect(); + if chars.is_empty() { + return String::new(); + } + let center = matcher.ranges(&plain).first().map_or(0, |range| range.0); + let mut start = center.saturating_sub(SNIPPET_CHARS / 3); + let end = (start + SNIPPET_CHARS).min(chars.len()); + if end - start < SNIPPET_CHARS { + start = end.saturating_sub(SNIPPET_CHARS); + } + let body: String = chars[start..end].iter().collect(); + let mut out = String::new(); + if start > 0 { + out.push('…'); + } + out.push_str(body.trim()); + if end < chars.len() { + out.push('…'); + } + out +} + +impl Store { + /// Opens (or creates) the database file and runs schema setup. + pub async fn open(path: &str) -> anyhow::Result<Self> { + // The FTS index method is gated behind this flag in turso 0.8. + let db = turso::Builder::new_local(path) + .experimental_index_method(true) + .build() + .await + .with_context(|| format!("opening database at {path}"))?; + let conn = db.connect()?; + + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS notes ( + id TEXT PRIMARY KEY, + title TEXT NOT NULL DEFAULT 'Untitled', + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + notebook_id TEXT, + trashed_at INTEGER + ); + CREATE TABLE IF NOT EXISTS notebooks ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + created_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS updates ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, + note_id TEXT NOT NULL, + hash BLOB NOT NULL, + data BLOB NOT NULL, + UNIQUE(note_id, hash) + ); + CREATE TABLE IF NOT EXISTS snapshots ( + note_id TEXT PRIMARY KEY, + data BLOB NOT NULL, + upto_seq INTEGER NOT NULL, + markdown TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS note_text ( + note_id TEXT PRIMARY KEY, + title TEXT NOT NULL, + body TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS note_versions ( + note_id TEXT NOT NULL, + at INTEGER NOT NULL, + frontiers BLOB NOT NULL, + PRIMARY KEY(note_id, at) + ); + CREATE INDEX IF NOT EXISTS note_text_fts ON note_text USING fts(title, body); + CREATE TABLE IF NOT EXISTS note_links ( + src TEXT NOT NULL, + dst_id TEXT, + dst_title TEXT + ); + CREATE INDEX IF NOT EXISTS note_links_src ON note_links(src); + CREATE INDEX IF NOT EXISTS note_links_dst_id ON note_links(dst_id); + CREATE INDEX IF NOT EXISTS note_links_dst_title ON note_links(dst_title);", + ) + .await + .context("running schema setup")?; + + // Databases created before notebooks have a notes table without notebook_id. + // CREATE TABLE IF NOT EXISTS does not add columns, so add it when missing. + if !Self::notes_columns(&conn).await?.iter().any(|c| c == "notebook_id") { + conn.execute("ALTER TABLE notes ADD COLUMN notebook_id TEXT", ()) + .await + .context("adding notes.notebook_id")?; + } + + // Databases created before the trash existed lack notes.trashed_at. + if !Self::notes_columns(&conn).await?.iter().any(|c| c == "trashed_at") { + conn.execute("ALTER TABLE notes ADD COLUMN trashed_at INTEGER", ()) + .await + .context("adding notes.trashed_at")?; + } + + // Notes saved before note_text existed: copy their snapshot markdown once. + conn.execute( + "INSERT INTO note_text (note_id, title, body) + SELECT s.note_id, n.title, s.markdown FROM snapshots s + JOIN notes n ON n.id = s.note_id + WHERE NOT EXISTS (SELECT 1 FROM note_text t WHERE t.note_id = s.note_id)", + (), + ) + .await + .context("backfilling note_text")?; + + Ok(Self { + conn: Mutex::new(conn), + _db: db, + }) + } + + /// Column names of the notes table, read from `PRAGMA table_info`. + async fn notes_columns(conn: &turso::Connection) -> anyhow::Result<Vec<String>> { + let mut rows = conn.query("PRAGMA table_info(notes)", ()).await?; + let mut names = Vec::new(); + while let Some(row) = rows.next().await? { + names.push(text_col(&row, 1)?); + } + Ok(names) + } + + pub async fn create_note(&self, notebook_id: Option<&str>) -> anyhow::Result<NoteMeta> { + let now = now_millis(); + let note = NoteMeta { + id: uuid::Uuid::now_v7().to_string(), + title: "Untitled".to_string(), + created_at: now, + updated_at: now, + notebook_id: notebook_id.map(str::to_string), + trashed_at: None, + }; + + let conn = self.conn.lock().await; + conn.execute( + "INSERT INTO notes (id, title, created_at, updated_at, notebook_id) VALUES (?1, ?2, ?3, ?4, ?5)", + ( + note.id.clone(), + note.title.clone(), + note.created_at, + note.updated_at, + note.notebook_id.clone(), + ), + ) + .await?; + Ok(note) + } + + pub async fn create_notebook(&self, name: &str) -> anyhow::Result<Notebook> { + let notebook = Notebook { + id: uuid::Uuid::now_v7().to_string(), + name: name.to_string(), + created_at: now_millis(), + }; + + let conn = self.conn.lock().await; + conn.execute( + "INSERT INTO notebooks (id, name, created_at) VALUES (?1, ?2, ?3)", + ( + notebook.id.clone(), + notebook.name.clone(), + notebook.created_at, + ), + ) + .await?; + Ok(notebook) + } + + pub async fn list_notebooks(&self) -> anyhow::Result<Vec<Notebook>> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT id, name, created_at FROM notebooks ORDER BY name COLLATE NOCASE, id", + (), + ) + .await?; + let mut notebooks = Vec::new(); + while let Some(row) = rows.next().await? { + notebooks.push(notebook_from_row(&row)?); + } + Ok(notebooks) + } + + pub async fn get_notebook(&self, id: &str) -> anyhow::Result<Option<Notebook>> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT id, name, created_at FROM notebooks WHERE id = ?1", + (id.to_string(),), + ) + .await?; + match rows.next().await? { + Some(row) => Ok(Some(notebook_from_row(&row)?)), + None => Ok(None), + } + } + + pub async fn rename_notebook(&self, id: &str, name: &str) -> anyhow::Result<()> { + let conn = self.conn.lock().await; + conn.execute( + "UPDATE notebooks SET name = ?2 WHERE id = ?1", + (id.to_string(), name.to_string()), + ) + .await?; + Ok(()) + } + + /// Deletes the notebook. Its notes are kept and become unfiled. + pub async fn delete_notebook(&self, id: &str) -> anyhow::Result<()> { + let mut conn = self.conn.lock().await; + let tx = conn.transaction().await?; + tx.execute( + "UPDATE notes SET notebook_id = NULL WHERE notebook_id = ?1", + (id.to_string(),), + ) + .await?; + tx.execute("DELETE FROM notebooks WHERE id = ?1", (id.to_string(),)) + .await?; + tx.commit().await?; + Ok(()) + } + + pub async fn move_note(&self, note_id: &str, notebook_id: Option<&str>) -> anyhow::Result<()> { + let conn = self.conn.lock().await; + conn.execute( + "UPDATE notes SET notebook_id = ?2 WHERE id = ?1", + (note_id.to_string(), notebook_id.map(str::to_string)), + ) + .await?; + Ok(()) + } + + /// Deletes the note together with its updates, snapshot and searchable text. + pub async fn delete_note(&self, note_id: &str) -> anyhow::Result<()> { + let mut conn = self.conn.lock().await; + let tx = conn.transaction().await?; + delete_note_rows(&tx, note_id).await?; + tx.commit().await?; + Ok(()) + } + + /// Moves the note to the trash. It stays readable by `get_note` and is hidden + /// from lists and search until restored or purged. + pub async fn trash_note(&self, note_id: &str) -> anyhow::Result<()> { + let conn = self.conn.lock().await; + conn.execute( + "UPDATE notes SET trashed_at = ?2 WHERE id = ?1", + (note_id.to_string(), now_millis()), + ) + .await?; + Ok(()) + } + + /// Takes the note out of the trash. + pub async fn restore_note(&self, note_id: &str) -> anyhow::Result<()> { + let conn = self.conn.lock().await; + conn.execute( + "UPDATE notes SET trashed_at = NULL WHERE id = ?1", + (note_id.to_string(),), + ) + .await?; + Ok(()) + } + + /// Permanently deletes notes trashed more than `older_than_ms` milliseconds ago. + /// Returns the ids of the deleted notes. + pub async fn purge_trash(&self, older_than_ms: i64) -> anyhow::Result<Vec<String>> { + let cutoff = now_millis().saturating_sub(older_than_ms); + self.delete_trashed(cutoff).await + } + + /// Permanently deletes every trashed note. Returns the ids of the deleted notes. + pub async fn empty_trash(&self) -> anyhow::Result<Vec<String>> { + self.delete_trashed(i64::MAX).await + } + + /// Deletes trashed notes with `trashed_at < before` in one transaction. + async fn delete_trashed(&self, before: i64) -> anyhow::Result<Vec<String>> { + let mut conn = self.conn.lock().await; + let tx = conn.transaction().await?; + let mut rows = tx + .query( + "SELECT id FROM notes WHERE trashed_at IS NOT NULL AND trashed_at < ?1 ORDER BY trashed_at, id", + (before,), + ) + .await?; + let mut ids = Vec::new(); + while let Some(row) = rows.next().await? { + ids.push(text_col(&row, 0)?); + } + drop(rows); + for id in &ids { + delete_note_rows(&tx, id).await?; + } + tx.commit().await?; + Ok(ids) + } + + /// Trashed notes, most recently trashed first. + pub async fn list_trash(&self) -> anyhow::Result<Vec<NoteMeta>> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes + WHERE trashed_at IS NOT NULL ORDER BY trashed_at DESC, id", + (), + ) + .await?; + let mut notes = Vec::new(); + while let Some(row) = rows.next().await? { + notes.push(note_from_row(&row)?); + } + Ok(notes) + } + + /// Notes that are not in the trash, most recently updated first. + pub async fn list_notes(&self) -> anyhow::Result<Vec<NoteMeta>> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes + WHERE trashed_at IS NULL ORDER BY updated_at DESC, id", + (), + ) + .await?; + let mut notes = Vec::new(); + while let Some(row) = rows.next().await? { + notes.push(note_from_row(&row)?); + } + Ok(notes) + } + + pub async fn get_note(&self, id: &str) -> anyhow::Result<Option<NoteMeta>> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes WHERE id = ?1", + (id.to_string(),), + ) + .await?; + match rows.next().await? { + Some(row) => Ok(Some(note_from_row(&row)?)), + None => Ok(None), + } + } + + /// Appends a Loro update. Idempotent: the same bytes stored twice are kept once. + pub async fn append_update(&self, note_id: &str, update: &[u8]) -> anyhow::Result<()> { + let hash = blake3::hash(update).as_bytes().to_vec(); + let mut conn = self.conn.lock().await; + let tx = conn.transaction().await?; + let inserted = tx + .execute( + "INSERT OR IGNORE INTO updates (note_id, hash, data) VALUES (?1, ?2, ?3)", + (note_id.to_string(), hash, update.to_vec()), + ) + .await?; + if inserted > 0 { + tx.execute( + "UPDATE notes SET updated_at = ?2 WHERE id = ?1", + (note_id.to_string(), now_millis()), + ) + .await?; + } + tx.commit().await?; + Ok(()) + } + + pub async fn load_doc(&self, note_id: &str) -> anyhow::Result<DocBytes> { + let conn = self.conn.lock().await; + + let mut rows = conn + .query( + "SELECT data, upto_seq FROM snapshots WHERE note_id = ?1", + (note_id.to_string(),), + ) + .await?; + let (snapshot, upto_seq) = match rows.next().await? { + Some(row) => (Some(blob_col(&row, 0)?), int_col(&row, 1)?), + None => (None, 0), + }; + drop(rows); + + let mut rows = conn + .query( + "SELECT data FROM updates WHERE note_id = ?1 AND seq > ?2 ORDER BY seq", + (note_id.to_string(), upto_seq), + ) + .await?; + let mut updates = Vec::new(); + while let Some(row) = rows.next().await? { + updates.push(blob_col(&row, 0)?); + } + + Ok(DocBytes { snapshot, updates }) + } + + /// Stores a full snapshot plus the derived markdown and title. + /// Updates are never deleted; later loads only read updates newer than the snapshot. + pub async fn put_snapshot( + &self, + note_id: &str, + snapshot: &[u8], + markdown: &str, + title: &str, + ) -> anyhow::Result<()> { + let mut conn = self.conn.lock().await; + let tx = conn.transaction().await?; + + let mut rows = tx + .query( + "SELECT COALESCE(MAX(seq), 0) FROM updates WHERE note_id = ?1", + (note_id.to_string(),), + ) + .await?; + let max_seq = match rows.next().await? { + Some(row) => int_col(&row, 0)?, + None => 0, + }; + drop(rows); + + tx.execute( + "INSERT INTO snapshots (note_id, data, upto_seq, markdown) VALUES (?1, ?2, ?3, ?4) + ON CONFLICT(note_id) DO UPDATE SET + data = excluded.data, + upto_seq = excluded.upto_seq, + markdown = excluded.markdown", + ( + note_id.to_string(), + snapshot.to_vec(), + max_seq, + markdown.to_string(), + ), + ) + .await?; + tx.execute( + "UPDATE notes SET title = ?2 WHERE id = ?1", + (note_id.to_string(), title.to_string()), + ) + .await?; + + tx.commit().await?; + Ok(()) + } + + pub async fn set_title(&self, note_id: &str, title: &str) -> anyhow::Result<()> { + let conn = self.conn.lock().await; + conn.execute( + "UPDATE notes SET title = ?2 WHERE id = ?1", + (note_id.to_string(), title.to_string()), + ) + .await?; + Ok(()) + } + + /// Upserts the searchable text of a note. Does nothing when the note no longer + /// exists, so a flush that races a delete cannot bring the text back. + pub async fn put_text(&self, note_id: &str, title: &str, body: &str) -> anyhow::Result<()> { + let conn = self.conn.lock().await; + let mut rows = conn + .query("SELECT 1 FROM notes WHERE id = ?1", (note_id.to_string(),)) + .await?; + let exists = rows.next().await?.is_some(); + drop(rows); + if !exists { + return Ok(()); + } + conn.execute( + "INSERT INTO note_text (note_id, title, body) VALUES (?1, ?2, ?3) + ON CONFLICT(note_id) DO UPDATE SET title = excluded.title, body = excluded.body", + (note_id.to_string(), title.to_string(), body.to_string()), + ) + .await?; + Ok(()) + } + + /// Replaces the note links of `src`. Does nothing when the note no longer exists, like + /// `put_text`. Title targets are stored by `title_key`. + pub async fn set_links(&self, src: &str, targets: &[LinkTarget]) -> anyhow::Result<()> { + let mut conn = self.conn.lock().await; + let mut rows = conn + .query("SELECT 1 FROM notes WHERE id = ?1", (src.to_string(),)) + .await?; + let exists = rows.next().await?.is_some(); + drop(rows); + if !exists { + return Ok(()); + } + let tx = conn.transaction().await?; + tx.execute("DELETE FROM note_links WHERE src = ?1", (src.to_string(),)) + .await?; + for target in targets { + match target { + LinkTarget::Id(id) => { + tx.execute( + "INSERT INTO note_links (src, dst_id, dst_title) VALUES (?1, ?2, NULL)", + (src.to_string(), id.clone()), + ) + .await?; + } + LinkTarget::Title(title) => { + let key = title_key(title); + if key.is_empty() { + continue; + } + tx.execute( + "INSERT INTO note_links (src, dst_id, dst_title) VALUES (?1, NULL, ?2)", + (src.to_string(), key), + ) + .await?; + } + } + } + tx.commit().await?; + Ok(()) + } + + /// Non-trashed notes, other than `note_id`, that link to the note by its id or by + /// its title. Most recently updated first. + pub async fn backlinks(&self, note_id: &str, title: &str) -> anyhow::Result<Vec<NoteMeta>> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes + WHERE trashed_at IS NULL AND id <> ?1 AND id IN + (SELECT src FROM note_links WHERE dst_id = ?1 OR dst_title = ?2) + ORDER BY updated_at DESC, id", + (note_id.to_string(), title_key(title)), + ) + .await?; + let mut notes = Vec::new(); + while let Some(row) = rows.next().await? { + notes.push(note_from_row(&row)?); + } + Ok(notes) + } + + /// Search over titles and bodies with `matcher` (see [`crate::matcher`]): every term + /// must match the title or the text. Closest matches first, then more terms in the + /// title, then most recently updated. + pub async fn search(&self, matcher: &Matcher, limit: usize) -> anyhow::Result<Vec<SearchHit>> { + if limit == 0 { + return Ok(Vec::new()); + } + // A scan rather than the FTS index: the index matches whole words only, and + // typing "asd" has to find "asdadasxd" (and "isik" find "Işık"). + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT n.id, n.title, n.created_at, n.updated_at, n.notebook_id, n.trashed_at, + COALESCE(t.body, '') + FROM notes n LEFT JOIN note_text t ON t.note_id = n.id + WHERE n.trashed_at IS NULL", + (), + ) + .await?; + let mut hits = Vec::new(); + while let Some(row) = rows.next().await? { + let note = note_from_row(&row)?; + let body = text_col(&row, 6)?; + let in_title = matcher.term_costs(¬e.title); + let in_text = matcher.term_costs(&plain_text(&body)); + // Each term matches the title or the text, whichever is closer. Cheaper + // matches first (exact before typos), then more terms in the title. + let mut cost = 0; + let mut title_terms = 0; + let mut matched = true; + for (t, x) in in_title.into_iter().zip(in_text) { + match (t, x) { + (Some(t), Some(x)) if t <= x => (cost += t, title_terms += 1), + (Some(t), None) => (cost += t, title_terms += 1), + (_, Some(x)) => (cost += x, ()), + (None, None) => { + matched = false; + break; + } + }; + } + if !matched { + continue; + } + hits.push(( + (cost, std::cmp::Reverse(title_terms)), + SearchHit { + snippet: snippet(&body, matcher), + note, + }, + )); + } + hits.sort_by(|a, b| a.0.cmp(&b.0).then(b.1.note.updated_at.cmp(&a.1.note.updated_at))); + hits.truncate(limit); + Ok(hits.into_iter().map(|(_, hit)| hit).collect()) + } + + /// Notes, not in the trash, whose title holds every word of `query`, typos allowed + /// (see [`crate::matcher`]). Closest matches first, then most recently updated. + pub async fn search_titles(&self, query: &str, limit: usize) -> anyhow::Result<Vec<NoteMeta>> { + let Some(matcher) = Matcher::simple(query) else { + return Ok(Vec::new()); + }; + if limit == 0 { + return Ok(Vec::new()); + } + // Matched in Rust, not with SQL LIKE, which folds only ASCII case and has no + // typo tolerance: "izmir" and "izmr" have to find "İzmir". + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes + WHERE trashed_at IS NULL ORDER BY updated_at DESC, id", + (), + ) + .await?; + let mut notes = Vec::new(); + while let Some(row) = rows.next().await? { + let note = note_from_row(&row)?; + if let Some(cost) = matcher.cost(¬e.title) { + notes.push((cost, note)); + } + } + // Stable: equal costs stay most recent first. + notes.sort_by_key(|(cost, _)| *cost); + notes.truncate(limit); + Ok(notes.into_iter().map(|(_, note)| note).collect()) + } + + /// Previews of every note's text, keyed by note id, for list rows. Trashed notes are + /// included; callers look up only the notes they show. + pub async fn previews(&self) -> anyhow::Result<HashMap<String, String>> { + let conn = self.conn.lock().await; + let mut rows = conn.query("SELECT note_id, body FROM note_text", ()).await?; + let mut previews = HashMap::new(); + while let Some(row) = rows.next().await? { + previews.insert(text_col(&row, 0)?, preview(&text_col(&row, 1)?)); + } + Ok(previews) + } + + /// Stores a version of a note: the time in millis and the encoded frontiers of the doc. + pub async fn add_version(&self, note_id: &str, at_ms: i64, frontiers: &[u8]) -> anyhow::Result<()> { + let conn = self.conn.lock().await; + conn.execute( + "INSERT OR REPLACE INTO note_versions (note_id, at, frontiers) VALUES (?1, ?2, ?3)", + (note_id.to_string(), at_ms, frontiers.to_vec()), + ) + .await?; + Ok(()) + } + + /// Recorded versions of a note as `(at, frontiers)`, newest first. + pub async fn list_versions(&self, note_id: &str) -> anyhow::Result<Vec<(i64, Vec<u8>)>> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT at, frontiers FROM note_versions WHERE note_id = ?1 ORDER BY at DESC", + (note_id.to_string(),), + ) + .await?; + let mut versions = Vec::new(); + while let Some(row) = rows.next().await? { + versions.push((int_col(&row, 0)?, blob_col(&row, 1)?)); + } + Ok(versions) + } + + /// The encoded frontiers of the version of a note taken at `at`, if it exists. + pub async fn get_version(&self, note_id: &str, at: i64) -> anyhow::Result<Option<Vec<u8>>> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT frontiers FROM note_versions WHERE note_id = ?1 AND at = ?2", + (note_id.to_string(), at), + ) + .await?; + match rows.next().await? { + Some(row) => Ok(Some(blob_col(&row, 0)?)), + None => Ok(None), + } + } + + pub async fn get_markdown(&self, note_id: &str) -> anyhow::Result<Option<String>> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT markdown FROM snapshots WHERE note_id = ?1", + (note_id.to_string(),), + ) + .await?; + match rows.next().await? { + Some(row) => Ok(Some(text_col(&row, 0)?)), + None => Ok(None), + } + } +} + diff --git a/styles.css b/styles.css new file mode 100644 index 0000000..af1fc15 --- /dev/null +++ b/styles.css @@ -0,0 +1,1006 @@ +/* The theme is a small set of design tokens. Components refer to tokens only, never + to raw colors. Each color scheme (see the nine `:root[data-scheme="..."]` blocks + below) sets every color token for light and for `.dark`. With no `data-scheme`, the + Sage values in `:root` and `.dark` apply. + + --background the page background + --foreground text and iconography on the background + --card editor page, list pane, cards + --card-foreground text on cards + --popover floating menus and dialogs (lifted in dark) + --popover-foreground text on floating surfaces + --muted-foreground secondary text, metadata, placeholders + --primary highlighter fill: primary buttons, active marker + --primary-foreground text on the highlighter fill + --destructive destructive actions and error states + --destructive-foreground text on a destructive-filled surface + --border hairline borders and dividers + --ring the focus outline + --sidebar the sidebar background + --sidebar-foreground sidebar text and icons + --sidebar-primary primary actions inside the sidebar + --sidebar-primary-foreground text on sidebar primary actions + --sidebar-accent sidebar hover and selected backgrounds + --sidebar-accent-foreground text on sidebar accents + --sidebar-border sidebar borders and dividers + --sidebar-ring sidebar focus rings + --link links and accent ink + --mark text selection and search matches + --active-row the selected row: sidebar item, note, palette option + --active-row-foreground text on the selected row + --ok connected, saved + --warn offline, reconnecting + --bad errors (same role as --destructive) + --keycap-bg keycap chips + --shadow-xs, --shadow-sm raised controls and cards: none by default + --shadow-float floating surfaces only (menus, dialogs, tooltips) + + Fonts are declared in Rust with topcoat-font (Atkinson Hyperlegible Next for + UI and body text, Atkinson Hyperlegible Mono for metadata and keycaps). */ + +@import "tailwindcss"; + +/* Scan the project's Rust sources for the Tailwind classes they use. This + file is installed at the project root, so `./src` is the crate's source. */ +@source "./src/**/*.rs"; + +/* Dark mode is opted into by putting the `dark` class on an ancestor, + typically <html>. */ +@custom-variant dark (&:is(.dark *)); + +/* Expose the tokens as Tailwind utilities (`bg-background`, `text-primary`, + `border-border`, `text-link`, `bg-mark`, ...). The indirection through plain + variables on `:root` and `.dark` is what lets the values swap when the color + scheme changes. */ +@theme inline { + --font-sans: "Atkinson Hyperlegible Next", sans-serif; + --font-mono: "Atkinson Hyperlegible Mono", ui-monospace, monospace; + + --color-background: var(--background); + --color-foreground: var(--foreground); + --color-card: var(--card); + --color-card-foreground: var(--card-foreground); + --color-popover: var(--popover); + --color-popover-foreground: var(--popover-foreground); + --color-muted-foreground: var(--muted-foreground); + --color-primary: var(--primary); + --color-primary-foreground: var(--primary-foreground); + --color-destructive: var(--destructive); + --color-destructive-foreground: var(--destructive-foreground); + --color-border: var(--border); + --color-ring: var(--ring); + --color-sidebar: var(--sidebar); + --color-sidebar-foreground: var(--sidebar-foreground); + --color-sidebar-primary: var(--sidebar-primary); + --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); + --color-sidebar-accent: var(--sidebar-accent); + --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); + --color-sidebar-border: var(--sidebar-border); + --color-sidebar-ring: var(--sidebar-ring); + --color-link: var(--link); + --color-mark: var(--mark); + --color-active-row: var(--active-row); + --color-active-row-foreground: var(--active-row-foreground); + --color-ok: var(--ok); + --color-warn: var(--warn); + --color-bad: var(--bad); + --color-keycap: var(--keycap-bg); + + --radius-control: 6px; + --radius-float: 10px; + --radius-pill: 999px; + + --shadow-xs: var(--shadow-xs); + --shadow-sm: var(--shadow-sm); + --shadow-float: var(--shadow-float); +} + +:root { + --background: #f5f7f4; + --foreground: #18201a; + --card: #ffffff; + --card-foreground: #18201a; + --popover: #ffffff; + --popover-foreground: #18201a; + --muted-foreground: #56625a; + --primary: #567752; + --primary-foreground: #ffffff; + --destructive: #b3261e; + --destructive-foreground: #ffffff; + --border: #d2dbd0; + --ring: #2f6b3a; + --sidebar: #e9efe6; + --sidebar-foreground: #18201a; + --sidebar-primary: #567752; + --sidebar-primary-foreground: #ffffff; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #18201a; + --sidebar-border: #d2dbd0; + --sidebar-ring: #2f6b3a; + --link: #2f6b3a; + --mark: #ffe9a3; + --active-row: #d9ebd3; + --active-row-foreground: #1f3d22; + --ok: #1f7a4a; + --warn: #9a5b00; + --bad: #b3261e; + --keycap-bg: #e1e9de; + --shadow-xs: 0 1px 2px rgb(0 0 0 / 0.08); + --shadow-sm: 0 0 #0000; + --shadow-float: 0 8px 24px rgb(0 0 0 / 0.12); +} + +.dark { + --background: #151615; + --foreground: #e6e6e1; + --card: #1b1c1b; + --card-foreground: #e6e6e1; + --popover: #1b1c1b; + --popover-foreground: #e6e6e1; + --muted-foreground: #9f9f98; + --primary: #4a6847; + --primary-foreground: #eef4ea; + --destructive: #f08a80; + --destructive-foreground: #151615; + --border: #2b2d2b; + --ring: #a7c49f; + --sidebar: #111211; + --sidebar-foreground: #e6e6e1; + --sidebar-primary: #4a6847; + --sidebar-primary-foreground: #eef4ea; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #e6e6e1; + --sidebar-border: #2b2d2b; + --sidebar-ring: #a7c49f; + --link: #a7c49f; + --mark: #5e5216; + --active-row: #233024; + --active-row-foreground: #d8e6d4; + --ok: #8cc79a; + --warn: #f2b45a; + --bad: #f08a80; + --keycap-bg: #252625; + --shadow-xs: 0 1px 2px rgb(0 0 0 / 0.5); + --shadow-sm: 0 0 #0000; + --shadow-float: 0 8px 24px rgb(0 0 0 / 0.5); +} + +/* Color schemes. Each palette: a light block for the default mode and a dark block + for `.dark`. The `:not(.dark)` keeps the light block from winning in dark mode. */ +:root[data-scheme="graphite"]:not(.dark) { + --background: #f6f7f9; + --foreground: #15181d; + --card: #ffffff; + --card-foreground: #15181d; + --popover: #ffffff; + --popover-foreground: #15181d; + --muted-foreground: #5a616d; + --primary: #f2b600; + --primary-foreground: #15181d; + --destructive: #b42318; + --destructive-foreground: #ffffff; + --border: #d5d9e0; + --ring: #1d4ed8; + --sidebar: #eceef2; + --sidebar-foreground: #15181d; + --sidebar-primary: #f2b600; + --sidebar-primary-foreground: #15181d; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #15181d; + --sidebar-border: #d5d9e0; + --sidebar-ring: #1d4ed8; + --link: #1d4ed8; + --mark: #ffe9a0; + --active-row: #ffe08a; + --active-row-foreground: #15181d; + --ok: #1e7a46; + --warn: #9a5b00; + --bad: #b42318; + --keycap-bg: #e3e6eb; +} + +:root[data-scheme="graphite"].dark { + --background: #16181c; + --foreground: #eceef2; + --card: #22262d; + --card-foreground: #eceef2; + --popover: #22262d; + --popover-foreground: #eceef2; + --muted-foreground: #9aa3b2; + --primary: #ffc93c; + --primary-foreground: #15181d; + --destructive: #ff8a80; + --destructive-foreground: #16181c; + --border: #343a45; + --ring: #8ab4ff; + --sidebar: #1d2026; + --sidebar-foreground: #eceef2; + --sidebar-primary: #ffc93c; + --sidebar-primary-foreground: #15181d; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #eceef2; + --sidebar-border: #343a45; + --sidebar-ring: #8ab4ff; + --link: #8ab4ff; + --mark: #7a5f00; + --active-row: #5c4700; + --active-row-foreground: #fff3c4; + --ok: #5fcf8f; + --warn: #f2b45a; + --bad: #ff8a80; + --keycap-bg: #2b3038; +} + +:root[data-scheme="cobalt"]:not(.dark) { + --background: #fbfcff; + --foreground: #0e1830; + --card: #ffffff; + --card-foreground: #0e1830; + --popover: #ffffff; + --popover-foreground: #0e1830; + --muted-foreground: #4a5772; + --primary: #1f4fd1; + --primary-foreground: #ffffff; + --destructive: #b3261e; + --destructive-foreground: #ffffff; + --border: #d3dcea; + --ring: #1f4fd1; + --sidebar: #eef3fb; + --sidebar-foreground: #0e1830; + --sidebar-primary: #1f4fd1; + --sidebar-primary-foreground: #ffffff; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #0e1830; + --sidebar-border: #d3dcea; + --sidebar-ring: #1f4fd1; + --link: #1f4fd1; + --mark: #fff0a6; + --active-row: #dce7ff; + --active-row-foreground: #0b2a80; + --ok: #137a4a; + --warn: #9a5b00; + --bad: #b3261e; + --keycap-bg: #e2e9f7; +} + +:root[data-scheme="cobalt"].dark { + --background: #0c1120; + --foreground: #e6ecfb; + --card: #17213a; + --card-foreground: #e6ecfb; + --popover: #17213a; + --popover-foreground: #e6ecfb; + --muted-foreground: #97a4c2; + --primary: #5b8bff; + --primary-foreground: #0a1024; + --destructive: #ff8b84; + --destructive-foreground: #0c1120; + --border: #2a3756; + --ring: #8fb0ff; + --sidebar: #121a2c; + --sidebar-foreground: #e6ecfb; + --sidebar-primary: #5b8bff; + --sidebar-primary-foreground: #0a1024; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #e6ecfb; + --sidebar-border: #2a3756; + --sidebar-ring: #8fb0ff; + --link: #8fb0ff; + --mark: #6b5a00; + --active-row: #1d2f5c; + --active-row-foreground: #cfdcff; + --ok: #5fd39a; + --warn: #f2b45a; + --bad: #ff8b84; + --keycap-bg: #1f2a45; +} + +:root[data-scheme="oxblood"]:not(.dark) { + --background: #f7f5f4; + --foreground: #201a19; + --card: #ffffff; + --card-foreground: #201a19; + --popover: #ffffff; + --popover-foreground: #201a19; + --muted-foreground: #625a57; + --primary: #8e1b22; + --primary-foreground: #ffffff; + --destructive: #a4161a; + --destructive-foreground: #ffffff; + --border: #d9d2cf; + --ring: #9c2a2a; + --sidebar: #eeeae8; + --sidebar-foreground: #201a19; + --sidebar-primary: #8e1b22; + --sidebar-primary-foreground: #ffffff; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #201a19; + --sidebar-border: #d9d2cf; + --sidebar-ring: #9c2a2a; + --link: #9c2a2a; + --mark: #ffe9a3; + --active-row: #f8dcd9; + --active-row-foreground: #6b1218; + --ok: #2d6a3e; + --warn: #9a5b00; + --bad: #a4161a; + --keycap-bg: #e7e2e0; +} + +:root[data-scheme="oxblood"].dark { + --background: #141111; + --foreground: #f1eceb; + --card: #221d1d; + --card-foreground: #f1eceb; + --popover: #221d1d; + --popover-foreground: #f1eceb; + --muted-foreground: #a89f9c; + --primary: #d85c63; + --primary-foreground: #140e0e; + --destructive: #ff8a8a; + --destructive-foreground: #141111; + --border: #3a3332; + --ring: #f09a94; + --sidebar: #1c1818; + --sidebar-foreground: #f1eceb; + --sidebar-primary: #d85c63; + --sidebar-primary-foreground: #140e0e; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #f1eceb; + --sidebar-border: #3a3332; + --sidebar-ring: #f09a94; + --link: #f09a94; + --mark: #6e5a10; + --active-row: #4a1d21; + --active-row-foreground: #ffd9d6; + --ok: #7ccf96; + --warn: #f2b45a; + --bad: #ff8a8a; + --keycap-bg: #2e2828; +} + +:root[data-scheme="teal"]:not(.dark) { + --background: #f4f8f8; + --foreground: #13201f; + --card: #ffffff; + --card-foreground: #13201f; + --popover: #ffffff; + --popover-foreground: #13201f; + --muted-foreground: #4f6663; + --primary: #0f5e5a; + --primary-foreground: #ffffff; + --destructive: #b42318; + --destructive-foreground: #ffffff; + --border: #cbdad8; + --ring: #0b6b66; + --sidebar: #e8f0f0; + --sidebar-foreground: #13201f; + --sidebar-primary: #0f5e5a; + --sidebar-primary-foreground: #ffffff; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #13201f; + --sidebar-border: #cbdad8; + --sidebar-ring: #0b6b66; + --link: #0b6b66; + --mark: #ffe27a; + --active-row: #cdeee9; + --active-row-foreground: #073b38; + --ok: #1b7340; + --warn: #9a5b00; + --bad: #b42318; + --keycap-bg: #dde8e7; +} + +:root[data-scheme="teal"].dark { + --background: #0d1514; + --foreground: #e3efed; + --card: #172624; + --card-foreground: #e3efed; + --popover: #172624; + --popover-foreground: #e3efed; + --muted-foreground: #98b1ad; + --primary: #3fb3a6; + --primary-foreground: #06201e; + --destructive: #ff8a80; + --destructive-foreground: #0d1514; + --border: #2a3d3b; + --ring: #7fd6cc; + --sidebar: #121d1c; + --sidebar-foreground: #e3efed; + --sidebar-primary: #3fb3a6; + --sidebar-primary-foreground: #06201e; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #e3efed; + --sidebar-border: #2a3d3b; + --sidebar-ring: #7fd6cc; + --link: #7fd6cc; + --mark: #6b5a10; + --active-row: #15403b; + --active-row-foreground: #c4f2eb; + --ok: #5fcf8f; + --warn: #f2b45a; + --bad: #ff8a80; + --keycap-bg: #1f3431; +} + +:root[data-scheme="plum"]:not(.dark) { + --background: #f8f6fa; + --foreground: #1f1a26; + --card: #ffffff; + --card-foreground: #1f1a26; + --popover: #ffffff; + --popover-foreground: #1f1a26; + --muted-foreground: #5f5570; + --primary: #7b2d6e; + --primary-foreground: #ffffff; + --destructive: #b3261e; + --destructive-foreground: #ffffff; + --border: #d9d1e2; + --ring: #6a2fb0; + --sidebar: #efeaf3; + --sidebar-foreground: #1f1a26; + --sidebar-primary: #7b2d6e; + --sidebar-primary-foreground: #ffffff; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #1f1a26; + --sidebar-border: #d9d1e2; + --sidebar-ring: #6a2fb0; + --link: #6a2fb0; + --mark: #ffe9a3; + --active-row: #f1d9ee; + --active-row-foreground: #5a1a4f; + --ok: #1f7a4a; + --warn: #9a5b00; + --bad: #b3261e; + --keycap-bg: #e8e2ee; +} + +:root[data-scheme="plum"].dark { + --background: #120f16; + --foreground: #ece8f2; + --card: #201b27; + --card-foreground: #ece8f2; + --popover: #201b27; + --popover-foreground: #ece8f2; + --muted-foreground: #a79fb6; + --primary: #d27ac4; + --primary-foreground: #1a0d18; + --destructive: #ff8a8a; + --destructive-foreground: #120f16; + --border: #3a3246; + --ring: #c9a6ff; + --sidebar: #1a1620; + --sidebar-foreground: #ece8f2; + --sidebar-primary: #d27ac4; + --sidebar-primary-foreground: #1a0d18; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #ece8f2; + --sidebar-border: #3a3246; + --sidebar-ring: #c9a6ff; + --link: #c9a6ff; + --mark: #6b5a10; + --active-row: #4a2446; + --active-row-foreground: #f5d6ef; + --ok: #7ccf96; + --warn: #f2b45a; + --bad: #ff8a8a; + --keycap-bg: #2e2739; +} + +:root[data-scheme="mono"]:not(.dark) { + --background: #fafafa; + --foreground: #111111; + --card: #ffffff; + --card-foreground: #111111; + --popover: #ffffff; + --popover-foreground: #111111; + --muted-foreground: #5c5c5c; + --primary: #111111; + --primary-foreground: #ffffff; + --destructive: #9b1c1c; + --destructive-foreground: #ffffff; + --border: #d8d8d8; + --ring: #222222; + --sidebar: #f0f0f0; + --sidebar-foreground: #111111; + --sidebar-primary: #111111; + --sidebar-primary-foreground: #ffffff; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #111111; + --sidebar-border: #d8d8d8; + --sidebar-ring: #222222; + --link: #222222; + --mark: #fff1a8; + --active-row: #e4e4e4; + --active-row-foreground: #111111; + --ok: #2e6b3a; + --warn: #9a5b00; + --bad: #9b1c1c; + --keycap-bg: #e6e6e6; +} + +:root[data-scheme="mono"].dark { + --background: #0e0e0e; + --foreground: #f2f2f2; + --card: #1c1c1c; + --card-foreground: #f2f2f2; + --popover: #1c1c1c; + --popover-foreground: #f2f2f2; + --muted-foreground: #a3a3a3; + --primary: #f2f2f2; + --primary-foreground: #111111; + --destructive: #ff8a8a; + --destructive-foreground: #0e0e0e; + --border: #333333; + --ring: #e6e6e6; + --sidebar: #161616; + --sidebar-foreground: #f2f2f2; + --sidebar-primary: #f2f2f2; + --sidebar-primary-foreground: #111111; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #f2f2f2; + --sidebar-border: #333333; + --sidebar-ring: #e6e6e6; + --link: #e6e6e6; + --mark: #5e4f12; + --active-row: #2e2e2e; + --active-row-foreground: #f2f2f2; + --ok: #7ccf96; + --warn: #f2b45a; + --bad: #ff8a8a; + --keycap-bg: #262626; +} + +:root[data-scheme="tangerine"]:not(.dark) { + --background: #f6f7f8; + --foreground: #161a1f; + --card: #ffffff; + --card-foreground: #161a1f; + --popover: #ffffff; + --popover-foreground: #161a1f; + --muted-foreground: #5a626c; + --primary: #f59e0b; + --primary-foreground: #1a0d00; + --destructive: #b3261e; + --destructive-foreground: #ffffff; + --border: #d6dadf; + --ring: #a85200; + --sidebar: #eceef0; + --sidebar-foreground: #161a1f; + --sidebar-primary: #f59e0b; + --sidebar-primary-foreground: #1a0d00; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #161a1f; + --sidebar-border: #d6dadf; + --sidebar-ring: #a85200; + --link: #a85200; + --mark: #fff1a8; + --active-row: #fde9c4; + --active-row-foreground: #6b3d00; + --ok: #1f7a4a; + --warn: #9a5b00; + --bad: #b3261e; + --keycap-bg: #e3e6ea; +} + +:root[data-scheme="tangerine"].dark { + --background: #0f1113; + --foreground: #eef0f2; + --card: #1c2024; + --card-foreground: #eef0f2; + --popover: #1c2024; + --popover-foreground: #eef0f2; + --muted-foreground: #a4acb6; + --primary: #ffb347; + --primary-foreground: #1a0d00; + --destructive: #ff8a8a; + --destructive-foreground: #0f1113; + --border: #343a42; + --ring: #ffc27a; + --sidebar: #16191c; + --sidebar-foreground: #eef0f2; + --sidebar-primary: #ffb347; + --sidebar-primary-foreground: #1a0d00; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #eef0f2; + --sidebar-border: #343a42; + --sidebar-ring: #ffc27a; + --link: #ffc27a; + --mark: #5e4f12; + --active-row: #4f3412; + --active-row-foreground: #ffe2b8; + --ok: #7ccf96; + --warn: #f2b45a; + --bad: #ff8a8a; + --keycap-bg: #2a2f35; +} + +:root[data-scheme="sage"]:not(.dark) { + --background: #f5f7f4; + --foreground: #18201a; + --card: #ffffff; + --card-foreground: #18201a; + --popover: #ffffff; + --popover-foreground: #18201a; + --muted-foreground: #56625a; + --primary: #567752; + --primary-foreground: #ffffff; + --destructive: #b3261e; + --destructive-foreground: #ffffff; + --border: #d2dbd0; + --ring: #2f6b3a; + --sidebar: #e9efe6; + --sidebar-foreground: #18201a; + --sidebar-primary: #567752; + --sidebar-primary-foreground: #ffffff; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #18201a; + --sidebar-border: #d2dbd0; + --sidebar-ring: #2f6b3a; + --link: #2f6b3a; + --mark: #ffe9a3; + --active-row: #d9ebd3; + --active-row-foreground: #1f3d22; + --ok: #1f7a4a; + --warn: #9a5b00; + --bad: #b3261e; + --keycap-bg: #e1e9de; +} + +:root[data-scheme="sage"].dark { + --background: #151615; + --foreground: #e6e6e1; + --card: #1b1c1b; + --card-foreground: #e6e6e1; + --popover: #1b1c1b; + --popover-foreground: #e6e6e1; + --muted-foreground: #9f9f98; + --primary: #4a6847; + --primary-foreground: #eef4ea; + --destructive: #f08a80; + --destructive-foreground: #151615; + --border: #2b2d2b; + --ring: #a7c49f; + --sidebar: #111211; + --sidebar-foreground: #e6e6e1; + --sidebar-primary: #4a6847; + --sidebar-primary-foreground: #eef4ea; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #e6e6e1; + --sidebar-border: #2b2d2b; + --sidebar-ring: #a7c49f; + --link: #a7c49f; + --mark: #5e5216; + --active-row: #233024; + --active-row-foreground: #d8e6d4; + --ok: #8cc79a; + --warn: #f2b45a; + --bad: #f08a80; + --keycap-bg: #252625; +} + +:root[data-scheme="spark"]:not(.dark) { + --background: #f6f6f7; + --foreground: #1a1a1d; + --card: #ffffff; + --card-foreground: #1a1a1d; + --popover: #ffffff; + --popover-foreground: #1a1a1d; + --muted-foreground: #5b5b63; + --primary: #ff8205; + --primary-foreground: #1a0e00; + --destructive: #b3261e; + --destructive-foreground: #ffffff; + --border: #d8d8dd; + --ring: #a34c00; + --sidebar: #eeeef0; + --sidebar-foreground: #1a1a1d; + --sidebar-primary: #ff8205; + --sidebar-primary-foreground: #1a0e00; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #1a1a1d; + --sidebar-border: #d8d8dd; + --sidebar-ring: #a34c00; + --link: #a34c00; + --mark: #fff1a8; + --active-row: #ffe8c7; + --active-row-foreground: #753a00; + --ok: #1f7a4a; + --warn: #9a5b00; + --bad: #b3261e; + --keycap-bg: #e5e5ea; +} + +:root[data-scheme="spark"].dark { + --background: #120f0d; + --foreground: #f3ebe6; + --card: #211b17; + --card-foreground: #f3ebe6; + --popover: #211b17; + --popover-foreground: #f3ebe6; + --muted-foreground: #ab9d94; + --primary: #ff9a2e; + --primary-foreground: #1a0e00; + --destructive: #ff8a8a; + --destructive-foreground: #120f0d; + --border: #3d322b; + --ring: #ffaa5c; + --sidebar: #1a1512; + --sidebar-foreground: #f3ebe6; + --sidebar-primary: #ff9a2e; + --sidebar-primary-foreground: #1a0e00; + --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border)); + --sidebar-accent-foreground: #f3ebe6; + --sidebar-border: #3d322b; + --sidebar-ring: #ffaa5c; + --link: #ffaa5c; + --mark: #6b5a10; + --active-row: #58320a; + --active-row-foreground: #ffe0bd; + --ok: #7ccf96; + --warn: #f2b45a; + --bad: #ff8a8a; + --keycap-bg: #2e2520; +} + + +@layer base { + /* Tailwind's preflight resets buttons to the default cursor; every clickable control gets the pointer. */ + button:not(:disabled), + [role="button"]:not([aria-disabled="true"]), + [role="menuitem"], + [role="menuitemradio"], + [role="option"], + summary, + select, + label[for] { + cursor: pointer; + } + body { + @apply bg-background font-sans text-foreground antialiased; + font-size: 14px; + line-height: 20px; + } + + ::selection { + background-color: var(--mark); + color: var(--foreground); + } + + :focus-visible { + outline: 2px solid var(--ring); + outline-offset: 2px; + } + + @media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + transition: none !important; + animation: none !important; + scroll-behavior: auto !important; + } + } + + @media (forced-colors: active) { + :focus-visible { + outline: 2px solid CanvasText; + outline-offset: 2px; + } + + ::selection { + background-color: Highlight; + color: HighlightText; + } + } +} + +@layer components { + /* Highlighter swipe behind the active sidebar item or selected note row. */ + .marker { + border-radius: 6px; + color: var(--active-row-foreground); + background-image: linear-gradient(transparent 15%, var(--active-row) 15% 85%, transparent 85%); + background-repeat: no-repeat; + background-size: 100% 100%; + animation: marker-swipe 160ms ease-out; + } + + @keyframes marker-swipe { + from { + background-size: 0% 100%; + } + to { + background-size: 100% 100%; + } + } + + @media (forced-colors: active) { + .marker { + background: Highlight; + color: HighlightText; + } + } + + /* The three swatch dots in the color scheme picker. The inline style sets each dot's + light and dark colors; `.dark` picks the dark one. */ + .scheme-dots { + display: inline-flex; + flex-shrink: 0; + align-items: center; + gap: 3px; + } + + .scheme-dot { + width: 8px; + height: 8px; + border-radius: var(--radius-pill); + background-color: var(--dot-light); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--foreground) 18%, transparent); + } + + .dark .scheme-dot { + background-color: var(--dot-dark); + } + + /* The checkmark on the chosen scheme in the picker menu. */ + [role="menuitemradio"] .scheme-check { + flex-shrink: 0; + opacity: 0; + } + + [role="menuitemradio"][aria-checked="true"] .scheme-check { + opacity: 1; + } + + /* A keyboard key label, such as Ctrl, K, or Esc. */ + .keycap { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 4px; + min-width: 20px; + padding: 1px 5px; + font-family: var(--font-mono); + font-size: 11px; + line-height: 16px; + white-space: nowrap; + color: var(--muted-foreground); + background-color: var(--keycap-bg); + border: 1px solid var(--border); + border-bottom-width: 2px; + border-radius: 4px; + } + + /* Segmented control: a track of mutually exclusive buttons. The pressed segment + (aria-pressed="true") is raised on the card surface. Both controls in the sidebar + footer use these, so they share height and visual language. */ + .segmented { + display: inline-flex; + flex-shrink: 0; + align-items: center; + gap: 2px; + height: 28px; + padding: 2px; + border-radius: var(--radius-control); + background-color: color-mix(in srgb, var(--foreground) 5%, transparent); + } + + .segment { + display: inline-flex; + flex-shrink: 0; + align-items: center; + justify-content: center; + height: 24px; + min-width: 24px; + padding: 0 8px; + border: 1px solid transparent; + border-radius: 4px; + font-size: 12px; + font-weight: 500; + line-height: 16px; + color: var(--muted-foreground); + background-color: transparent; + cursor: pointer; + transition: background-color 150ms ease-out, color 150ms ease-out, box-shadow 150ms ease-out; + } + + .segment:hover { + color: var(--foreground); + background-color: color-mix(in srgb, var(--foreground) 6%, transparent); + } + + .segment:active { + background-color: color-mix(in srgb, var(--foreground) 12%, transparent); + } + + .segment-icon { + width: 24px; + padding: 0; + } + + /* Declared after the hover and active rules so the pressed segment keeps its look. */ + .segment[aria-pressed="true"] { + color: var(--foreground); + background-color: var(--card); + border-color: var(--border); + box-shadow: var(--shadow-xs); + } + + .segment:disabled { + cursor: not-allowed; + opacity: 0.5; + } + + /* One-pixel rules between rows and panes. */ + .hairline-t { + border-top: 1px solid var(--border); + } + .hairline-b { + border-bottom: 1px solid var(--border); + } + .hairline-l { + border-left: 1px solid var(--border); + } + .hairline-r { + border-right: 1px solid var(--border); + } + + /* Tiny mono labels that group a list or a pane. */ + .section-label { + font-family: var(--font-mono); + font-size: 11px; + line-height: 16px; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--muted-foreground); + } +} + +/* The browser's own clear button on search fields is drawn in its accent color (blue + in dark mode). Redraw it as a muted cross, and drop the shortcut hint while there is + text so the cross sits at the edge. */ +input[type="search"]::-webkit-search-cancel-button { + -webkit-appearance: none; + appearance: none; + width: 14px; + height: 14px; + cursor: pointer; + background-color: var(--muted-foreground); + -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2.5' stroke-linecap='round'%3E%3Cpath d='M18 6 6 18M6 6l12 12'/%3E%3C/svg%3E") center / contain no-repeat; + mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2.5' stroke-linecap='round'%3E%3Cpath d='M18 6 6 18M6 6l12 12'/%3E%3C/svg%3E") center / contain no-repeat; +} +input[type="search"]::-webkit-search-cancel-button:hover { + background-color: var(--foreground); +} +#search-input:not(:placeholder-shown) { + padding-right: 2rem; +} +form:has(#search-input:not(:placeholder-shown)) .search-hint { + display: none; +} + +/* Checkbox of a search filter row: an empty box, filled with a tick when on. */ +.filter-box { + display: inline-flex; + flex-shrink: 0; + align-items: center; + justify-content: center; + width: 16px; + height: 16px; + border: 1px solid var(--border); + border-radius: 4px; +} +.filter-box svg { + display: none; + width: 12px; + height: 12px; +} +[aria-checked="true"] > .filter-box { + border-color: transparent; + background: var(--primary); + color: var(--primary-foreground); +} +[aria-checked="true"] > .filter-box svg { + display: block; +} diff --git a/web/build.ts b/web/build.ts new file mode 100644 index 0000000..6a534ff --- /dev/null +++ b/web/build.ts @@ -0,0 +1,48 @@ +// Bundles the editor into ../assets: editor.js (+ map), editor.css, and the Loro WASM as +// a separate content-hashed file (loro-<hash>.wasm). The server serves assets/ with +// mime_guess, so the .wasm goes out as application/wasm and can be stream-compiled. +import { readdirSync, unlinkSync } from "node:fs"; +import { dirname } from "node:path"; +import type { BunPlugin } from "bun"; + +const outdir = `${import.meta.dir}/../assets`; + +// loro-crdt's "web" entry takes the WASM URL in its default init(), so nothing is inlined. +// Aliasing the bare specifier makes loro-prosemirror share the same Loro instance. +const loroWeb: BunPlugin = { + name: "loro-crdt-web", + setup(build) { + build.onResolve({ filter: /^loro-crdt$/ }, () => ({ + path: Bun.resolveSync("loro-crdt/web", import.meta.dir), + })); + }, +}; + +// Copy the WASM out under a name that changes with its bytes; remove older copies we made. +const wasmSource = `${dirname(Bun.resolveSync("loro-crdt/web", import.meta.dir))}/loro_wasm_bg.wasm`; +const wasmBytes = new Uint8Array(await Bun.file(wasmSource).arrayBuffer()); +const digest = new Bun.CryptoHasher("sha256").update(wasmBytes).digest("hex").slice(0, 12); +const wasmName = `loro-${digest}.wasm`; +for (const file of readdirSync(outdir)) { + if (/^loro-[0-9a-f]{12}\.wasm$/.test(file) && file !== wasmName) unlinkSync(`${outdir}/${file}`); +} +await Bun.write(`${outdir}/${wasmName}`, wasmBytes); +console.log(`${outdir}/${wasmName} ${(wasmBytes.length / 1024).toFixed(1)} KiB`); + +for (const entry of ["src/editor.ts", "src/editor.css"]) { + const result = await Bun.build({ + entrypoints: [`${import.meta.dir}/${entry}`], + outdir, + target: "browser", + format: "esm", + minify: true, + sourcemap: "linked", + define: { __LORO_WASM_NAME__: JSON.stringify(wasmName) }, + plugins: [loroWeb], + }); + if (!result.success) { + for (const log of result.logs) console.error(log); + process.exit(1); + } + for (const out of result.outputs) console.log(`${out.path} ${(out.size / 1024).toFixed(1)} KiB`); +} diff --git a/web/bun.lock b/web/bun.lock new file mode 100644 index 0000000..5da6262 --- /dev/null +++ b/web/bun.lock @@ -0,0 +1,58 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "project-note-editor", + "dependencies": { + "loro-crdt": "1.17.1", + "loro-prosemirror": "0.4.4", + "prosemirror-commands": "1.7.2", + "prosemirror-dropcursor": "^1.8.4", + "prosemirror-gapcursor": "^1.4.1", + "prosemirror-inputrules": "^1.5.1", + "prosemirror-keymap": "1.2.3", + "prosemirror-model": "1.25.12", + "prosemirror-schema-basic": "1.2.5", + "prosemirror-schema-list": "1.5.1", + "prosemirror-state": "1.4.4", + "prosemirror-view": "1.42.8", + }, + }, + }, + "packages": { + "isomorphic.js": ["isomorphic.js@0.2.5", "", {}, "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw=="], + + "lib0": ["lib0@0.2.119", "", { "dependencies": { "isomorphic.js": "^0.2.4" }, "bin": { "0serve": "bin/0serve.js", "0gentesthtml": "bin/gentesthtml.js", "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js" } }, "sha512-vh+TiejVy8Xm+hCdnRfn9BthGNvNUZdEXltNjVZL3TzRIKP3s1lnQh8pWd/Q0wCgY0FPAGVVjFF4ZiHUV3LFgA=="], + + "loro-crdt": ["loro-crdt@1.17.1", "", {}, "sha512-83hWRYG6eMMpPezm+yXWlOqCuUsC0BYY1MVCPW9x2zlikgkHhL7GC7Q6JFH+Hjvauyn287Q1MiwTuRW0lUOUag=="], + + "loro-prosemirror": ["loro-prosemirror@0.4.4", "", { "dependencies": { "lib0": "^0.2.42", "prosemirror-model": "^1.18.1", "prosemirror-state": "^1.4.1", "prosemirror-view": "^1.28.0" }, "peerDependencies": { "loro-crdt": "^1.10.2" } }, "sha512-9Ttd3yHcb6Y+qxsqiS+fNMy9c9bNeimlLd7FShbVwRUBer8iosI9txWZlegzKnNjUUqIRyV15ybM6w3c2zS+Jg=="], + + "orderedmap": ["orderedmap@2.1.1", "", {}, "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g=="], + + "prosemirror-commands": ["prosemirror-commands@1.7.2", "", { "dependencies": { "prosemirror-model": "^1.0.0", "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.10.2" } }, "sha512-q6Q6szxqdu9Xd6EcdKsqXghu5nQdZTpB4Q9yd04WRc7/jt763e/rT60Owh0L1GYY+T46o5rD+9lEN36dZS43tw=="], + + "prosemirror-dropcursor": ["prosemirror-dropcursor@1.8.4", "", { "dependencies": { "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.1.0", "prosemirror-view": "^1.1.0" } }, "sha512-VmKxhcA6a+h5oPSYmfF1ZNeQqPbyYaIxqZsKqeYCyTlPtrjUgNaHL3P8vVaO19oqAV0zuaM/axkowZHrB1P3Tg=="], + + "prosemirror-gapcursor": ["prosemirror-gapcursor@1.4.1", "", { "dependencies": { "prosemirror-keymap": "^1.0.0", "prosemirror-model": "^1.0.0", "prosemirror-state": "^1.0.0", "prosemirror-view": "^1.0.0" } }, "sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw=="], + + "prosemirror-inputrules": ["prosemirror-inputrules@1.5.1", "", { "dependencies": { "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.0.0" } }, "sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw=="], + + "prosemirror-keymap": ["prosemirror-keymap@1.2.3", "", { "dependencies": { "prosemirror-state": "^1.0.0", "w3c-keyname": "^2.2.0" } }, "sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw=="], + + "prosemirror-model": ["prosemirror-model@1.25.12", "", { "dependencies": { "orderedmap": "^2.0.0" } }, "sha512-Ue2gTmXMa7EhpLNhC7J+h4+ykD8ha12K6rrZFFKKJHBForfIStw5gJ6Zrf1mqqAa9NmpmEB4wp9bKmA4eUVjWg=="], + + "prosemirror-schema-basic": ["prosemirror-schema-basic@1.2.5", "", { "dependencies": { "prosemirror-model": "^1.25.0" } }, "sha512-McBWhfgOfThyu3Nltbs8SOUbM4t/h0pxteibaaHd1QR4S+F1t0u7M1ETaCE6/cveFoF+2fowTIBNkJOyeZQjNg=="], + + "prosemirror-schema-list": ["prosemirror-schema-list@1.5.1", "", { "dependencies": { "prosemirror-model": "^1.0.0", "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.7.3" } }, "sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q=="], + + "prosemirror-state": ["prosemirror-state@1.4.4", "", { "dependencies": { "prosemirror-model": "^1.0.0", "prosemirror-transform": "^1.0.0", "prosemirror-view": "^1.27.0" } }, "sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw=="], + + "prosemirror-transform": ["prosemirror-transform@1.12.4", "", { "dependencies": { "prosemirror-model": "^1.21.0" } }, "sha512-2/WuPum3pn+O/Vi2vzpi8210ICUe2kIPXdLYjQ09Pv5DtT5bcKWMJhAKPBwvpPjpp5iOYUVwVEr0gOM1BY1Mgw=="], + + "prosemirror-view": ["prosemirror-view@1.42.8", "", { "dependencies": { "prosemirror-model": "^1.25.12", "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.1.0" } }, "sha512-ftDZjCs9AjAekXmCfJRn2U3IdlRCl0Yc4tZT1/jJWCsz4DiSifEBXtWmpJpw/4f1Rg328uAUQ+u2lCJ0+AVZkw=="], + + "w3c-keyname": ["w3c-keyname@2.2.8", "", {}, "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ=="], + } +} diff --git a/web/package.json b/web/package.json new file mode 100644 index 0000000..680482e --- /dev/null +++ b/web/package.json @@ -0,0 +1,23 @@ +{ + "name": "project-note-editor", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "bun build.ts" + }, + "dependencies": { + "loro-crdt": "1.17.1", + "loro-prosemirror": "0.4.4", + "prosemirror-commands": "1.7.2", + "prosemirror-dropcursor": "^1.8.4", + "prosemirror-gapcursor": "^1.4.1", + "prosemirror-inputrules": "^1.5.1", + "prosemirror-keymap": "1.2.3", + "prosemirror-model": "1.25.12", + "prosemirror-schema-basic": "1.2.5", + "prosemirror-schema-list": "1.5.1", + "prosemirror-state": "1.4.4", + "prosemirror-view": "1.42.8" + } +} diff --git a/web/src/dom.ts b/web/src/dom.ts new file mode 100644 index 0000000..0bb0e05 --- /dev/null +++ b/web/src/dom.ts @@ -0,0 +1,76 @@ +// Shared DOM helpers for the editor chrome: element builder, keycaps, tooltips and +// viewport positioning for floating surfaces (position: fixed, from coordsAtPos). +import type { EditorView } from "prosemirror-view"; + +export const isMac = /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent); +export const MOD = isMac ? "⌘" : "Ctrl"; +export const SHIFT = isMac ? "⇧" : "Shift"; +export const ALT = isMac ? "⌥" : "Alt"; + +/** Creates an element with string attributes and children. Only pass trusted literals as text. */ +export function h<K extends keyof HTMLElementTagNameMap>( + tag: K, + attrs: Record<string, string> = {}, + ...kids: (Node | string)[] +): HTMLElementTagNameMap[K] { + const node = document.createElement(tag); + for (const [name, value] of Object.entries(attrs)) node.setAttribute(name, value); + node.append(...kids); + return node; +} + +/** Mono keycap chips, e.g. keycaps("Ctrl", "K"). Decorative: screen readers get aria-keyshortcuts elsewhere. */ +export function keycaps(...keys: string[]): HTMLSpanElement { + return h( + "span", + { class: "keycaps", "aria-hidden": "true" }, + ...keys.map((key) => h("kbd", { class: "keycap" }, key)), + ); +} + +/** Tooltip shown on hover/focus of its parent button: label, keycaps, optional reason. */ +export function tooltip(label: string, keys: string[], reason?: string): HTMLSpanElement { + const children: (Node | string)[] = [h("span", { class: "tip-label" }, label)]; + if (keys.length) children.push(keycaps(...keys)); + if (reason) children.push(h("span", { class: "tip-reason" }, reason)); + return h("span", { class: "tip", "aria-hidden": "true", role: "presentation" }, ...children); +} + +export interface Box { + top: number; + bottom: number; + left: number; + right: number; +} + +/** Viewport box around the text between two positions (spans lines when needed). */ +export function rangeBox(view: EditorView, from: number, to: number): Box { + const a = view.coordsAtPos(from); + const b = view.coordsAtPos(to); + return { + top: Math.min(a.top, b.top), + bottom: Math.max(a.bottom, b.bottom), + left: Math.min(a.left, b.left), + right: Math.max(a.right, b.right), + }; +} + +const GAP = 8; + +/** + * Positions a fixed element next to a box, centred horizontally and clamped to the + * viewport. "above" flips below when there is no room; "below" flips above at the bottom. + */ +export function placeFloating(el: HTMLElement, box: Box, prefer: "above" | "below"): void { + const width = el.offsetWidth; + const height = el.offsetHeight; + const above = box.top - height - GAP; + const below = box.bottom + GAP; + let top: number; + if (prefer === "above") top = above >= GAP ? above : below; + else top = below + height <= window.innerHeight - GAP ? below : above; + const center = (box.left + box.right) / 2; + const left = Math.min(Math.max(center - width / 2, GAP), window.innerWidth - width - GAP); + el.style.top = `${Math.max(top, GAP)}px`; + el.style.left = `${Math.max(left, GAP)}px`; +} diff --git a/web/src/editing.ts b/web/src/editing.ts new file mode 100644 index 0000000..ed8a0ab --- /dev/null +++ b/web/src/editing.ts @@ -0,0 +1,294 @@ +// Editing behaviour on top of the base schema: block/mark commands, keyboard +// shortcuts, markdown-style input rules, cursors for gaps and drops, and the +// empty-note placeholder. The toolbar (toolbar.ts) drives the same commands. +import { + Fragment, + type Attrs, + type Mark, + type MarkType, + type Node as PMNode, + type NodeType, + type Schema, +} from "prosemirror-model"; +import { Plugin, TextSelection, type Command, type EditorState } from "prosemirror-state"; +import { Decoration, DecorationSet, type EditorView } from "prosemirror-view"; +import { t } from "./i18n"; +import { keymap } from "prosemirror-keymap"; +import { lift, setBlockType, toggleMark, wrapIn } from "prosemirror-commands"; +import { liftListItem, wrapInList } from "prosemirror-schema-list"; +import { + InputRule, + inputRules, + textblockTypeInputRule, + undoInputRule, + wrappingInputRule, +} from "prosemirror-inputrules"; +import { dropCursor } from "prosemirror-dropcursor"; +import { gapCursor } from "prosemirror-gapcursor"; + +/** True when the mark applies at the cursor (stored marks included) or across the selection. */ +export function isMarkActive(state: EditorState, type: MarkType): boolean { + const { from, to, empty, $from } = state.selection; + if (empty) return !!type.isInSet(state.storedMarks || $from.marks()); + return state.doc.rangeHasMark(from, to, type); +} + +/** True when the selection's textblock is of `type` (and matches `attrs`, if given). */ +export function isBlockActive(state: EditorState, type: NodeType, attrs?: Attrs): boolean { + const parent = state.selection.$from.parent; + if (parent.type !== type) return false; + return !attrs || Object.keys(attrs).every((k) => parent.attrs[k] === attrs[k]); +} + +/** Nearest ancestor of the selection matching `match`, with its document position. */ +export function findAncestor( + state: EditorState, + match: (node: PMNode) => boolean, +): { node: PMNode; pos: number } | null { + const { $from } = state.selection; + for (let d = $from.depth; d > 0; d--) { + const node = $from.node(d); + if (match(node)) return { node, pos: $from.before(d) }; + } + return null; +} + +/** + * Input rule for inline marks written with delimiters ("**x**", "*x*", "`x`"). + * `pattern` must end with the closing delimiter; capture group 1 is the marked text. + * The delimiter length is passed explicitly so the text positions are exact. + */ +function markInputRule(pattern: RegExp, markType: MarkType, delimLength: number): InputRule { + return new InputRule(pattern, (state, match, start, end) => { + const content = match[1]; + if (!content) return null; + // Input rules run before the last typed character is inserted, so the closing + // delimiter is one character short in the doc. Positions come from the match start. + const textStart = start + match[0].length - delimLength - content.length; + const textEnd = textStart + content.length; + const openStart = textStart - delimLength; + const tr = state.tr; + tr.delete(textEnd, end); + tr.delete(openStart, textStart); + tr.addMark(openStart, openStart + content.length, markType.create()); + tr.removeStoredMark(markType); + return tr; + }); +} + +/** Range of the mark of `type` that contains `pos` within its textblock, or null. */ +export function markRangeAt( + doc: PMNode, + pos: number, + type: MarkType, +): { from: number; to: number; mark: Mark } | null { + const $pos = doc.resolve(pos); + if (!$pos.parent.inlineContent) return null; + const start = $pos.start(); + let found: { from: number; to: number; mark: Mark } | null = null; + $pos.parent.forEach((child, offset) => { + if (found) return; + const from = start + offset; + const to = from + child.nodeSize; + const mark = type.isInSet(child.marks); + if (mark && from <= pos && pos <= to) found = { from, to, mark }; + }); + return found; +} + +/** Accepts plain URLs (adds https://) and http/mailto/relative links; rejects script-like schemes. */ +export function normalizeHref(raw: string): string | null { + const href = raw.trim(); + if (!href) return null; + // Whitespace and control characters are removed before the check, so "java\tscript:" is caught too. + if (/^(javascript|data|vbscript):/i.test(href.replace(/[\s\x00-\x1f]/g, ""))) return null; + if (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("/") || href.startsWith("#")) return href; + return `https://${href}`; +} + +export interface Editing { + /** Keymap, input rules, drop/gap cursors and placeholder. Insert before baseKeymap. */ + plugins: Plugin[]; + paragraph: Command; + heading(level: number): Command; + codeBlock: Command; + bold: Command; + italic: Command; + inlineCode: Command; + link: Command; + bulletList: Command; + orderedList: Command; + blockquote: Command; + horizontalRule: Command; +} + +export interface EditingHooks { + /** Called by Mod-K and the toolbar/bubble link buttons; the floating UI opens the link popover. */ + requestLink(view: EditorView): void; +} + +export function createEditing(schema: Schema, hooks: EditingHooks): Editing { + const { paragraph, heading, code_block, blockquote, horizontal_rule, bullet_list, ordered_list, list_item } = + schema.nodes; + const { strong, em, code, link: linkMark } = schema.marks; + + // Toggling variants: applying the active block type again returns to a paragraph. + const toParagraph = setBlockType(paragraph); + const toggleBlock = + (type: NodeType, attrs?: Attrs): Command => + (state, dispatch) => + isBlockActive(state, type, attrs) + ? toParagraph(state, dispatch) + : setBlockType(type, attrs)(state, dispatch); + + const toggleList = + (type: NodeType): Command => + (state, dispatch) => { + const list = findAncestor(state, (n) => n.type === bullet_list || n.type === ordered_list); + if (!list) return wrapInList(type)(state, dispatch); + if (list.node.type === type) return liftListItem(list_item)(state, dispatch); + // Switching between bullet and ordered: retype the existing list in place. + if (dispatch) dispatch(state.tr.setNodeMarkup(list.pos, type)); + return true; + }; + + const toggleQuote: Command = (state, dispatch) => + findAncestor(state, (n) => n.type === blockquote) + ? lift(state, dispatch) + : wrapIn(blockquote)(state, dispatch); + + // Opens the link popover for a selection, or for the link the cursor is inside. + const toggleLink: Command = (state, dispatch, view) => { + const { $from, empty } = state.selection; + const insideLink = empty && markRangeAt(state.doc, state.selection.from, linkMark) !== null; + const canLink = !empty && $from.parent.inlineContent && $from.parent.type.allowsMarkType(linkMark); + if (!insideLink && !canLink) return false; + if (dispatch && view) hooks.requestLink(view); + return true; + }; + + const insertRule: Command = (state, dispatch) => { + const { $from } = state.selection; + if ($from.parent.type.spec.code) return false; + if (!dispatch) return true; + const tr = state.tr.replaceSelectionWith(horizontal_rule.create()); + if (!tr.selection.$from.parent.inlineContent) { + // Keep a text position after a trailing rule so the user can keep typing. + const pos = tr.selection.from; + tr.insert(pos, paragraph.create()); + tr.setSelection(TextSelection.create(tr.doc, pos + 1)); + } + dispatch(tr.scrollIntoView()); + return true; + }; + + // "---" on its own line becomes a rule followed by an empty paragraph. + const hrRule = new InputRule(/^---$/, (state, _match, start, end) => { + const $start = state.doc.resolve(start); + const depth = $start.depth; + if (depth < 1 || $start.parent.type.spec.code) return null; + const index = $start.index(depth - 1); + const parent = $start.node(depth - 1); + const replacement = Fragment.from([horizontal_rule.create(), paragraph.create()]); + if (!parent.canReplace(index, index + 1, replacement)) return null; + const before = $start.before(); + const tr = state.tr.replaceWith(before, $start.after(), [horizontal_rule.create(), paragraph.create()]); + tr.setSelection(TextSelection.create(tr.doc, before + horizontal_rule.create().nodeSize + 1)); + return tr; + }); + + // Ctrl/Cmd+Shift+V pastes plain text. The keydown sets a short-lived flag, and the paste + // event the browser fires next reads it. Normal paste keeps basic structure and drops styling. + let plainPasteUntil = 0; + const paste = new Plugin({ + props: { + transformPastedHTML(html) { + return html.replace(/\s(?:style|class)\s*=\s*("[^"]*"|'[^']*')/gi, ""); + }, + handleKeyDown(_view, event) { + if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLowerCase() === "v") { + plainPasteUntil = Date.now() + 1000; + } + return false; + }, + handlePaste(view, event) { + if (Date.now() > plainPasteUntil) return false; + plainPasteUntil = 0; + const text = event.clipboardData?.getData("text/plain"); + if (!text) return false; + view.pasteText(text); + return true; + }, + }, + }); + + const keys = keymap({ + "Mod-Alt-0": toParagraph, + "Mod-Alt-1": toggleBlock(heading, { level: 1 }), + "Mod-Alt-2": toggleBlock(heading, { level: 2 }), + "Mod-Alt-3": toggleBlock(heading, { level: 3 }), + "Mod-Shift-8": toggleList(bullet_list), + "Mod-Shift-9": toggleList(ordered_list), + "Mod-k": toggleLink, + "Mod-e": toggleMark(code), + Backspace: undoInputRule, + }); + + const rules = inputRules({ + rules: [ + textblockTypeInputRule(/^(#{1,3})\s$/, heading, (m) => ({ level: m[1].length })), + textblockTypeInputRule(/^```$/, code_block), + wrappingInputRule(/^\s*([-*])\s$/, bullet_list), + wrappingInputRule( + /^(\d+)\.\s$/, + ordered_list, + (m) => ({ order: Number(m[1]) }), + (m, node) => node.childCount + node.attrs.order === Number(m[1]), + ), + wrappingInputRule(/^\s*>\s$/, blockquote), + markInputRule(/\*\*([^*]+)\*\*$/, strong, 2), + markInputRule(/(?:^|[^*])\*([^*]+)\*$/, em, 1), + markInputRule(/`([^`]+)`$/, code, 1), + hrRule, + ], + }); + + // Shown only while the whole note is one empty paragraph. + const placeholder = new Plugin({ + props: { + decorations(state) { + const { doc } = state; + const first = doc.firstChild; + if (doc.childCount !== 1 || !first || first.type !== paragraph || first.content.size > 0) return null; + return DecorationSet.create(doc, [ + Decoration.node(0, first.nodeSize, { + class: "is-placeholder", + "data-placeholder": t("placeholder"), + }), + ]); + }, + }, + }); + + return { + plugins: [ + paste, + keys, + rules, + dropCursor({ color: "var(--primary)", width: 2 }), + gapCursor(), + placeholder, + ], + paragraph: toParagraph, + heading: (level) => toggleBlock(heading, { level }), + codeBlock: toggleBlock(code_block), + bold: toggleMark(strong), + italic: toggleMark(em), + inlineCode: toggleMark(code), + link: toggleLink, + bulletList: toggleList(bullet_list), + orderedList: toggleList(ordered_list), + blockquote: toggleQuote, + horizontalRule: insertRule, + }; +} diff --git a/web/src/editor.css b/web/src/editor.css new file mode 100644 index 0000000..6b64f63 --- /dev/null +++ b/web/src/editor.css @@ -0,0 +1,800 @@ +@import "prosemirror-view/style/prosemirror.css"; +@import "prosemirror-gapcursor/style/gapcursor.css"; + +/* + * Editor styles, tokens only ("Graphite & Highlighter", see styles.css). Light/dark is + * handled by the theme variables themselves. Fallbacks are the light values. + * Type: Atkinson Hyperlegible Next (UI and body), Atkinson Hyperlegible Mono (meta, keycaps, code). + */ + +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +/* ---- Keycaps (every visible command shows its shortcut as these) ---- */ + +.keycaps { + display: inline-flex; + align-items: center; + gap: 3px; + margin-inline-start: 6px; + vertical-align: middle; +} + +.keycap { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 18px; + height: 18px; + padding: 0 4px; + border: 1px solid var(--border, #e3e5ea); + border-bottom-width: 2px; + border-radius: 6px; + background: var(--keycap-bg, #ffffff); + color: var(--muted-foreground, #5b6270); + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 11px; + font-weight: 500; + line-height: 1; + font-variant-numeric: tabular-nums; +} + +/* ---- Tooltips (toolbar and bubble buttons) ---- */ + +.tip { + position: absolute; + top: calc(100% + 6px); + left: 50%; + z-index: 40; + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 2px; + max-width: 240px; + padding: 4px 6px 4px 8px; + border: 1px solid var(--border, #e3e5ea); + border-radius: 10px; + background: var(--popover, #ffffff); + color: var(--popover-foreground, #16181d); + box-shadow: var(--shadow-float, 0 8px 24px rgb(0 0 0 / 0.12)); + font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); + font-size: 12px; + font-weight: 500; + line-height: 16px; + white-space: nowrap; + pointer-events: none; + opacity: 0; + transform: translate(-50%, -2px); + transition: + opacity 150ms ease-out, + transform 150ms ease-out; +} + +.tip .keycaps { + margin-inline-start: 4px; +} + +.tip-reason { + display: none; + flex-basis: 100%; + color: var(--muted-foreground, #5b6270); + font-weight: 400; +} + +.editor-toolbar-btn:disabled .tip-reason { + display: block; +} + +.editor-toolbar-btn:hover .tip, +.editor-toolbar-btn:focus-visible .tip, +.bubble-btn:hover .tip, +.bubble-btn:focus-visible .tip { + opacity: 1; + transform: translate(-50%, 0); + transition-delay: 300ms; +} + +.bubble .tip { + top: auto; + bottom: calc(100% + 6px); +} + +/* ---- Sync status pill (in the note header's #sync-slot) ---- */ + +#sync-status { + display: inline-flex; + align-items: center; + gap: 6px; + height: 24px; + padding: 0 10px 0 8px; + border: 1px solid var(--border, #e3e5ea); + border-radius: 999px; + background: var(--card, #ffffff); + color: var(--muted-foreground, #5b6270); + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 12px; + font-weight: 400; + line-height: 16px; + white-space: nowrap; + transition: color 150ms ease-out; +} + +#sync-status::before { + content: ""; + width: 6px; + height: 6px; + border-radius: 50%; + background: currentColor; + flex: none; +} + +#sync-status[data-state="saved"] { + color: var(--ok, #1f7a4d); +} + +#sync-status[data-state="saving"] { + color: var(--muted-foreground, #5b6270); +} + +#sync-status[data-state="local"], +#sync-status[data-state="reconnecting"] { + color: var(--warn, #9a5b00); +} + +/* ---- Note header: one row, the formatting toolbar sits inside it ---- */ + +#note-header { + container: note-header / inline-size; +} + +/* ---- Toolbar: compact, icons only, one line (groups drop out when the row is narrow) ---- */ + +.editor-toolbar { + display: flex; + flex: 0 0 auto; + flex-wrap: nowrap; + align-items: center; + gap: 2px; +} + +.editor-toolbar-group { + display: flex; + align-items: center; + gap: 2px; +} + +.editor-toolbar-group + .editor-toolbar-group::before { + content: ""; + width: 1px; + height: 16px; + margin: 0 4px; + background: var(--border, #e3e5ea); +} + +/* Lower-priority commands leave the bar as the header narrows, so the title keeps + at least 8rem. They stay reachable through the slash menu (/) and markdown shortcuts. */ +@container note-header (max-width: 879px) { + .note-crumb-notebook { + display: none; + } +} + +@container note-header (max-width: 779px) { + .editor-toolbar-group[data-group="blocks"] { + display: none; + } +} + +@container note-header (max-width: 619px) { + .editor-toolbar-btn[data-command="h1"], + .editor-toolbar-btn[data-command="h2"], + .editor-toolbar-btn[data-command="h3"] { + display: none; + } +} + +@container note-header (max-width: 559px) { + #sync-status { + gap: 0; + padding: 0 8px; + font-size: 0; + } +} + +@container note-header (max-width: 469px) { + .editor-toolbar-group[data-group="history"] { + display: none; + } +} + +@container note-header (max-width: 419px) { + .editor-toolbar-btn[data-command="paragraph"], + .editor-toolbar-group[data-group="headings"] { + display: none; + } + .note-crumb { + min-width: 6rem; + } +} + +.editor-toolbar-btn { + position: relative; + display: inline-grid; + place-items: center; + width: 28px; + height: 28px; + margin: 0; + padding: 0; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--muted-foreground, #5b6270); + cursor: pointer; + transition: + background-color 150ms ease-out, + color 150ms ease-out; +} + +.editor-toolbar-icon { + display: grid; + place-items: center; +} + +.editor-toolbar-icon svg { + display: block; +} + +.editor-toolbar-btn:hover:not(:disabled) { + background: var(--sidebar-accent, #e3e6eb); + color: var(--foreground, #16181d); +} + +.editor-toolbar-btn[aria-pressed="true"] { + background: var(--active-row, #d9ebd3); + color: var(--active-row-foreground, #1f3d22); +} + +.editor-toolbar-btn:disabled { + opacity: 0.4; + cursor: not-allowed; +} + +.editor-toolbar-btn:focus-visible, +.bubble-btn:focus-visible, +.btn:focus-visible, +.link-input:focus-visible, +.slash-item:focus-visible { + outline: 2px solid var(--ring, #8a5a00); + outline-offset: 2px; +} + +/* ---- Floating surfaces: bubble, link popover, slash menu ---- */ + +.bubble, +.popover { + position: fixed; + z-index: 50; + color: var(--popover-foreground, #16181d); + background: var(--popover, #ffffff); + border: 1px solid var(--border, #e3e5ea); + border-radius: 10px; + box-shadow: var(--shadow-float, 0 8px 24px rgb(0 0 0 / 0.12)); + font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); + font-size: 14px; + line-height: 20px; +} + +.bubble[hidden], +.popover[hidden], +.link-view[hidden], +.link-edit[hidden], +.link-error[hidden] { + display: none; +} + +.bubble { + display: flex; + align-items: center; + gap: 2px; + padding: 4px; +} + +.bubble-btn { + position: relative; + display: inline-grid; + place-items: center; + min-width: 28px; + height: 28px; + margin: 0; + padding: 0 6px; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--foreground, #16181d); + font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); + font-size: 13px; + font-weight: 700; + line-height: 1; + cursor: pointer; + transition: background-color 150ms ease-out; +} + +.bubble-btn:hover:not(:disabled) { + background: var(--sidebar-accent, #e3e6eb); +} + +.bubble-btn[aria-pressed="true"] { + background: var(--active-row, #d9ebd3); +} + +.bubble-btn:disabled { + opacity: 0.4; + cursor: not-allowed; +} + +.bubble-btn[data-command="italic"] .bubble-glyph { + font-style: italic; + font-weight: 500; +} + +.bubble-btn[data-command="bold"] .bubble-glyph { + font-weight: 800; +} + +.bubble-btn[data-command="code"] .bubble-glyph { + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 12px; + font-weight: 500; +} + +.link-popover { + width: min(360px, calc(100vw - 16px)); + box-sizing: border-box; + padding: 10px; +} + +.link-row { + display: flex; + gap: 6px; +} + +.link-input { + flex: 1; + min-width: 0; + height: 32px; + padding: 0 10px; + border: 1px solid var(--border, #e3e5ea); + border-radius: 6px; + background: var(--card, #ffffff); + color: var(--foreground, #16181d); + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 13px; +} + +.link-input[aria-invalid="true"] { + border-color: var(--bad, #b3261e); +} + +.link-input::placeholder { + color: var(--muted-foreground, #5b6270); +} + +.link-error { + margin: 6px 0 0; + color: var(--bad, #b3261e); + font-size: 12px; + line-height: 16px; +} + +.link-actions { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 8px; +} + +.link-view { + display: grid; + gap: 2px; +} + +.link-href { + display: block; + color: var(--link, #8a5a00); + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 13px; + line-height: 18px; + overflow-wrap: anywhere; +} + +.btn { + display: inline-flex; + align-items: center; + gap: 6px; + height: 28px; + padding: 0 10px; + border: 1px solid var(--border, #e3e5ea); + border-radius: 6px; + background: var(--card, #ffffff); + color: var(--foreground, #16181d); + font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); + font-size: 13px; + font-weight: 500; + line-height: 1; + cursor: pointer; + transition: background-color 150ms ease-out; +} + +.btn:hover:not(:disabled) { + background: var(--sidebar-accent, #e3e6eb); +} + +.btn:disabled { + opacity: 0.45; + cursor: not-allowed; +} + +.btn-primary { + border-color: transparent; + background: var(--primary, #f2b600); + color: var(--primary-foreground, #16181d); +} + +.btn-primary:hover:not(:disabled) { + background: var(--primary, #f2b600); + opacity: 0.9; +} + +.btn-primary .keycaps { + margin-inline-start: 2px; +} + +.btn-primary .keycap { + border-color: transparent; + border-bottom-color: color-mix(in srgb, var(--primary-foreground, #16181d) 35%, transparent); + background: transparent; + color: inherit; +} + +.slash-menu { + width: 264px; + max-width: calc(100vw - 16px); + box-sizing: border-box; + padding: 4px; +} + +.slash-list { + max-height: 288px; + overflow-y: auto; +} + +.slash-item { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + min-height: 32px; + padding: 0 8px; + border-radius: 6px; + color: var(--foreground, #16181d); + cursor: pointer; +} + +.slash-item[aria-selected="true"] { + background: var(--active-row, #d9ebd3); +} + +.slash-item .keycaps { + margin-inline-start: 0; +} + +.slash-empty { + padding: 8px; + color: var(--muted-foreground, #5b6270); + font-size: 13px; +} + +.slash-footer { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 2px; + margin-top: 4px; + padding: 6px 8px 2px; + border-top: 1px solid var(--border, #e3e5ea); + color: var(--muted-foreground, #5b6270); + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 11px; + line-height: 16px; +} + +.slash-footer .keycaps { + margin-inline-start: 0; +} + +/* Note suggestions: long titles are cut with an ellipsis */ + +.note-menu .slash-label { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* ---- Editor surface ---- */ + +#editor { + max-width: calc(68ch + 48px); + margin: 0 auto; + padding: 32px 24px 30vh; + box-sizing: border-box; +} + +#editor .ProseMirror { + min-height: 60vh; + max-width: 68ch; + margin: 0 auto; + outline: none; + color: var(--foreground, #16181d); + caret-color: var(--foreground, #16181d); + font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); + font-size: 17px; + line-height: 1.65; + overflow-wrap: break-word; + word-wrap: break-word; + font-variant-ligatures: common-ligatures; +} + +#editor .ProseMirror:focus, +#editor .ProseMirror:focus-visible { + outline: none; +} + +#editor .ProseMirror > * + * { + margin-top: 0.75em; +} + +#editor .ProseMirror ::selection, +#editor .ProseMirror::selection { + background: var(--mark, #ffe08a); + color: var(--foreground, #16181d); +} + +#editor .ProseMirror p { + margin: 0; +} + +/* Placeholder: shown by the placeholder decoration while the note is empty. */ +#editor .ProseMirror p.is-placeholder::before { + content: attr(data-placeholder); + float: left; + height: 0; + color: var(--muted-foreground, #5b6270); + pointer-events: none; +} + +/* Headings: 30/36, 23/30, 19/26, all bold. */ +#editor .ProseMirror h1, +#editor .ProseMirror h2, +#editor .ProseMirror h3 { + margin: 0; + color: var(--foreground, #16181d); + font-weight: 700; + letter-spacing: -0.01em; +} + +#editor .ProseMirror > * + h1, +#editor .ProseMirror > * + h2, +#editor .ProseMirror > * + h3 { + margin-top: 1.4em; +} + +#editor .ProseMirror h1 { + font-size: 30px; + line-height: 36px; +} + +#editor .ProseMirror h2 { + font-size: 23px; + line-height: 30px; +} + +#editor .ProseMirror h3 { + font-size: 19px; + line-height: 26px; +} + +/* Lists */ + +#editor .ProseMirror ul, +#editor .ProseMirror ol { + margin: 0; + padding-left: 1.6em; +} + +#editor .ProseMirror ul { + list-style: disc; +} + +#editor .ProseMirror ol { + list-style: decimal; +} + +#editor .ProseMirror ul ul { + list-style: circle; +} + +#editor .ProseMirror ul ul ul { + list-style: square; +} + +#editor .ProseMirror li { + margin: 0.2em 0; +} + +#editor .ProseMirror li::marker { + color: var(--muted-foreground, #5b6270); +} + +#editor .ProseMirror li > p + p, +#editor .ProseMirror li > * + ul, +#editor .ProseMirror li > * + ol { + margin-top: 0.2em; +} + +/* Quote */ + +#editor .ProseMirror blockquote { + margin: 0; + padding: 2px 0 2px 16px; + border-left: 3px solid var(--border, #e3e5ea); + color: var(--muted-foreground, #5b6270); +} + +/* Code: mono on the background token, hairline border */ + +#editor .ProseMirror code { + padding: 1px 5px; + border: 1px solid var(--border, #e3e5ea); + border-radius: 6px; + background: var(--background, #f5f6f8); + color: var(--foreground, #16181d); + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 0.88em; +} + +#editor .ProseMirror pre { + margin: 0; + padding: 12px 14px; + border: 1px solid var(--border, #e3e5ea); + border-radius: 10px; + background: var(--background, #f5f6f8); + color: var(--foreground, #16181d); + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 14px; + line-height: 22px; + overflow-x: auto; + white-space: pre; +} + +#editor .ProseMirror pre code { + padding: 0; + border: 0; + border-radius: 0; + background: none; + font-size: inherit; +} + +/* Marks: search-style highlight */ + +#editor .ProseMirror mark { + padding: 0 0.1em; + border-radius: 3px; + background: var(--mark, #ffe08a); + color: inherit; +} + +/* Links: accent ink with a quiet underline */ + +#editor .ProseMirror a { + color: var(--link, #8a5a00); + text-decoration-line: underline; + text-decoration-thickness: 1px; + text-decoration-color: color-mix(in srgb, var(--link, #8a5a00) 45%, transparent); + text-underline-offset: 3px; + cursor: pointer; +} + +#editor .ProseMirror a:hover { + text-decoration-color: var(--link, #8a5a00); +} + +/* Note links (href /notes/<id>): a tinted chip, underlined only on hover */ + +#editor .ProseMirror a[href^="/notes/"] { + padding: 0 0.2em; + border-radius: 4px; + background: color-mix(in srgb, var(--link, #8a5a00) 12%, transparent); + text-decoration-line: none; + box-decoration-break: clone; + -webkit-box-decoration-break: clone; +} + +#editor .ProseMirror a[href^="/notes/"]:hover { + text-decoration-line: underline; +} + +/* Horizontal rule */ + +#editor .ProseMirror hr { + margin: 2em 0; + border: 0; + border-top: 1px solid var(--border, #e3e5ea); +} + +#editor .ProseMirror hr.ProseMirror-selectednode { + outline: 2px solid var(--ring, #8a5a00); + outline-offset: 4px; + border-radius: 2px; +} + +/* ---- Remote cursors and selections (loro-prosemirror classes) ---- */ + +.ProseMirror-loro-cursor { + position: relative; + margin-left: -1px; + margin-right: -1px; + /* border-color is set inline per user */ + border-left: 2px solid; + word-break: normal; + pointer-events: none; +} + +/* Name label in the user's color, mono 11px. */ +.ProseMirror-loro-cursor > div { + position: absolute; + top: -1.5em; + left: -2px; + padding: 0 5px; + border-radius: 4px 4px 4px 0; + /* background-color is set inline per user */ + color: #ffffff; + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 11px; + font-weight: 500; + line-height: 16px; + white-space: nowrap; + user-select: none; +} + +.loro-selection { + border-radius: 2px; +} + +@media (prefers-reduced-motion: reduce) { + .editor-toolbar-btn, + .bubble-btn, + .btn, + .tip, + #sync-status { + transition-duration: 0ms !important; + transition-delay: 0ms !important; + } +} + +@media (forced-colors: active) { + .editor-toolbar-btn[aria-pressed="true"], + .bubble-btn[aria-pressed="true"], + .slash-item[aria-selected="true"] { + outline: 2px solid CanvasText; + } +} diff --git a/web/src/editor.ts b/web/src/editor.ts new file mode 100644 index 0000000..ed236cc --- /dev/null +++ b/web/src/editor.ts @@ -0,0 +1,394 @@ +// "loro-crdt/web" is the entry build.ts bundles for every "loro-crdt" import. Its init is the +// default export of loro_wasm.js, the module web/index.js re-exports, so there is one WASM instance. +import { LoroDoc, VersionVector } from "loro-crdt/web"; +import init from "loro-crdt/web/loro_wasm.js"; +import { + CursorEphemeralStore, + LoroEphemeralCursorPlugin, + LoroSyncPlugin, + LoroUndoPlugin, + redo, + undo, +} from "loro-prosemirror"; +import type { CursorUser, LoroDocType } from "loro-prosemirror"; +import { Schema, type NodeSpec } from "prosemirror-model"; +import { EditorState } from "prosemirror-state"; +import { EditorView } from "prosemirror-view"; +import { schema as basicSchema } from "prosemirror-schema-basic"; +import { + addListNodes, + liftListItem, + sinkListItem, + splitListItem, +} from "prosemirror-schema-list"; +import { keymap } from "prosemirror-keymap"; +import { baseKeymap, toggleMark } from "prosemirror-commands"; +import { createEditing } from "./editing"; +import { createFloating } from "./floating"; +import { createNoteLinks } from "./noteLinks"; +import { createToolbar } from "./toolbar"; +import { h } from "./dom"; +import { t, type Key } from "./i18n"; + +// Replaced at build time with the content-hashed name of the WASM file in assets/. +declare const __LORO_WASM_NAME__: string; + +// The WASM ships as its own file so browsers can stream-compile and cache it. It must be +// initialized before the first LoroDoc or ephemeral store exists. +await init({ module_or_path: new URL(`/${__LORO_WASM_NAME__}`, location.origin) }); + +// ---- Wire protocol (must match the Rust server) ---- +const TAG_SYNC_REQ = 0x01; +const TAG_UPDATE = 0x02; +const TAG_EPHEMERAL = 0x03; + +// ---- Schema: basic nodes/marks + lists ---- +// Code blocks keep the fence language (```rust) so markdown round-trips. +const codeBlock: NodeSpec = { + ...basicSchema.spec.nodes.get("code_block")!, + attrs: { language: { default: null } }, + parseDOM: [ + { + tag: "pre", + preserveWhitespace: "full", + getAttrs: (dom) => ({ language: (dom as HTMLElement).dataset.language || null }), + }, + ], + toDOM: (node) => [ + "pre", + node.attrs.language ? { "data-language": node.attrs.language } : {}, + ["code", 0], + ], +}; + +const schema = new Schema({ + nodes: addListNodes( + basicSchema.spec.nodes.update("code_block", codeBlock), + "paragraph block*", + "block", + ), + marks: basicSchema.spec.marks, +}); + +// ---- Per-tab peer identity for cursors ---- +function peerIdentity(): CursorUser { + const key = "project-note-peer"; + let stored: CursorUser | null = null; + try { + const raw = sessionStorage.getItem(key); + if (raw) stored = JSON.parse(raw) as CursorUser; + } catch { + stored = null; + } + if (!stored) { + const n = 1000 + Math.floor(Math.random() * 9000); + const hue = Math.floor(Math.random() * 360); + stored = { name: `user-${n}`, color: `hsl(${hue} 70% 45%)` }; + try { + sessionStorage.setItem(key, JSON.stringify(stored)); + } catch { + // sessionStorage unavailable: identity just lasts for this load + } + } + return stored; +} + +// ---- Document, presence, editor ---- +const mount = document.getElementById("editor"); +if (!mount) throw new Error("#editor element not found"); +const noteId = mount.dataset.noteId ?? ""; +const noteTitle = + mount.dataset.noteTitle?.trim() || + document.querySelector<HTMLElement>("header span.truncate")?.textContent?.trim() || + "Note"; + +const doc = new LoroDoc() as unknown as LoroDocType; +const user = peerIdentity(); +const presence = new CursorEphemeralStore((doc as unknown as LoroDoc).peerIdStr); + +const statusEl = ensureStatusElement(mount); +const liveEl = ensureLiveRegion(); + +// Remote selections are tinted with the peer's color instead of loro's default yellow. +function peerSelection(peer: string) { + const all = presence.getAll() as Record<string, { user?: { color?: string } } | undefined>; + const color = all[peer]?.user?.color ?? "currentColor"; + return { + class: "loro-selection", + "data-peer": peer, + style: `background-color: color-mix(in srgb, ${color} 28%, transparent)`, + }; +} + +// Link commands open the floating popover; the floating UI is created right after. +const editing = createEditing(schema, { requestLink: (v) => floating.openLink(v) }); +const floating = createFloating(schema, editing); +const toolbarPlugin = createToolbar(mount, schema, editing, { undo, redo }); + +const noteLinks = createNoteLinks(schema, { currentNoteId: noteId }); + +const listKeys = keymap({ + Enter: splitListItem(schema.nodes.list_item), + Tab: sinkListItem(schema.nodes.list_item), + "Shift-Tab": liftListItem(schema.nodes.list_item), + "Mod-b": toggleMark(schema.marks.strong), + "Mod-i": toggleMark(schema.marks.em), + "Mod-`": toggleMark(schema.marks.code), +}); + +const state = EditorState.create({ + schema, + plugins: [ + LoroSyncPlugin({ doc }), + LoroUndoPlugin({ doc }), + keymap({ + "Mod-z": undo, + "Mod-y": redo, + "Shift-Mod-z": redo, + }), + ...floating.plugins, + ...noteLinks.plugins, + listKeys, + ...editing.plugins, + keymap(baseKeymap), + toolbarPlugin, + LoroEphemeralCursorPlugin(presence, { user, createSelection: peerSelection }), + ], +}); + +// The editor is created only after the server's state is imported. Creating it on an +// empty doc makes loro-prosemirror write a fresh root that competes with the real one. +let view: EditorView | null = null; +let serverVersion: VersionVector | null = null; + +function maybeCreateEditor() { + if (view || !serverVersion) return; + const ours = (doc as unknown as LoroDoc).oplogVersion(); + const cmp = serverVersion.compare(ours); + if (cmp === undefined || cmp > 0) return; + view = new EditorView(mount!, { + state, + attributes: { + role: "textbox", + "aria-multiline": "true", + "aria-label": noteTitle, + }, + }); +} + +// ---- Transport ---- +const url = `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/notes/${encodeURIComponent(noteId)}/ws`; +const BASE_DELAY = 500; +const MAX_DELAY = 5000; +let socket: WebSocket | null = null; +let retryDelay = BASE_DELAY; +// False until this connection has sent our offline changes. Presence refers to +// containers inside the doc, so it must not reach peers before those changes do. +let presenceReady = false; + +function frame(tag: number, payload: Uint8Array): Uint8Array<ArrayBuffer> { + const out = new Uint8Array(payload.length + 1); + out[0] = tag; + out.set(payload, 1); + return out; +} + +function isOpen(): boolean { + return socket !== null && socket.readyState === WebSocket.OPEN; +} + +function send(tag: number, payload: Uint8Array) { + if (isOpen()) socket!.send(frame(tag, payload)); +} + +// ---- Sync status ---- +// "Saving…" is shown only when local changes stay unsent for more than 1.5s. A change is +// confirmed sent once the socket's buffer is empty and 300ms have passed without edits. +type SyncState = "connecting" | "reconnecting" | "saved" | "saving" | "local"; +const STATUS_KEY: Record<SyncState, Key> = { + connecting: "statusConnecting", + reconnecting: "statusReconnecting", + saved: "statusSaved", + saving: "statusSaving", + local: "statusLocal", +}; + +let connected = false; +let everConnected = false; +let dirty = false; +let savingShown = false; +let savingTimer: ReturnType<typeof setTimeout> | undefined; +let flushTimer: ReturnType<typeof setTimeout> | undefined; + +function currentSyncState(): SyncState { + if (navigator.onLine === false) return "local"; + if (!connected) return everConnected ? "reconnecting" : "connecting"; + return savingShown ? "saving" : "saved"; +} + +function renderStatus() { + const syncState = currentSyncState(); + statusEl.dataset.state = syncState; + statusEl.textContent = t(STATUS_KEY[syncState]); +} + +function markLocalChange() { + if (!dirty) { + dirty = true; + clearTimeout(savingTimer); + savingTimer = setTimeout(() => { + if (dirty) { + savingShown = true; + renderStatus(); + } + }, 1500); + } + clearTimeout(flushTimer); + flushTimer = setTimeout(checkFlushed, 300); +} + +function checkFlushed() { + if (!dirty) return; + if (isOpen() && socket!.bufferedAmount > 0) { + flushTimer = setTimeout(checkFlushed, 100); + return; + } + dirty = false; + clearTimeout(savingTimer); + savingShown = false; + renderStatus(); +} + +function setConnected(value: boolean) { + connected = value; + if (value) everConnected = true; + renderStatus(); +} + +// The pill lives in the note header's #sync-slot (right side, next to the actions menu). +function ensureStatusElement(anchor: HTMLElement): HTMLElement { + let el = document.getElementById("sync-status"); + if (!el) { + el = document.createElement("span"); + el.id = "sync-status"; + const slot = document.getElementById("sync-slot"); + if (slot) slot.append(el); + else anchor.before(el); + } + return el; +} + +// Visually hidden; only offline/online transitions are announced. +function ensureLiveRegion(): HTMLElement { + const el = h("div", { class: "sr-only", role: "status", "aria-live": "polite" }); + document.body.append(el); + return el; +} + +function announce(message: string) { + liveEl.textContent = message; +} + +window.addEventListener("offline", () => { + renderStatus(); + announce(t("announceOffline")); +}); +window.addEventListener("online", () => { + renderStatus(); + announce(t("announceOnline")); +}); + +// Local doc changes: only sent while the socket is open. +// Offline changes are delivered by the SYNC_REQ handshake on reconnect. +(doc as unknown as LoroDoc).subscribeLocalUpdates((bytes: Uint8Array) => { + send(TAG_UPDATE, bytes); + markLocalChange(); +}); + +// Local presence changes: sent while open. +presence.subscribeLocalUpdates((bytes: Uint8Array) => { + if (presenceReady) send(TAG_EPHEMERAL, bytes); +}); + +function handleMessage(data: ArrayBuffer | string) { + if (typeof data === "string") return; + const bytes = new Uint8Array(data); + if (bytes.length === 0) return; + const tag = bytes[0]; + const payload = bytes.subarray(1); + switch (tag) { + case TAG_SYNC_REQ: { + // Peer asks for what we have beyond its version: reply with an update. + const from = VersionVector.decode(payload); + const update = (doc as unknown as LoroDoc).export({ mode: "update", from }); + send(TAG_UPDATE, update); + if (!presenceReady) { + presenceReady = true; + send(TAG_EPHEMERAL, presence.encodeAll()); + } + if (!serverVersion) { + serverVersion = from; + maybeCreateEditor(); + } + break; + } + case TAG_UPDATE: + try { + (doc as unknown as LoroDoc).import(payload); + maybeCreateEditor(); + } catch (err) { + console.error("failed to import update", err); + } + break; + case TAG_EPHEMERAL: + try { + presence.apply(payload); + } catch (err) { + console.error("failed to apply presence", err); + } + break; + default: + console.warn("unknown frame tag", tag); + } +} + +function connect() { + const ws = new WebSocket(url); + ws.binaryType = "arraybuffer"; + socket = ws; + + ws.onopen = () => { + retryDelay = BASE_DELAY; + setConnected(true); + // Handshake: ask the server for what we are missing. + presenceReady = false; + send(TAG_SYNC_REQ, (doc as unknown as LoroDoc).oplogVersion().encode()); + }; + + ws.onmessage = (ev: MessageEvent) => handleMessage(ev.data); + + ws.onerror = () => { + ws.close(); + }; + + ws.onclose = () => { + if (socket === ws) socket = null; + if (detached) return; + setConnected(false); + setTimeout(connect, retryDelay); + retryDelay = Math.min(retryDelay * 2, MAX_DELAY); + }; +} + +// Live search swaps the page content without a reload; it fires `note:detach` first so +// this editor closes its socket instead of syncing a note that is no longer on screen. +let detached = false; +window.addEventListener("note:detach", () => { + detached = true; + socket?.close(); + view?.destroy(); + view = null; +}); + +renderStatus(); +connect(); diff --git a/web/src/floating.ts b/web/src/floating.ts new file mode 100644 index 0000000..2cf4514 --- /dev/null +++ b/web/src/floating.ts @@ -0,0 +1,453 @@ +// Floating editor UI, all plain DOM on <body> and positioned from view.coordsAtPos: +// - selection bubble menu (formatting, shown for a non-empty text selection), +// - link popover (edit mode for Mod-K / buttons, view mode when a link is clicked), +// - slash menu (typing "/" at the start of a block or after a space). +// One ProseMirror plugin keeps them in sync with the editor state. +import type { MarkType, Schema } from "prosemirror-model"; +import { Plugin, TextSelection, type Command, type EditorState } from "prosemirror-state"; +import type { EditorView } from "prosemirror-view"; +import { t } from "./i18n"; +import { isBlockActive, isMarkActive, markRangeAt, normalizeHref, type Editing } from "./editing"; +import { ALT, MOD, SHIFT, h, keycaps, placeFloating, rangeBox, tooltip } from "./dom"; +import { isNoteHref } from "./noteLinks"; + +interface BubbleItem { + id: string; + label: string; + glyph: string; + keys: string[]; + run: Command; + active: (state: EditorState) => boolean; +} + +interface SlashItem { + id: string; + label: string; + /** English words the filter also matches, so "h2" or "list" work in either language. */ + keywords: string; + keys: string[]; + run: Command; +} + +export interface Floating { + plugins: Plugin[]; + /** Opens the link popover for the selection, or for the link the cursor is in. */ + openLink(view: EditorView): void; +} + +interface LinkState { + from: number; + to: number; + mode: "edit" | "view"; + /** Existing href at the range, if any. */ + href: string | null; +} + +/** Position of an open "/query" trigger and what has been typed after the slash. */ +function slashContext(state: EditorState): { from: number; query: string } | null { + const { selection } = state; + if (!(selection instanceof TextSelection) || !selection.empty) return null; + const $from = selection.$from; + if (!$from.parent.isTextblock || $from.parent.type.spec.code) return null; + const before = $from.parent.textBetween(0, $from.parentOffset, undefined, "\n"); + const match = /(?:^|\s)\/([^\s/]*)$/.exec(before); + if (!match) return null; + return { from: $from.pos - match[1].length - 1, query: match[1] }; +} + +function hrefInRange(state: EditorState, from: number, to: number, type: MarkType): string | null { + let href: string | null = null; + state.doc.nodesBetween(from, to, (node) => { + if (href !== null) return false; + const mark = type.isInSet(node.marks); + if (mark) href = String(mark.attrs.href); + return href === null; + }); + return href; +} + +export function createFloating(schema: Schema, editing: Editing): Floating { + const { strong, em, code, link: linkMark } = schema.marks; + const { heading } = schema.nodes; + + let view: EditorView | null = null; + let bubbleDismissed = false; + let link: LinkState | null = null; + let slashFrom: number | null = null; + let slashQuery = ""; + let slashIndex = 0; + let slashFiltered: SlashItem[] = []; + let slashDismissed: number | null = null; + + // ---- Bubble menu ---- + const bubbleItems: BubbleItem[] = [ + { id: "bold", label: t("bold"), glyph: "B", keys: [MOD, "B"], run: editing.bold, active: (s) => isMarkActive(s, strong) }, + { id: "italic", label: t("italic"), glyph: "I", keys: [MOD, "I"], run: editing.italic, active: (s) => isMarkActive(s, em) }, + { id: "code", label: t("inlineCode"), glyph: "</>", keys: [MOD, "E"], run: editing.inlineCode, active: (s) => isMarkActive(s, code) }, + { id: "link", label: t("link"), glyph: "Link", keys: [MOD, "K"], run: editing.link, active: (s) => isMarkActive(s, linkMark) }, + { id: "h1", label: t("heading1"), glyph: "H1", keys: [MOD, ALT, "1"], run: editing.heading(1), active: (s) => isBlockActive(s, heading, { level: 1 }) }, + { id: "h2", label: t("heading2"), glyph: "H2", keys: [MOD, ALT, "2"], run: editing.heading(2), active: (s) => isBlockActive(s, heading, { level: 2 }) }, + { id: "h3", label: t("heading3"), glyph: "H3", keys: [MOD, ALT, "3"], run: editing.heading(3), active: (s) => isBlockActive(s, heading, { level: 3 }) }, + ]; + + const bubble = h("div", { class: "bubble", role: "toolbar", "aria-label": t("bubbleLabel") }); + bubble.hidden = true; + const bubbleButtons = bubbleItems.map((item) => { + const btn = h( + "button", + { type: "button", class: "bubble-btn", "aria-label": item.label, "data-command": item.id }, + h("span", { class: "bubble-glyph", "aria-hidden": "true" }, item.glyph), + tooltip(item.label, item.keys), + ); + btn.addEventListener("click", () => { + if (!view) return; + item.run(view.state, view.dispatch, view); + if (item.id !== "link") view.focus(); + }); + bubble.append(btn); + return { btn, item }; + }); + // Keep the text selection while pressing bubble buttons. + bubble.addEventListener("mousedown", (e) => e.preventDefault()); + + // ---- Link popover (edit and view panels share one element) ---- + const linkPop = h("div", { class: "popover link-popover", role: "dialog", "aria-label": t("linkDialog") }); + linkPop.hidden = true; + + const editPanel = h("form", { class: "link-edit", novalidate: "" }); + const linkInput = h("input", { + type: "text", + class: "link-input", + inputmode: "url", + autocomplete: "off", + autocapitalize: "off", + spellcheck: "false", + placeholder: "https://", + "aria-label": t("linkUrl"), + "aria-describedby": "link-error", + }); + const linkError = h("p", { class: "link-error", id: "link-error", role: "alert" }); + linkError.hidden = true; + const applyBtn = h("button", { type: "submit", class: "btn btn-primary" }, t("apply"), keycaps("↵")); + const editRemove = h("button", { type: "button", class: "btn" }, t("remove")); + const editOpen = h("button", { type: "button", class: "btn" }, t("open")); + editPanel.append( + h("div", { class: "link-row" }, linkInput, applyBtn), + linkError, + h("div", { class: "link-actions" }, editRemove, editOpen), + ); + + // View mode is a small menu: href as its label, then Edit / Remove / Open as menu items. + const viewPanel = h("div", { class: "link-view", role: "menu", "aria-label": t("linkMenu") }); + const linkHref = h("span", { class: "link-href" }); + const viewEdit = h("button", { type: "button", class: "btn", role: "menuitem" }, t("edit")); + const viewRemove = h("button", { type: "button", class: "btn", role: "menuitem" }, t("remove")); + const viewOpen = h("button", { type: "button", class: "btn", role: "menuitem" }, t("open")); + viewPanel.append(linkHref, h("div", { class: "link-actions", role: "none" }, viewEdit, viewRemove, viewOpen)); + + linkPop.append(editPanel, viewPanel); + + function closeLink(restoreFocus: boolean) { + if (!link) return; + link = null; + linkPop.hidden = true; + if (restoreFocus) view?.focus(); + } + + function showLink(v: EditorView, from: number, to: number, mode: "edit" | "view") { + closeSlash(); + const href = hrefInRange(v.state, from, to, linkMark); + link = { from, to, mode, href }; + linkPop.hidden = false; + editPanel.hidden = mode !== "edit"; + viewPanel.hidden = mode !== "view"; + linkError.hidden = true; + linkInput.removeAttribute("aria-invalid"); + linkInput.value = href ?? ""; + linkHref.textContent = href ?? ""; + for (const btn of [editRemove, editOpen, viewRemove, viewOpen]) { + btn.disabled = href === null; + btn.title = href === null ? t("linkNeedsLink") : ""; + } + renderFloating(v); + if (mode === "edit") { + linkInput.focus(); + linkInput.select(); + } else { + viewEdit.focus(); + } + } + + function openLink(v: EditorView) { + const sel = v.state.selection; + const range = sel.empty ? markRangeAt(v.state.doc, sel.from, linkMark) : { from: sel.from, to: sel.to }; + if (!range) return; + showLink(v, range.from, range.to, "edit"); + } + + editPanel.addEventListener("submit", (e) => { + e.preventDefault(); + if (!link || !view) return; + const href = normalizeHref(linkInput.value); + if (!href) { + linkError.textContent = t("linkInvalid"); + linkError.hidden = false; + linkInput.setAttribute("aria-invalid", "true"); + linkInput.focus(); + return; + } + const { from, to } = link; + closeLink(false); + view.dispatch(view.state.tr.removeMark(from, to, linkMark).addMark(from, to, linkMark.create({ href }))); + view.focus(); + }); + + function removeLink() { + if (!link || !view) return; + const { from, to } = link; + closeLink(false); + view.dispatch(view.state.tr.removeMark(from, to, linkMark)); + view.focus(); + } + + function openHref() { + if (!link?.href) return; + // Note links open in this tab; external links keep opening in a new one. + if (isNoteHref(link.href)) { + location.assign(link.href); + return; + } + window.open(link.href, "_blank", "noopener,noreferrer"); + } + + editRemove.addEventListener("click", removeLink); + viewRemove.addEventListener("click", removeLink); + editOpen.addEventListener("click", openHref); + viewOpen.addEventListener("click", openHref); + viewEdit.addEventListener("click", () => { + if (view && link) showLink(view, link.from, link.to, "edit"); + }); + + linkPop.addEventListener("keydown", (e) => { + if (e.key === "Escape") { + e.preventDefault(); + e.stopPropagation(); + closeLink(true); + return; + } + // Arrow keys move between the menu items in view mode. + if ((e.key === "ArrowDown" || e.key === "ArrowUp") && !viewPanel.hidden) { + const items = [viewEdit, viewRemove, viewOpen].filter((b) => !b.disabled); + const index = items.indexOf(document.activeElement as HTMLButtonElement); + const step = e.key === "ArrowDown" ? 1 : -1; + const next = items[(index + step + items.length) % items.length]; + if (next) { + e.preventDefault(); + next.focus(); + } + } + }); + + // ---- Slash menu ---- + const slashItems: SlashItem[] = [ + { id: "text", label: t("paragraph"), keywords: "text paragraph p", keys: [MOD, ALT, "0"], run: editing.paragraph }, + { id: "h1", label: t("heading1"), keywords: "heading title h1", keys: [MOD, ALT, "1"], run: editing.heading(1) }, + { id: "h2", label: t("heading2"), keywords: "heading subtitle h2", keys: [MOD, ALT, "2"], run: editing.heading(2) }, + { id: "h3", label: t("heading3"), keywords: "heading h3", keys: [MOD, ALT, "3"], run: editing.heading(3) }, + { id: "bullets", label: t("bulletList"), keywords: "list ul bullet unordered", keys: [MOD, SHIFT, "8"], run: editing.bulletList }, + { id: "ordered", label: t("numberedList"), keywords: "list ol number ordered", keys: [MOD, SHIFT, "9"], run: editing.orderedList }, + { id: "quote", label: t("quote"), keywords: "blockquote quote", keys: [">"], run: editing.blockquote }, + { id: "codeblock", label: t("codeBlock"), keywords: "code pre fence", keys: ["```"], run: editing.codeBlock }, + { id: "divider", label: t("divider"), keywords: "hr rule line divider", keys: ["---"], run: editing.horizontalRule }, + ]; + + const slashMenu = h("div", { class: "popover slash-menu", role: "presentation" }); + slashMenu.hidden = true; + const slashList = h("div", { class: "slash-list", role: "listbox", "aria-label": t("blockMenu") }); + const slashFooter = h( + "div", + { class: "slash-footer", "aria-hidden": "true" }, + keycaps("↑", "↓"), + ` ${t("navigate")} `, + keycaps("↵"), + ` ${t("insert")} `, + keycaps("Esc"), + ` ${t("close")}`, + ); + slashMenu.append(slashList, slashFooter); + // Keep focus in the editor while clicking menu items. + slashMenu.addEventListener("mousedown", (e) => e.preventDefault()); + + function closeSlash() { + slashFrom = null; + slashMenu.hidden = true; + view?.dom.removeAttribute("aria-activedescendant"); + } + + function renderSlash() { + if (!view || slashFrom === null) return; + const q = slashQuery.toLowerCase(); + slashFiltered = slashItems.filter( + (item) => !q || item.label.toLowerCase().includes(q) || item.keywords.split(" ").some((w) => w.startsWith(q)), + ); + if (slashIndex >= slashFiltered.length) slashIndex = 0; + if (slashFiltered.length === 0) { + slashList.replaceChildren(h("div", { class: "slash-empty", role: "presentation" }, t("noMatches"))); + view.dom.removeAttribute("aria-activedescendant"); + return; + } + slashList.replaceChildren( + ...slashFiltered.map((item, i) => { + const el = h( + "div", + { class: "slash-item", role: "option", id: `slash-opt-${item.id}`, "aria-selected": String(i === slashIndex) }, + h("span", { class: "slash-label" }, item.label), + keycaps(...item.keys), + ); + el.addEventListener("click", () => applySlash(item)); + return el; + }), + ); + const active = slashFiltered[slashIndex]; + view.dom.setAttribute("aria-activedescendant", `slash-opt-${active.id}`); + slashList.querySelector<HTMLElement>(`#slash-opt-${active.id}`)?.scrollIntoView({ block: "nearest" }); + } + + function applySlash(item: SlashItem) { + const v = view; + if (!v || slashFrom === null) return; + const from = slashFrom; + const to = v.state.selection.from; + closeSlash(); + v.dispatch(v.state.tr.delete(from, to)); + item.run(v.state, v.dispatch, v); + v.focus(); + } + + /** Opens, filters or closes the slash menu from the current selection. */ + function syncSlash(v: EditorView) { + const ctx = slashContext(v.state); + if (!ctx) { + slashDismissed = null; + closeSlash(); + return; + } + if (ctx.from === slashDismissed || link) { + closeSlash(); + return; + } + if (ctx.from !== slashFrom || ctx.query !== slashQuery) slashIndex = 0; + slashFrom = ctx.from; + slashQuery = ctx.query; + slashMenu.hidden = false; + renderSlash(); + } + + // ---- Positioning and visibility ---- + function bubbleVisible(v: EditorView): boolean { + const sel = v.state.selection; + return sel instanceof TextSelection && !sel.empty && !v.composing && !bubbleDismissed && link === null; + } + + function renderFloating(v: EditorView) { + view = v; + const state = v.state; + const show = bubbleVisible(v); + bubble.hidden = !show; + if (show) { + for (const { btn, item } of bubbleButtons) { + const on = item.active(state); + btn.dataset.active = String(on); + btn.setAttribute("aria-pressed", String(on)); + btn.disabled = !item.run(state); + } + placeFloating(bubble, rangeBox(v, state.selection.from, state.selection.to), "above"); + } + if (link) { + placeFloating(linkPop, rangeBox(v, link.from, link.to), "above"); + } + if (slashFrom !== null && !slashMenu.hidden) { + placeFloating(slashMenu, rangeBox(v, slashFrom, state.selection.from), "below"); + } + } + + // ---- Keyboard and mouse ---- + const plugin = new Plugin({ + props: { + handleKeyDown(v, e) { + if (slashFrom !== null) { + const n = slashFiltered.length; + if (e.key === "ArrowDown" && n) { + slashIndex = (slashIndex + 1) % n; + renderSlash(); + return true; + } + if (e.key === "ArrowUp" && n) { + slashIndex = (slashIndex - 1 + n) % n; + renderSlash(); + return true; + } + if (e.key === "Enter" && n) { + applySlash(slashFiltered[slashIndex]); + return true; + } + if (e.key === "Escape") { + slashDismissed = slashFrom; + closeSlash(); + return true; + } + } + if (e.key === "Escape" && bubbleVisible(v)) { + bubbleDismissed = true; + renderFloating(v); + return true; + } + return false; + }, + handleClick(v, pos, event) { + const target = event.target as Element | null; + const anchor = target?.closest?.("a"); + if (!anchor) return false; + // Ctrl/Cmd+click navigates to a note (noteLinks.ts), so no popover opens for it. + if ((event.ctrlKey || event.metaKey) && isNoteHref(anchor.getAttribute("href"))) return false; + const range = markRangeAt(v.state.doc, pos, linkMark); + if (range) showLink(v, range.from, range.to, "view"); + return false; + }, + }, + view(v) { + view = v; + document.body.append(bubble, linkPop, slashMenu); + const onViewport = () => { + if (view) renderFloating(view); + }; + const onOutsideDown = (e: MouseEvent) => { + if (link && !linkPop.contains(e.target as Node)) closeLink(false); + }; + window.addEventListener("scroll", onViewport, { capture: true, passive: true }); + window.addEventListener("resize", onViewport); + document.addEventListener("mousedown", onOutsideDown, true); + renderFloating(v); + return { + update(u, prev) { + if (!prev.selection.eq(u.state.selection)) bubbleDismissed = false; + // A popover refers to a fixed range; remote or local edits invalidate it. + if (link && u.state.doc !== prev.doc) closeLink(false); + syncSlash(u); + renderFloating(u); + }, + destroy() { + window.removeEventListener("scroll", onViewport, { capture: true }); + window.removeEventListener("resize", onViewport); + document.removeEventListener("mousedown", onOutsideDown, true); + bubble.remove(); + linkPop.remove(); + slashMenu.remove(); + view = null; + }, + }; + }, + }); + + return { plugins: [plugin], openLink }; +} diff --git a/web/src/i18n.ts b/web/src/i18n.ts new file mode 100644 index 0000000..8e29f18 --- /dev/null +++ b/web/src/i18n.ts @@ -0,0 +1,109 @@ +// Editor UI strings. The language comes from <html lang>; anything but Turkish uses English. + +const en = { + placeholder: "Start writing…", + toolbarLabel: "Formatting", + bubbleLabel: "Text formatting", + blockMenu: "Insert block", + noMatches: "No matches", + navigate: "navigate", + insert: "insert", + close: "close", + unavailable: "Not available here", + undo: "Undo", + redo: "Redo", + paragraph: "Paragraph", + heading1: "Heading 1", + heading2: "Heading 2", + heading3: "Heading 3", + bold: "Bold", + italic: "Italic", + inlineCode: "Inline code", + link: "Link", + bulletList: "Bullet list", + numberedList: "Numbered list", + quote: "Quote", + codeBlock: "Code block", + divider: "Divider", + text: "Text", + linkDialog: "Link", + linkMenu: "Link options", + linkUrl: "Link URL", + linkInvalid: "Enter a valid link, such as example.com", + linkNeedsLink: "Add a link first", + apply: "Apply", + remove: "Remove", + open: "Open", + edit: "Edit", + statusSaved: "Saved", + statusSaving: "Saving…", + statusLocal: "Saved on this device", + statusReconnecting: "Reconnecting…", + statusConnecting: "Connecting…", + announceOffline: "You are offline. Changes stay on this device.", + announceOnline: "Back online.", + pasteAsText: "Paste as plain text", + noteMenu: "Link to a note", + createNote: "Create note “{q}”", + noNotesFound: "No notes found", + untitled: "Untitled", +} as const; + +export type Key = keyof typeof en; + +const tr: Record<Key, string> = { + placeholder: "Yazmaya başla…", + toolbarLabel: "Biçimlendirme", + bubbleLabel: "Metin biçimlendirme", + blockMenu: "Blok ekle", + noMatches: "Eşleşme yok", + navigate: "gezin", + insert: "ekle", + close: "kapat", + unavailable: "Bu alanda kullanılamaz", + undo: "Geri al", + redo: "Yinele", + paragraph: "Metin", + heading1: "Başlık 1", + heading2: "Başlık 2", + heading3: "Başlık 3", + bold: "Kalın", + italic: "İtalik", + inlineCode: "Kod", + link: "Bağlantı", + bulletList: "Madde listesi", + numberedList: "Numaralı liste", + quote: "Alıntı", + codeBlock: "Kod bloğu", + divider: "Ayırıcı", + text: "Metin", + linkDialog: "Bağlantı", + linkMenu: "Bağlantı seçenekleri", + linkUrl: "Bağlantı adresi", + linkInvalid: "Geçerli bir bağlantı girin, ör. example.com", + linkNeedsLink: "Önce bir bağlantı ekleyin", + apply: "Uygula", + remove: "Kaldır", + open: "Aç", + edit: "Düzenle", + statusSaved: "Kaydedildi", + statusSaving: "Kaydediliyor…", + statusLocal: "Bu cihazda kaydedildi", + statusReconnecting: "Yeniden bağlanıyor…", + statusConnecting: "Bağlanıyor…", + announceOffline: "Çevrimdışısınız. Değişiklikler bu cihazda kalır.", + announceOnline: "Yeniden çevrimiçisiniz.", + pasteAsText: "Düz metin olarak yapıştır", + noteMenu: "Nota bağlantısı", + createNote: "“{q}” notunu oluştur", + noNotesFound: "Not bulunamadı", + untitled: "Adsız", +}; + +const lang: "en" | "tr" = (document.documentElement.lang || "en").toLowerCase().startsWith("tr") ? "tr" : "en"; + +/** Looks up a UI string; `{name}` placeholders are filled from `vars`. */ +export function t(key: Key, vars?: Record<string, string>): string { + const text: string = lang === "tr" ? tr[key] : en[key]; + return vars ? text.replace(/\{(\w+)\}/g, (match, name: string) => vars[name] ?? match) : text; +} diff --git a/web/src/noteLinks.ts b/web/src/noteLinks.ts new file mode 100644 index 0000000..4f85eae --- /dev/null +++ b/web/src/noteLinks.ts @@ -0,0 +1,334 @@ +// Note-to-note links. Typing "[[" opens a suggestion menu of note titles. Picking one (or +// "Create note") replaces "[[query" with the title as a link mark whose href is /notes/<id>. +// The menu reuses the slash menu's classes and keyboard model so it looks and behaves the same. +import type { MarkType, Schema } from "prosemirror-model"; +import { Plugin, TextSelection, type EditorState } from "prosemirror-state"; +import type { EditorView } from "prosemirror-view"; +import { t } from "./i18n"; +import { h, keycaps, placeFloating, rangeBox } from "./dom"; + +interface NoteHit { + id: string; + title: string; +} + +type Item = { kind: "note"; hit: NoteHit } | { kind: "create"; title: string }; + +/** "[[" trigger: `from` is the position of the first bracket, `query` the text after it. */ +interface Trigger { + from: number; + query: string; +} + +const SEARCH_DEBOUNCE_MS = 120; + +export interface NoteLinks { + plugins: Plugin[]; +} + +export function isNoteHref(href: string | null | undefined): boolean { + return !!href && href.startsWith("/notes/"); +} + +/** The "[[query" right before the cursor, when the cursor is in a textblock outside code. */ +function triggerAt(state: EditorState, code: MarkType): Trigger | null { + const { selection } = state; + if (!(selection instanceof TextSelection) || !selection.empty) return null; + const $from = selection.$from; + if (!$from.parent.isTextblock || $from.parent.type.spec.code) return null; + if (code.isInSet(state.storedMarks || $from.marks())) return null; + const before = $from.parent.textBetween(0, $from.parentOffset, undefined, "\n"); + // A closing "]]" or a stray bracket ends the match, so the menu closes on its own. + const match = /\[\[([^\[\]\n]*)$/.exec(before); + if (!match) return null; + return { from: $from.pos - match[0].length, query: match[1] }; +} + +function parseHits(data: unknown): NoteHit[] { + if (!Array.isArray(data)) return []; + return data.filter( + (x): x is NoteHit => + typeof x === "object" && x !== null && typeof x.id === "string" && typeof x.title === "string", + ); +} + +async function createNote(title: string): Promise<string> { + const res = await fetch("/notes/quick", { method: "POST", body: new URLSearchParams({ title }) }); + if (!res.ok) throw new Error(`quick ${res.status}`); + const id = (await res.text()).trim(); + if (!id) throw new Error("empty note id"); + return id; +} + +export function createNoteLinks(schema: Schema, opts: { currentNoteId: string }): NoteLinks { + const linkMark = schema.marks.link; + const codeMark = schema.marks.code; + const currentId = opts.currentNoteId; + + let view: EditorView | null = null; + let active: Trigger | null = null; + let dismissedFrom: number | null = null; + let results: NoteHit[] = []; + let loaded = false; + let items: Item[] = []; + let index = 0; + let busy = false; + let fetchTimer: ReturnType<typeof setTimeout> | undefined; + let controller: AbortController | null = null; + + const menu = h("div", { class: "popover slash-menu note-menu", role: "presentation" }); + menu.hidden = true; + const list = h("div", { class: "slash-list", role: "listbox", "aria-label": t("noteMenu") }); + const footer = h( + "div", + { class: "slash-footer", "aria-hidden": "true" }, + keycaps("↑", "↓"), + ` ${t("navigate")} `, + keycaps("↵"), + ` ${t("insert")} `, + keycaps("Esc"), + ` ${t("close")}`, + ); + menu.append(list, footer); + // Keep focus in the editor while clicking menu items. + menu.addEventListener("mousedown", (e) => e.preventDefault()); + + function itemText(item: Item): string { + if (item.kind === "create") return item.title; + return item.hit.title.trim() || t("untitled"); + } + + function itemLabel(item: Item): string { + return item.kind === "create" ? t("createNote", { q: item.title }) : itemText(item); + } + + function buildItems(query: string): Item[] { + const list: Item[] = results.map((hit): Item => ({ kind: "note", hit })); + const q = query.trim(); + const exact = results.some((hit) => hit.title.trim().toLowerCase() === q.toLowerCase()); + if (q && !exact) list.push({ kind: "create", title: q }); + return list; + } + + function abortFetch() { + clearTimeout(fetchTimer); + controller?.abort(); + controller = null; + } + + function close() { + abortFetch(); + active = null; + items = []; + results = []; + loaded = false; + index = 0; + menu.hidden = true; + view?.dom.removeAttribute("aria-activedescendant"); + } + + async function search(query: string) { + const ctrl = new AbortController(); + controller = ctrl; + try { + const res = await fetch(`/notes/titles.json?q=${encodeURIComponent(query)}`, { + signal: ctrl.signal, + headers: { accept: "application/json" }, + }); + if (!res.ok) throw new Error(`titles ${res.status}`); + const data: unknown = await res.json(); + if (ctrl.signal.aborted) return; + results = parseHits(data).filter((hit) => hit.id !== currentId); + } catch (err) { + if (ctrl.signal.aborted) return; + console.error("note search failed", err); + results = []; + } + if (controller === ctrl) controller = null; + loaded = true; + renderList(); + } + + function scheduleSearch(query: string) { + abortFetch(); + loaded = false; + fetchTimer = setTimeout(() => void search(query), SEARCH_DEBOUNCE_MS); + } + + function markActive() { + if (!view) return; + const rows = list.querySelectorAll<HTMLElement>(".slash-item"); + rows.forEach((row, i) => row.setAttribute("aria-selected", String(i === index))); + const row = rows[index]; + if (row) { + view.dom.setAttribute("aria-activedescendant", row.id); + row.scrollIntoView({ block: "nearest" }); + } + } + + function setIndex(i: number) { + index = i; + markActive(); + } + + function renderList() { + if (!view || !active) return; + items = buildItems(active.query); + if (index >= items.length) index = 0; + if (items.length === 0) { + // Only shown once the search for this query has answered; an empty query with no notes lands here. + list.replaceChildren( + ...(loaded ? [h("div", { class: "slash-empty", role: "presentation" }, t("noNotesFound"))] : []), + ); + view.dom.removeAttribute("aria-activedescendant"); + return; + } + list.replaceChildren( + ...items.map((item, i) => { + const el = h( + "div", + { class: "slash-item", role: "option", id: `note-opt-${i}`, "aria-selected": String(i === index) }, + h("span", { class: "slash-label" }, itemLabel(item)), + ); + el.addEventListener("mouseenter", () => setIndex(i)); + el.addEventListener("click", () => pick(item)); + return el; + }), + ); + markActive(); + } + + function place(v: EditorView) { + if (!active) return; + placeFloating(menu, rangeBox(v, active.from, v.state.selection.from), "below"); + } + + /** Replaces [from, to) with the link text, a plain space, and the cursor after it. One transaction. */ + function insertLink(v: EditorView, from: number, to: number, text: string, id: string) { + const tr = v.state.tr.replaceWith(from, to, schema.text(text, [linkMark.create({ href: `/notes/${id}` })])); + const end = from + text.length; + tr.insert(end, schema.text(" ")); + tr.setSelection(TextSelection.create(tr.doc, end + 1)); + tr.setStoredMarks([]); + v.dispatch(tr.scrollIntoView()); + v.focus(); + } + + async function createAndInsert(v: EditorView, from: number, to: number, title: string) { + // The range as it reads now; if the user edits it while the request runs, nothing is inserted. + const before = v.state.doc.textBetween(from, to); + busy = true; + let id: string; + try { + id = await createNote(title); + } catch (err) { + console.error("note create failed", err); + return; + } finally { + busy = false; + } + const cur = view; + if (!cur) return; + const sel = cur.state.selection; + if (!sel.empty || sel.from !== to || cur.state.doc.textBetween(from, to) !== before) return; + insertLink(cur, from, to, title, id); + } + + function pick(item: Item) { + const v = view; + if (!v || !active || busy) return; + const { from } = active; + const to = v.state.selection.from; + if (item.kind === "note") { + insertLink(v, from, to, itemText(item), item.hit.id); + return; + } + void createAndInsert(v, from, to, item.title); + } + + /** Opens, refetches or closes the menu from the current selection. */ + function sync(v: EditorView) { + view = v; + const trig = triggerAt(v.state, codeMark); + if (!trig) { + dismissedFrom = null; + close(); + return; + } + if (trig.from === dismissedFrom) { + close(); + return; + } + const changed = !active || trig.from !== active.from || trig.query !== active.query; + active = trig; + if (changed) { + index = 0; + scheduleSearch(trig.query); + } + menu.hidden = false; + if (changed) renderList(); + place(v); + } + + const plugin = new Plugin({ + props: { + handleKeyDown(v, e) { + if (!active) return false; + const n = items.length; + if (e.key === "Escape") { + dismissedFrom = active.from; + close(); + return true; + } + if (e.key === "ArrowDown" && n) { + setIndex((index + 1) % n); + return true; + } + if (e.key === "ArrowUp" && n) { + setIndex((index - 1 + n) % n); + return true; + } + if ((e.key === "Enter" || e.key === "Tab") && n) { + if (!busy) pick(items[index]); + return true; + } + return false; + }, + // Ctrl/Cmd+click on a note link opens the note in this tab. + handleDOMEvents: { + click(_view, event) { + if (!(event.ctrlKey || event.metaKey)) return false; + const anchor = (event.target as Element | null)?.closest?.("a"); + const href = anchor?.getAttribute("href"); + if (!href || !isNoteHref(href)) return false; + event.preventDefault(); + location.assign(href); + return true; + }, + }, + }, + view(v) { + view = v; + document.body.append(menu); + const onViewport = () => { + if (view) place(view); + }; + window.addEventListener("scroll", onViewport, { capture: true, passive: true }); + window.addEventListener("resize", onViewport); + return { + update(u) { + sync(u); + }, + destroy() { + window.removeEventListener("scroll", onViewport, { capture: true }); + window.removeEventListener("resize", onViewport); + abortFetch(); + menu.remove(); + view = null; + }, + }; + }, + }); + + return { plugins: [plugin] }; +} diff --git a/web/src/toolbar.ts b/web/src/toolbar.ts new file mode 100644 index 0000000..2406627 --- /dev/null +++ b/web/src/toolbar.ts @@ -0,0 +1,279 @@ +// Formatting toolbar: plain DOM, rendered once. A ProseMirror plugin view keeps the +// active/disabled state of every button in sync with the editor. Icons only, with +// keycap tooltips; roving tabindex so the bar is one Tab stop. +import type { Schema } from "prosemirror-model"; +import { Plugin, type Command, type EditorState } from "prosemirror-state"; +import type { EditorView } from "prosemirror-view"; +import { findAncestor, isBlockActive, isMarkActive, type Editing } from "./editing"; +import { t } from "./i18n"; +import { ALT, MOD, SHIFT, h, tooltip } from "./dom"; + + +// Lucide-style glyphs (24x24, stroke based). Static strings, safe for innerHTML. +const ICONS = { + undo: '<path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/>', + redo: '<path d="m15 14 5-5-5-5"/><path d="M20 9H9.5a5.5 5.5 0 0 0 0 11H13"/>', + paragraph: '<path d="M13 4v16"/><path d="M17 4v16"/><path d="M19 4H9.5a4.5 4.5 0 0 0 0 9H13"/>', + h1: '<path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="m17 12 3-2v8"/>', + h2: '<path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1"/>', + h3: '<path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2"/><path d="M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2"/>', + bold: '<path d="M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8"/>', + italic: '<line x1="19" x2="10" y1="4" y2="4"/><line x1="14" x2="5" y1="20" y2="20"/><line x1="15" x2="9" y1="4" y2="20"/>', + code: '<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>', + link: '<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>', + bullets: + '<line x1="8" x2="21" y1="6" y2="6"/><line x1="8" x2="21" y1="12" y2="12"/><line x1="8" x2="21" y1="18" y2="18"/><line x1="3" x2="3.01" y1="6" y2="6"/><line x1="3" x2="3.01" y1="12" y2="12"/><line x1="3" x2="3.01" y1="18" y2="18"/>', + ordered: + '<line x1="10" x2="21" y1="6" y2="6"/><line x1="10" x2="21" y1="12" y2="12"/><line x1="10" x2="21" y1="18" y2="18"/><path d="M4 6h1v4"/><path d="M4 10h2"/><path d="M6 18H4c0-1 2-2 2-3s-1-1.5-2-1"/>', + quote: '<path d="M17 6H3"/><path d="M21 12H8"/><path d="M21 18H8"/><path d="M3 12v6"/>', + codeBlock: '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="m10 9-3 3 3 3"/><path d="m14 15 3-3-3-3"/>', + rule: '<line x1="5" x2="19" y1="12" y2="12"/>', +} as const; + +interface Item { + id: string; + label: string; + keys: string[]; + icon: string; + run: Command; + /** Present for toggles: drives aria-pressed and the active look. */ + isActive?: (state: EditorState) => boolean; +} + +type Entry = Item | "|"; + +function buildItems(schema: Schema, editing: Editing, history: { undo: Command; redo: Command }): Entry[] { + const { paragraph, heading, code_block, blockquote, bullet_list, ordered_list } = schema.nodes; + const { strong, em, code, link } = schema.marks; + const headingItem = (level: 1 | 2 | 3): Item => ({ + id: `h${level}`, + label: t(`heading${level}` as "heading1"), + keys: [MOD, ALT, String(level)], + icon: level === 1 ? ICONS.h1 : level === 2 ? ICONS.h2 : ICONS.h3, + run: editing.heading(level), + isActive: (s) => isBlockActive(s, heading, { level }), + }); + const inList = (type: typeof bullet_list) => (s: EditorState) => findAncestor(s, (n) => n.type === type) !== null; + + return [ + { id: "undo", label: t("undo"), keys: [MOD, "Z"], icon: ICONS.undo, run: history.undo }, + { id: "redo", label: t("redo"), keys: [MOD, SHIFT, "Z"], icon: ICONS.redo, run: history.redo }, + "|", + { + id: "paragraph", + label: t("paragraph"), + keys: [MOD, ALT, "0"], + icon: ICONS.paragraph, + run: editing.paragraph, + isActive: (s) => isBlockActive(s, paragraph), + }, + headingItem(1), + headingItem(2), + headingItem(3), + "|", + { + id: "bold", + label: t("bold"), + keys: [MOD, "B"], + icon: ICONS.bold, + run: editing.bold, + isActive: (s) => isMarkActive(s, strong), + }, + { + id: "italic", + label: t("italic"), + keys: [MOD, "I"], + icon: ICONS.italic, + run: editing.italic, + isActive: (s) => isMarkActive(s, em), + }, + { + id: "code", + label: t("inlineCode"), + keys: [MOD, "E"], + icon: ICONS.code, + run: editing.inlineCode, + isActive: (s) => isMarkActive(s, code), + }, + { + id: "link", + label: t("link"), + keys: [MOD, "K"], + icon: ICONS.link, + run: editing.link, + isActive: (s) => isMarkActive(s, link), + }, + "|", + { + id: "bullets", + label: t("bulletList"), + keys: [MOD, SHIFT, "8"], + icon: ICONS.bullets, + run: editing.bulletList, + isActive: inList(bullet_list), + }, + { + id: "ordered", + label: t("numberedList"), + keys: [MOD, SHIFT, "9"], + icon: ICONS.ordered, + run: editing.orderedList, + isActive: inList(ordered_list), + }, + { + id: "quote", + label: t("quote"), + keys: [">"], + icon: ICONS.quote, + run: editing.blockquote, + isActive: (s) => findAncestor(s, (n) => n.type === blockquote) !== null, + }, + { + id: "codeblock", + label: t("codeBlock"), + keys: ["```"], + icon: ICONS.codeBlock, + run: editing.codeBlock, + isActive: (s) => isBlockActive(s, code_block), + }, + { + id: "rule", + label: t("divider"), + keys: ["---"], + icon: ICONS.rule, + run: editing.horizontalRule, + }, + ]; +} + +// data-group names, in order: one per run of buttons between the separators of buildItems. +const GROUP_NAMES = ["history", "headings", "marks", "blocks"] as const; + +/** + * Creates the toolbar DOM (into #editor-toolbar, or just before `mount`) and returns + * the ProseMirror plugin that drives it. Buttons stay disabled until the view exists. + */ +export function createToolbar( + mount: HTMLElement, + schema: Schema, + editing: Editing, + history: { undo: Command; redo: Command }, +): Plugin { + let el = document.getElementById("editor-toolbar"); + if (!el) { + el = document.createElement("div"); + el.id = "editor-toolbar"; + mount.before(el); + } + el.classList.add("editor-toolbar"); + el.setAttribute("role", "toolbar"); + el.setAttribute("aria-label", t("toolbarLabel")); + + let current: EditorView | null = null; + const buttons: { btn: HTMLButtonElement; item: Item; enabled: boolean }[] = []; + + // Each run of buttons between separators is a group; CSS hides low-priority groups + // and draws the dividers between them (see editor.css, container queries). + let group = h("div", { class: "editor-toolbar-group", "data-group": GROUP_NAMES[0] }); + el.append(group); + let groupIndex = 0; + + for (const entry of buildItems(schema, editing, history)) { + if (entry === "|") { + groupIndex += 1; + group = h("div", { class: "editor-toolbar-group", "data-group": GROUP_NAMES[groupIndex] }); + el.append(group); + continue; + } + const btn = h( + "button", + { + type: "button", + class: "editor-toolbar-btn", + "aria-label": entry.label, + "aria-keyshortcuts": ariaKeys(entry.keys), + "data-command": entry.id, + tabindex: "-1", + }, + h("span", { class: "editor-toolbar-icon", "aria-hidden": "true" }), + tooltip(entry.label, entry.keys, t("unavailable")), + ); + // Static icon paths only (see ICONS above). + btn.querySelector(".editor-toolbar-icon")!.innerHTML = `<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${entry.icon}</svg>`; + btn.disabled = true; + btn.addEventListener("click", () => { + if (!current) return; + entry.run(current.state, current.dispatch, current); + current.focus(); + }); + group.append(btn); + buttons.push({ btn, item: entry, enabled: false }); + } + + // Keep the editor's selection and focus when pressing toolbar buttons. + el.addEventListener("mousedown", (e) => e.preventDefault()); + + // Roving tabindex: arrows, Home and End move among enabled buttons. + const enabledButtons = () => buttons.map((b) => b.btn).filter((b) => !b.disabled); + const setStop = (target: HTMLButtonElement) => { + for (const { btn } of buttons) btn.tabIndex = btn === target ? 0 : -1; + }; + el.addEventListener("keydown", (e) => { + const list = enabledButtons(); + if (!list.length) return; + const index = list.indexOf(document.activeElement as HTMLButtonElement); + let next: HTMLButtonElement | undefined; + if (e.key === "ArrowRight") next = list[(index + 1 + list.length) % list.length]; + else if (e.key === "ArrowLeft") next = list[(index - 1 + list.length) % list.length]; + else if (e.key === "Home") next = list[0]; + else if (e.key === "End") next = list[list.length - 1]; + if (!next) return; + e.preventDefault(); + setStop(next); + next.focus(); + }); + + const sync = (state: EditorState) => { + for (const entry of buttons) { + // Commands without a dispatch only report whether they would apply. + entry.enabled = !!entry.item.run(state); + entry.btn.disabled = !entry.enabled; + if (entry.item.isActive) { + const active = entry.item.isActive(state); + entry.btn.dataset.active = String(active); + entry.btn.setAttribute("aria-pressed", String(active)); + } + } + // Keep one enabled button in the tab order, preferring the last one focused. + const stop = buttons.find((b) => b.btn.tabIndex === 0 && !b.btn.disabled)?.btn ?? enabledButtons()[0]; + if (stop) setStop(stop); + }; + + return new Plugin({ + view(view) { + current = view; + sync(view.state); + return { + update(v) { + sync(v.state); + }, + destroy() { + current = null; + }, + }; + }, + }); +} + +/** Keyboard shortcut in aria-keyshortcuts form, e.g. "Control+B" or "Meta+Shift+8". */ +function ariaKeys(keys: string[]): string { + const names: Record<string, string> = { + Ctrl: "Control", + "⌘": "Meta", + Shift: "Shift", + "⇧": "Shift", + Alt: "Alt", + "⌥": "Alt", + }; + return keys.map((k) => names[k] ?? k).join("+"); +}